aframe-master.js 2.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.AFRAME = f()}})(function(){var define,module,exports;return (function(){function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}return e})()({1:[function(_dereq_,module,exports){
  2. var str = Object.prototype.toString
  3. module.exports = anArray
  4. function anArray(arr) {
  5. return (
  6. arr.BYTES_PER_ELEMENT
  7. && str.call(arr.buffer) === '[object ArrayBuffer]'
  8. || Array.isArray(arr)
  9. )
  10. }
  11. },{}],2:[function(_dereq_,module,exports){
  12. (function (global){
  13. /*
  14. 2017 Julian Garnier
  15. Released under the MIT license
  16. */
  17. var $jscomp={scope:{}};$jscomp.defineProperty="function"==typeof Object.defineProperties?Object.defineProperty:function(e,r,p){if(p.get||p.set)throw new TypeError("ES3 does not support getters and setters.");e!=Array.prototype&&e!=Object.prototype&&(e[r]=p.value)};$jscomp.getGlobal=function(e){return"undefined"!=typeof window&&window===e?e:"undefined"!=typeof global&&null!=global?global:e};$jscomp.global=$jscomp.getGlobal(this);$jscomp.SYMBOL_PREFIX="jscomp_symbol_";
  18. $jscomp.initSymbol=function(){$jscomp.initSymbol=function(){};$jscomp.global.Symbol||($jscomp.global.Symbol=$jscomp.Symbol)};$jscomp.symbolCounter_=0;$jscomp.Symbol=function(e){return $jscomp.SYMBOL_PREFIX+(e||"")+$jscomp.symbolCounter_++};
  19. $jscomp.initSymbolIterator=function(){$jscomp.initSymbol();var e=$jscomp.global.Symbol.iterator;e||(e=$jscomp.global.Symbol.iterator=$jscomp.global.Symbol("iterator"));"function"!=typeof Array.prototype[e]&&$jscomp.defineProperty(Array.prototype,e,{configurable:!0,writable:!0,value:function(){return $jscomp.arrayIterator(this)}});$jscomp.initSymbolIterator=function(){}};$jscomp.arrayIterator=function(e){var r=0;return $jscomp.iteratorPrototype(function(){return r<e.length?{done:!1,value:e[r++]}:{done:!0}})};
  20. $jscomp.iteratorPrototype=function(e){$jscomp.initSymbolIterator();e={next:e};e[$jscomp.global.Symbol.iterator]=function(){return this};return e};$jscomp.array=$jscomp.array||{};$jscomp.iteratorFromArray=function(e,r){$jscomp.initSymbolIterator();e instanceof String&&(e+="");var p=0,m={next:function(){if(p<e.length){var u=p++;return{value:r(u,e[u]),done:!1}}m.next=function(){return{done:!0,value:void 0}};return m.next()}};m[Symbol.iterator]=function(){return m};return m};
  21. $jscomp.polyfill=function(e,r,p,m){if(r){p=$jscomp.global;e=e.split(".");for(m=0;m<e.length-1;m++){var u=e[m];u in p||(p[u]={});p=p[u]}e=e[e.length-1];m=p[e];r=r(m);r!=m&&null!=r&&$jscomp.defineProperty(p,e,{configurable:!0,writable:!0,value:r})}};$jscomp.polyfill("Array.prototype.keys",function(e){return e?e:function(){return $jscomp.iteratorFromArray(this,function(e){return e})}},"es6-impl","es3");var $jscomp$this=this;
  22. (function(e,r){"function"===typeof define&&define.amd?define([],r):"object"===typeof module&&module.exports?module.exports=r():e.anime=r()})(this,function(){function e(a){if(!h.col(a))try{return document.querySelectorAll(a)}catch(c){}}function r(a,c){for(var d=a.length,b=2<=arguments.length?arguments[1]:void 0,f=[],n=0;n<d;n++)if(n in a){var k=a[n];c.call(b,k,n,a)&&f.push(k)}return f}function p(a){return a.reduce(function(a,d){return a.concat(h.arr(d)?p(d):d)},[])}function m(a){if(h.arr(a))return a;
  23. h.str(a)&&(a=e(a)||a);return a instanceof NodeList||a instanceof HTMLCollection?[].slice.call(a):[a]}function u(a,c){return a.some(function(a){return a===c})}function C(a){var c={},d;for(d in a)c[d]=a[d];return c}function D(a,c){var d=C(a),b;for(b in a)d[b]=c.hasOwnProperty(b)?c[b]:a[b];return d}function z(a,c){var d=C(a),b;for(b in c)d[b]=h.und(a[b])?c[b]:a[b];return d}function T(a){a=a.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,function(a,c,d,k){return c+c+d+d+k+k});var c=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(a);
  24. a=parseInt(c[1],16);var d=parseInt(c[2],16),c=parseInt(c[3],16);return"rgba("+a+","+d+","+c+",1)"}function U(a){function c(a,c,b){0>b&&(b+=1);1<b&&--b;return b<1/6?a+6*(c-a)*b:.5>b?c:b<2/3?a+(c-a)*(2/3-b)*6:a}var d=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(a)||/hsla\((\d+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)\)/g.exec(a);a=parseInt(d[1])/360;var b=parseInt(d[2])/100,f=parseInt(d[3])/100,d=d[4]||1;if(0==b)f=b=a=f;else{var n=.5>f?f*(1+b):f+b-f*b,k=2*f-n,f=c(k,n,a+1/3),b=c(k,n,a);a=c(k,n,a-1/3)}return"rgba("+
  25. 255*f+","+255*b+","+255*a+","+d+")"}function y(a){if(a=/([\+\-]?[0-9#\.]+)(%|px|pt|em|rem|in|cm|mm|ex|ch|pc|vw|vh|vmin|vmax|deg|rad|turn)?$/.exec(a))return a[2]}function V(a){if(-1<a.indexOf("translate")||"perspective"===a)return"px";if(-1<a.indexOf("rotate")||-1<a.indexOf("skew"))return"deg"}function I(a,c){return h.fnc(a)?a(c.target,c.id,c.total):a}function E(a,c){if(c in a.style)return getComputedStyle(a).getPropertyValue(c.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase())||"0"}function J(a,c){if(h.dom(a)&&
  26. u(W,c))return"transform";if(h.dom(a)&&(a.getAttribute(c)||h.svg(a)&&a[c]))return"attribute";if(h.dom(a)&&"transform"!==c&&E(a,c))return"css";if(null!=a[c])return"object"}function X(a,c){var d=V(c),d=-1<c.indexOf("scale")?1:0+d;a=a.style.transform;if(!a)return d;for(var b=[],f=[],n=[],k=/(\w+)\((.+?)\)/g;b=k.exec(a);)f.push(b[1]),n.push(b[2]);a=r(n,function(a,b){return f[b]===c});return a.length?a[0]:d}function K(a,c){switch(J(a,c)){case "transform":return X(a,c);case "css":return E(a,c);case "attribute":return a.getAttribute(c)}return a[c]||
  27. 0}function L(a,c){var d=/^(\*=|\+=|-=)/.exec(a);if(!d)return a;var b=y(a)||0;c=parseFloat(c);a=parseFloat(a.replace(d[0],""));switch(d[0][0]){case "+":return c+a+b;case "-":return c-a+b;case "*":return c*a+b}}function F(a,c){return Math.sqrt(Math.pow(c.x-a.x,2)+Math.pow(c.y-a.y,2))}function M(a){a=a.points;for(var c=0,d,b=0;b<a.numberOfItems;b++){var f=a.getItem(b);0<b&&(c+=F(d,f));d=f}return c}function N(a){if(a.getTotalLength)return a.getTotalLength();switch(a.tagName.toLowerCase()){case "circle":return 2*
  28. Math.PI*a.getAttribute("r");case "rect":return 2*a.getAttribute("width")+2*a.getAttribute("height");case "line":return F({x:a.getAttribute("x1"),y:a.getAttribute("y1")},{x:a.getAttribute("x2"),y:a.getAttribute("y2")});case "polyline":return M(a);case "polygon":var c=a.points;return M(a)+F(c.getItem(c.numberOfItems-1),c.getItem(0))}}function Y(a,c){function d(b){b=void 0===b?0:b;return a.el.getPointAtLength(1<=c+b?c+b:0)}var b=d(),f=d(-1),n=d(1);switch(a.property){case "x":return b.x;case "y":return b.y;
  29. case "angle":return 180*Math.atan2(n.y-f.y,n.x-f.x)/Math.PI}}function O(a,c){var d=/-?\d*\.?\d+/g,b;b=h.pth(a)?a.totalLength:a;if(h.col(b))if(h.rgb(b)){var f=/rgb\((\d+,\s*[\d]+,\s*[\d]+)\)/g.exec(b);b=f?"rgba("+f[1]+",1)":b}else b=h.hex(b)?T(b):h.hsl(b)?U(b):void 0;else f=(f=y(b))?b.substr(0,b.length-f.length):b,b=c&&!/\s/g.test(b)?f+c:f;b+="";return{original:b,numbers:b.match(d)?b.match(d).map(Number):[0],strings:h.str(a)||c?b.split(d):[]}}function P(a){a=a?p(h.arr(a)?a.map(m):m(a)):[];return r(a,
  30. function(a,d,b){return b.indexOf(a)===d})}function Z(a){var c=P(a);return c.map(function(a,b){return{target:a,id:b,total:c.length}})}function aa(a,c){var d=C(c);if(h.arr(a)){var b=a.length;2!==b||h.obj(a[0])?h.fnc(c.duration)||(d.duration=c.duration/b):a={value:a}}return m(a).map(function(a,b){b=b?0:c.delay;a=h.obj(a)&&!h.pth(a)?a:{value:a};h.und(a.delay)&&(a.delay=b);return a}).map(function(a){return z(a,d)})}function ba(a,c){var d={},b;for(b in a){var f=I(a[b],c);h.arr(f)&&(f=f.map(function(a){return I(a,
  31. c)}),1===f.length&&(f=f[0]));d[b]=f}d.duration=parseFloat(d.duration);d.delay=parseFloat(d.delay);return d}function ca(a){return h.arr(a)?A.apply(this,a):Q[a]}function da(a,c){var d;return a.tweens.map(function(b){b=ba(b,c);var f=b.value,e=K(c.target,a.name),k=d?d.to.original:e,k=h.arr(f)?f[0]:k,w=L(h.arr(f)?f[1]:f,k),e=y(w)||y(k)||y(e);b.from=O(k,e);b.to=O(w,e);b.start=d?d.end:a.offset;b.end=b.start+b.delay+b.duration;b.easing=ca(b.easing);b.elasticity=(1E3-Math.min(Math.max(b.elasticity,1),999))/
  32. 1E3;b.isPath=h.pth(f);b.isColor=h.col(b.from.original);b.isColor&&(b.round=1);return d=b})}function ea(a,c){return r(p(a.map(function(a){return c.map(function(b){var c=J(a.target,b.name);if(c){var d=da(b,a);b={type:c,property:b.name,animatable:a,tweens:d,duration:d[d.length-1].end,delay:d[0].delay}}else b=void 0;return b})})),function(a){return!h.und(a)})}function R(a,c,d,b){var f="delay"===a;return c.length?(f?Math.min:Math.max).apply(Math,c.map(function(b){return b[a]})):f?b.delay:d.offset+b.delay+
  33. b.duration}function fa(a){var c=D(ga,a),d=D(S,a),b=Z(a.targets),f=[],e=z(c,d),k;for(k in a)e.hasOwnProperty(k)||"targets"===k||f.push({name:k,offset:e.offset,tweens:aa(a[k],d)});a=ea(b,f);return z(c,{children:[],animatables:b,animations:a,duration:R("duration",a,c,d),delay:R("delay",a,c,d)})}function q(a){function c(){return window.Promise&&new Promise(function(a){return p=a})}function d(a){return g.reversed?g.duration-a:a}function b(a){for(var b=0,c={},d=g.animations,f=d.length;b<f;){var e=d[b],
  34. k=e.animatable,h=e.tweens,n=h.length-1,l=h[n];n&&(l=r(h,function(b){return a<b.end})[0]||l);for(var h=Math.min(Math.max(a-l.start-l.delay,0),l.duration)/l.duration,w=isNaN(h)?1:l.easing(h,l.elasticity),h=l.to.strings,p=l.round,n=[],m=void 0,m=l.to.numbers.length,t=0;t<m;t++){var x=void 0,x=l.to.numbers[t],q=l.from.numbers[t],x=l.isPath?Y(l.value,w*x):q+w*(x-q);p&&(l.isColor&&2<t||(x=Math.round(x*p)/p));n.push(x)}if(l=h.length)for(m=h[0],w=0;w<l;w++)p=h[w+1],t=n[w],isNaN(t)||(m=p?m+(t+p):m+(t+" "));
  35. else m=n[0];ha[e.type](k.target,e.property,m,c,k.id);e.currentValue=m;b++}if(b=Object.keys(c).length)for(d=0;d<b;d++)H||(H=E(document.body,"transform")?"transform":"-webkit-transform"),g.animatables[d].target.style[H]=c[d].join(" ");g.currentTime=a;g.progress=a/g.duration*100}function f(a){if(g[a])g[a](g)}function e(){g.remaining&&!0!==g.remaining&&g.remaining--}function k(a){var k=g.duration,n=g.offset,w=n+g.delay,r=g.currentTime,x=g.reversed,q=d(a);if(g.children.length){var u=g.children,v=u.length;
  36. if(q>=g.currentTime)for(var G=0;G<v;G++)u[G].seek(q);else for(;v--;)u[v].seek(q)}if(q>=w||!k)g.began||(g.began=!0,f("begin")),f("run");if(q>n&&q<k)b(q);else if(q<=n&&0!==r&&(b(0),x&&e()),q>=k&&r!==k||!k)b(k),x||e();f("update");a>=k&&(g.remaining?(t=h,"alternate"===g.direction&&(g.reversed=!g.reversed)):(g.pause(),g.completed||(g.completed=!0,f("complete"),"Promise"in window&&(p(),m=c()))),l=0)}a=void 0===a?{}:a;var h,t,l=0,p=null,m=c(),g=fa(a);g.reset=function(){var a=g.direction,c=g.loop;g.currentTime=
  37. 0;g.progress=0;g.paused=!0;g.began=!1;g.completed=!1;g.reversed="reverse"===a;g.remaining="alternate"===a&&1===c?2:c;b(0);for(a=g.children.length;a--;)g.children[a].reset()};g.tick=function(a){h=a;t||(t=h);k((l+h-t)*q.speed)};g.seek=function(a){k(d(a))};g.pause=function(){var a=v.indexOf(g);-1<a&&v.splice(a,1);g.paused=!0};g.play=function(){g.paused&&(g.paused=!1,t=0,l=d(g.currentTime),v.push(g),B||ia())};g.reverse=function(){g.reversed=!g.reversed;t=0;l=d(g.currentTime)};g.restart=function(){g.pause();
  38. g.reset();g.play()};g.finished=m;g.reset();g.autoplay&&g.play();return g}var ga={update:void 0,begin:void 0,run:void 0,complete:void 0,loop:1,direction:"normal",autoplay:!0,offset:0},S={duration:1E3,delay:0,easing:"easeOutElastic",elasticity:500,round:0},W="translateX translateY translateZ rotate rotateX rotateY rotateZ scale scaleX scaleY scaleZ skewX skewY perspective".split(" "),H,h={arr:function(a){return Array.isArray(a)},obj:function(a){return-1<Object.prototype.toString.call(a).indexOf("Object")},
  39. pth:function(a){return h.obj(a)&&a.hasOwnProperty("totalLength")},svg:function(a){return a instanceof SVGElement},dom:function(a){return a.nodeType||h.svg(a)},str:function(a){return"string"===typeof a},fnc:function(a){return"function"===typeof a},und:function(a){return"undefined"===typeof a},hex:function(a){return/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(a)},rgb:function(a){return/^rgb/.test(a)},hsl:function(a){return/^hsl/.test(a)},col:function(a){return h.hex(a)||h.rgb(a)||h.hsl(a)}},A=function(){function a(a,
  40. d,b){return(((1-3*b+3*d)*a+(3*b-6*d))*a+3*d)*a}return function(c,d,b,f){if(0<=c&&1>=c&&0<=b&&1>=b){var e=new Float32Array(11);if(c!==d||b!==f)for(var k=0;11>k;++k)e[k]=a(.1*k,c,b);return function(k){if(c===d&&b===f)return k;if(0===k)return 0;if(1===k)return 1;for(var h=0,l=1;10!==l&&e[l]<=k;++l)h+=.1;--l;var l=h+(k-e[l])/(e[l+1]-e[l])*.1,n=3*(1-3*b+3*c)*l*l+2*(3*b-6*c)*l+3*c;if(.001<=n){for(h=0;4>h;++h){n=3*(1-3*b+3*c)*l*l+2*(3*b-6*c)*l+3*c;if(0===n)break;var m=a(l,c,b)-k,l=l-m/n}k=l}else if(0===
  41. n)k=l;else{var l=h,h=h+.1,g=0;do m=l+(h-l)/2,n=a(m,c,b)-k,0<n?h=m:l=m;while(1e-7<Math.abs(n)&&10>++g);k=m}return a(k,d,f)}}}}(),Q=function(){function a(a,b){return 0===a||1===a?a:-Math.pow(2,10*(a-1))*Math.sin(2*(a-1-b/(2*Math.PI)*Math.asin(1))*Math.PI/b)}var c="Quad Cubic Quart Quint Sine Expo Circ Back Elastic".split(" "),d={In:[[.55,.085,.68,.53],[.55,.055,.675,.19],[.895,.03,.685,.22],[.755,.05,.855,.06],[.47,0,.745,.715],[.95,.05,.795,.035],[.6,.04,.98,.335],[.6,-.28,.735,.045],a],Out:[[.25,
  42. .46,.45,.94],[.215,.61,.355,1],[.165,.84,.44,1],[.23,1,.32,1],[.39,.575,.565,1],[.19,1,.22,1],[.075,.82,.165,1],[.175,.885,.32,1.275],function(b,c){return 1-a(1-b,c)}],InOut:[[.455,.03,.515,.955],[.645,.045,.355,1],[.77,0,.175,1],[.86,0,.07,1],[.445,.05,.55,.95],[1,0,0,1],[.785,.135,.15,.86],[.68,-.55,.265,1.55],function(b,c){return.5>b?a(2*b,c)/2:1-a(-2*b+2,c)/2}]},b={linear:A(.25,.25,.75,.75)},f={},e;for(e in d)f.type=e,d[f.type].forEach(function(a){return function(d,f){b["ease"+a.type+c[f]]=h.fnc(d)?
  43. d:A.apply($jscomp$this,d)}}(f)),f={type:f.type};return b}(),ha={css:function(a,c,d){return a.style[c]=d},attribute:function(a,c,d){return a.setAttribute(c,d)},object:function(a,c,d){return a[c]=d},transform:function(a,c,d,b,f){b[f]||(b[f]=[]);b[f].push(c+"("+d+")")}},v=[],B=0,ia=function(){function a(){B=requestAnimationFrame(c)}function c(c){var b=v.length;if(b){for(var d=0;d<b;)v[d]&&v[d].tick(c),d++;a()}else cancelAnimationFrame(B),B=0}return a}();q.version="2.2.0";q.speed=1;q.running=v;q.remove=
  44. function(a){a=P(a);for(var c=v.length;c--;)for(var d=v[c],b=d.animations,f=b.length;f--;)u(a,b[f].animatable.target)&&(b.splice(f,1),b.length||d.pause())};q.getValue=K;q.path=function(a,c){var d=h.str(a)?e(a)[0]:a,b=c||100;return function(a){return{el:d,property:a,totalLength:N(d)*(b/100)}}};q.setDashoffset=function(a){var c=N(a);a.setAttribute("stroke-dasharray",c);return c};q.bezier=A;q.easings=Q;q.timeline=function(a){var c=q(a);c.pause();c.duration=0;c.add=function(d){c.children.forEach(function(a){a.began=
  45. !0;a.completed=!0});m(d).forEach(function(b){var d=z(b,D(S,a||{}));d.targets=d.targets||a.targets;b=c.duration;var e=d.offset;d.autoplay=!1;d.direction=c.direction;d.offset=h.und(e)?b:L(e,b);c.began=!0;c.completed=!0;c.seek(d.offset);d=q(d);d.began=!0;d.completed=!0;d.duration>b&&(c.duration=d.duration);c.children.push(d)});c.seek(0);c.reset();c.autoplay&&c.restart();return c};return c};q.random=function(a,c){return Math.floor(Math.random()*(c-a+1))+a};return q});
  46. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  47. },{}],3:[function(_dereq_,module,exports){
  48. module.exports = function numtype(num, def) {
  49. return typeof num === 'number'
  50. ? num
  51. : (typeof def === 'number' ? def : 0)
  52. }
  53. },{}],4:[function(_dereq_,module,exports){
  54. 'use strict'
  55. exports.byteLength = byteLength
  56. exports.toByteArray = toByteArray
  57. exports.fromByteArray = fromByteArray
  58. var lookup = []
  59. var revLookup = []
  60. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  61. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  62. for (var i = 0, len = code.length; i < len; ++i) {
  63. lookup[i] = code[i]
  64. revLookup[code.charCodeAt(i)] = i
  65. }
  66. // Support decoding URL-safe base64 strings, as Node.js does.
  67. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  68. revLookup['-'.charCodeAt(0)] = 62
  69. revLookup['_'.charCodeAt(0)] = 63
  70. function placeHoldersCount (b64) {
  71. var len = b64.length
  72. if (len % 4 > 0) {
  73. throw new Error('Invalid string. Length must be a multiple of 4')
  74. }
  75. // the number of equal signs (place holders)
  76. // if there are two placeholders, than the two characters before it
  77. // represent one byte
  78. // if there is only one, then the three characters before it represent 2 bytes
  79. // this is just a cheap hack to not do indexOf twice
  80. return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  81. }
  82. function byteLength (b64) {
  83. // base64 is 4/3 + up to two characters of the original data
  84. return (b64.length * 3 / 4) - placeHoldersCount(b64)
  85. }
  86. function toByteArray (b64) {
  87. var i, l, tmp, placeHolders, arr
  88. var len = b64.length
  89. placeHolders = placeHoldersCount(b64)
  90. arr = new Arr((len * 3 / 4) - placeHolders)
  91. // if there are placeholders, only get up to the last complete 4 chars
  92. l = placeHolders > 0 ? len - 4 : len
  93. var L = 0
  94. for (i = 0; i < l; i += 4) {
  95. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
  96. arr[L++] = (tmp >> 16) & 0xFF
  97. arr[L++] = (tmp >> 8) & 0xFF
  98. arr[L++] = tmp & 0xFF
  99. }
  100. if (placeHolders === 2) {
  101. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
  102. arr[L++] = tmp & 0xFF
  103. } else if (placeHolders === 1) {
  104. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
  105. arr[L++] = (tmp >> 8) & 0xFF
  106. arr[L++] = tmp & 0xFF
  107. }
  108. return arr
  109. }
  110. function tripletToBase64 (num) {
  111. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  112. }
  113. function encodeChunk (uint8, start, end) {
  114. var tmp
  115. var output = []
  116. for (var i = start; i < end; i += 3) {
  117. tmp = ((uint8[i] << 16) & 0xFF0000) + ((uint8[i + 1] << 8) & 0xFF00) + (uint8[i + 2] & 0xFF)
  118. output.push(tripletToBase64(tmp))
  119. }
  120. return output.join('')
  121. }
  122. function fromByteArray (uint8) {
  123. var tmp
  124. var len = uint8.length
  125. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  126. var output = ''
  127. var parts = []
  128. var maxChunkLength = 16383 // must be multiple of 3
  129. // go through the array every three bytes, we'll deal with trailing stuff later
  130. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  131. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  132. }
  133. // pad the end with zeros, but make sure to not forget the extra bytes
  134. if (extraBytes === 1) {
  135. tmp = uint8[len - 1]
  136. output += lookup[tmp >> 2]
  137. output += lookup[(tmp << 4) & 0x3F]
  138. output += '=='
  139. } else if (extraBytes === 2) {
  140. tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
  141. output += lookup[tmp >> 10]
  142. output += lookup[(tmp >> 4) & 0x3F]
  143. output += lookup[(tmp << 2) & 0x3F]
  144. output += '='
  145. }
  146. parts.push(output)
  147. return parts.join('')
  148. }
  149. },{}],5:[function(_dereq_,module,exports){
  150. 'use strict';
  151. // For more information about browser field, check out the browser field at https://github.com/substack/browserify-handbook#browser-field.
  152. module.exports = {
  153. // Create a <link> tag with optional data attributes
  154. createLink: function(href, attributes) {
  155. var head = document.head || document.getElementsByTagName('head')[0];
  156. var link = document.createElement('link');
  157. link.href = href;
  158. link.rel = 'stylesheet';
  159. for (var key in attributes) {
  160. if ( ! attributes.hasOwnProperty(key)) {
  161. continue;
  162. }
  163. var value = attributes[key];
  164. link.setAttribute('data-' + key, value);
  165. }
  166. head.appendChild(link);
  167. },
  168. // Create a <style> tag with optional data attributes
  169. createStyle: function(cssText, attributes) {
  170. var head = document.head || document.getElementsByTagName('head')[0],
  171. style = document.createElement('style');
  172. style.type = 'text/css';
  173. for (var key in attributes) {
  174. if ( ! attributes.hasOwnProperty(key)) {
  175. continue;
  176. }
  177. var value = attributes[key];
  178. style.setAttribute('data-' + key, value);
  179. }
  180. if (style.sheet) { // for jsdom and IE9+
  181. style.innerHTML = cssText;
  182. style.sheet.cssText = cssText;
  183. head.appendChild(style);
  184. } else if (style.styleSheet) { // for IE8 and below
  185. head.appendChild(style);
  186. style.styleSheet.cssText = cssText;
  187. } else { // for Chrome, Firefox, and Safari
  188. style.appendChild(document.createTextNode(cssText));
  189. head.appendChild(style);
  190. }
  191. }
  192. };
  193. },{}],6:[function(_dereq_,module,exports){
  194. var Buffer = _dereq_('buffer').Buffer; // for use with browserify
  195. module.exports = function (a, b) {
  196. if (!Buffer.isBuffer(a)) return undefined;
  197. if (!Buffer.isBuffer(b)) return undefined;
  198. if (typeof a.equals === 'function') return a.equals(b);
  199. if (a.length !== b.length) return false;
  200. for (var i = 0; i < a.length; i++) {
  201. if (a[i] !== b[i]) return false;
  202. }
  203. return true;
  204. };
  205. },{"buffer":7}],7:[function(_dereq_,module,exports){
  206. (function (global){
  207. /*!
  208. * The buffer module from node.js, for the browser.
  209. *
  210. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  211. * @license MIT
  212. */
  213. /* eslint-disable no-proto */
  214. 'use strict'
  215. var base64 = _dereq_('base64-js')
  216. var ieee754 = _dereq_('ieee754')
  217. var isArray = _dereq_('isarray')
  218. exports.Buffer = Buffer
  219. exports.SlowBuffer = SlowBuffer
  220. exports.INSPECT_MAX_BYTES = 50
  221. /**
  222. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  223. * === true Use Uint8Array implementation (fastest)
  224. * === false Use Object implementation (most compatible, even IE6)
  225. *
  226. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  227. * Opera 11.6+, iOS 4.2+.
  228. *
  229. * Due to various browser bugs, sometimes the Object implementation will be used even
  230. * when the browser supports typed arrays.
  231. *
  232. * Note:
  233. *
  234. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  235. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  236. *
  237. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  238. *
  239. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  240. * incorrect length in some situations.
  241. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  242. * get the Object implementation, which is slower but behaves correctly.
  243. */
  244. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  245. ? global.TYPED_ARRAY_SUPPORT
  246. : typedArraySupport()
  247. /*
  248. * Export kMaxLength after typed array support is determined.
  249. */
  250. exports.kMaxLength = kMaxLength()
  251. function typedArraySupport () {
  252. try {
  253. var arr = new Uint8Array(1)
  254. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  255. return arr.foo() === 42 && // typed array instances can be augmented
  256. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  257. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  258. } catch (e) {
  259. return false
  260. }
  261. }
  262. function kMaxLength () {
  263. return Buffer.TYPED_ARRAY_SUPPORT
  264. ? 0x7fffffff
  265. : 0x3fffffff
  266. }
  267. function createBuffer (that, length) {
  268. if (kMaxLength() < length) {
  269. throw new RangeError('Invalid typed array length')
  270. }
  271. if (Buffer.TYPED_ARRAY_SUPPORT) {
  272. // Return an augmented `Uint8Array` instance, for best performance
  273. that = new Uint8Array(length)
  274. that.__proto__ = Buffer.prototype
  275. } else {
  276. // Fallback: Return an object instance of the Buffer class
  277. if (that === null) {
  278. that = new Buffer(length)
  279. }
  280. that.length = length
  281. }
  282. return that
  283. }
  284. /**
  285. * The Buffer constructor returns instances of `Uint8Array` that have their
  286. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  287. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  288. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  289. * returns a single octet.
  290. *
  291. * The `Uint8Array` prototype remains unmodified.
  292. */
  293. function Buffer (arg, encodingOrOffset, length) {
  294. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  295. return new Buffer(arg, encodingOrOffset, length)
  296. }
  297. // Common case.
  298. if (typeof arg === 'number') {
  299. if (typeof encodingOrOffset === 'string') {
  300. throw new Error(
  301. 'If encoding is specified then the first argument must be a string'
  302. )
  303. }
  304. return allocUnsafe(this, arg)
  305. }
  306. return from(this, arg, encodingOrOffset, length)
  307. }
  308. Buffer.poolSize = 8192 // not used by this implementation
  309. // TODO: Legacy, not needed anymore. Remove in next major version.
  310. Buffer._augment = function (arr) {
  311. arr.__proto__ = Buffer.prototype
  312. return arr
  313. }
  314. function from (that, value, encodingOrOffset, length) {
  315. if (typeof value === 'number') {
  316. throw new TypeError('"value" argument must not be a number')
  317. }
  318. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  319. return fromArrayBuffer(that, value, encodingOrOffset, length)
  320. }
  321. if (typeof value === 'string') {
  322. return fromString(that, value, encodingOrOffset)
  323. }
  324. return fromObject(that, value)
  325. }
  326. /**
  327. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  328. * if value is a number.
  329. * Buffer.from(str[, encoding])
  330. * Buffer.from(array)
  331. * Buffer.from(buffer)
  332. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  333. **/
  334. Buffer.from = function (value, encodingOrOffset, length) {
  335. return from(null, value, encodingOrOffset, length)
  336. }
  337. if (Buffer.TYPED_ARRAY_SUPPORT) {
  338. Buffer.prototype.__proto__ = Uint8Array.prototype
  339. Buffer.__proto__ = Uint8Array
  340. if (typeof Symbol !== 'undefined' && Symbol.species &&
  341. Buffer[Symbol.species] === Buffer) {
  342. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  343. Object.defineProperty(Buffer, Symbol.species, {
  344. value: null,
  345. configurable: true
  346. })
  347. }
  348. }
  349. function assertSize (size) {
  350. if (typeof size !== 'number') {
  351. throw new TypeError('"size" argument must be a number')
  352. } else if (size < 0) {
  353. throw new RangeError('"size" argument must not be negative')
  354. }
  355. }
  356. function alloc (that, size, fill, encoding) {
  357. assertSize(size)
  358. if (size <= 0) {
  359. return createBuffer(that, size)
  360. }
  361. if (fill !== undefined) {
  362. // Only pay attention to encoding if it's a string. This
  363. // prevents accidentally sending in a number that would
  364. // be interpretted as a start offset.
  365. return typeof encoding === 'string'
  366. ? createBuffer(that, size).fill(fill, encoding)
  367. : createBuffer(that, size).fill(fill)
  368. }
  369. return createBuffer(that, size)
  370. }
  371. /**
  372. * Creates a new filled Buffer instance.
  373. * alloc(size[, fill[, encoding]])
  374. **/
  375. Buffer.alloc = function (size, fill, encoding) {
  376. return alloc(null, size, fill, encoding)
  377. }
  378. function allocUnsafe (that, size) {
  379. assertSize(size)
  380. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  381. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  382. for (var i = 0; i < size; ++i) {
  383. that[i] = 0
  384. }
  385. }
  386. return that
  387. }
  388. /**
  389. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  390. * */
  391. Buffer.allocUnsafe = function (size) {
  392. return allocUnsafe(null, size)
  393. }
  394. /**
  395. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  396. */
  397. Buffer.allocUnsafeSlow = function (size) {
  398. return allocUnsafe(null, size)
  399. }
  400. function fromString (that, string, encoding) {
  401. if (typeof encoding !== 'string' || encoding === '') {
  402. encoding = 'utf8'
  403. }
  404. if (!Buffer.isEncoding(encoding)) {
  405. throw new TypeError('"encoding" must be a valid string encoding')
  406. }
  407. var length = byteLength(string, encoding) | 0
  408. that = createBuffer(that, length)
  409. var actual = that.write(string, encoding)
  410. if (actual !== length) {
  411. // Writing a hex string, for example, that contains invalid characters will
  412. // cause everything after the first invalid character to be ignored. (e.g.
  413. // 'abxxcd' will be treated as 'ab')
  414. that = that.slice(0, actual)
  415. }
  416. return that
  417. }
  418. function fromArrayLike (that, array) {
  419. var length = array.length < 0 ? 0 : checked(array.length) | 0
  420. that = createBuffer(that, length)
  421. for (var i = 0; i < length; i += 1) {
  422. that[i] = array[i] & 255
  423. }
  424. return that
  425. }
  426. function fromArrayBuffer (that, array, byteOffset, length) {
  427. array.byteLength // this throws if `array` is not a valid ArrayBuffer
  428. if (byteOffset < 0 || array.byteLength < byteOffset) {
  429. throw new RangeError('\'offset\' is out of bounds')
  430. }
  431. if (array.byteLength < byteOffset + (length || 0)) {
  432. throw new RangeError('\'length\' is out of bounds')
  433. }
  434. if (byteOffset === undefined && length === undefined) {
  435. array = new Uint8Array(array)
  436. } else if (length === undefined) {
  437. array = new Uint8Array(array, byteOffset)
  438. } else {
  439. array = new Uint8Array(array, byteOffset, length)
  440. }
  441. if (Buffer.TYPED_ARRAY_SUPPORT) {
  442. // Return an augmented `Uint8Array` instance, for best performance
  443. that = array
  444. that.__proto__ = Buffer.prototype
  445. } else {
  446. // Fallback: Return an object instance of the Buffer class
  447. that = fromArrayLike(that, array)
  448. }
  449. return that
  450. }
  451. function fromObject (that, obj) {
  452. if (Buffer.isBuffer(obj)) {
  453. var len = checked(obj.length) | 0
  454. that = createBuffer(that, len)
  455. if (that.length === 0) {
  456. return that
  457. }
  458. obj.copy(that, 0, 0, len)
  459. return that
  460. }
  461. if (obj) {
  462. if ((typeof ArrayBuffer !== 'undefined' &&
  463. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  464. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  465. return createBuffer(that, 0)
  466. }
  467. return fromArrayLike(that, obj)
  468. }
  469. if (obj.type === 'Buffer' && isArray(obj.data)) {
  470. return fromArrayLike(that, obj.data)
  471. }
  472. }
  473. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  474. }
  475. function checked (length) {
  476. // Note: cannot use `length < kMaxLength()` here because that fails when
  477. // length is NaN (which is otherwise coerced to zero.)
  478. if (length >= kMaxLength()) {
  479. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  480. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  481. }
  482. return length | 0
  483. }
  484. function SlowBuffer (length) {
  485. if (+length != length) { // eslint-disable-line eqeqeq
  486. length = 0
  487. }
  488. return Buffer.alloc(+length)
  489. }
  490. Buffer.isBuffer = function isBuffer (b) {
  491. return !!(b != null && b._isBuffer)
  492. }
  493. Buffer.compare = function compare (a, b) {
  494. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  495. throw new TypeError('Arguments must be Buffers')
  496. }
  497. if (a === b) return 0
  498. var x = a.length
  499. var y = b.length
  500. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  501. if (a[i] !== b[i]) {
  502. x = a[i]
  503. y = b[i]
  504. break
  505. }
  506. }
  507. if (x < y) return -1
  508. if (y < x) return 1
  509. return 0
  510. }
  511. Buffer.isEncoding = function isEncoding (encoding) {
  512. switch (String(encoding).toLowerCase()) {
  513. case 'hex':
  514. case 'utf8':
  515. case 'utf-8':
  516. case 'ascii':
  517. case 'latin1':
  518. case 'binary':
  519. case 'base64':
  520. case 'ucs2':
  521. case 'ucs-2':
  522. case 'utf16le':
  523. case 'utf-16le':
  524. return true
  525. default:
  526. return false
  527. }
  528. }
  529. Buffer.concat = function concat (list, length) {
  530. if (!isArray(list)) {
  531. throw new TypeError('"list" argument must be an Array of Buffers')
  532. }
  533. if (list.length === 0) {
  534. return Buffer.alloc(0)
  535. }
  536. var i
  537. if (length === undefined) {
  538. length = 0
  539. for (i = 0; i < list.length; ++i) {
  540. length += list[i].length
  541. }
  542. }
  543. var buffer = Buffer.allocUnsafe(length)
  544. var pos = 0
  545. for (i = 0; i < list.length; ++i) {
  546. var buf = list[i]
  547. if (!Buffer.isBuffer(buf)) {
  548. throw new TypeError('"list" argument must be an Array of Buffers')
  549. }
  550. buf.copy(buffer, pos)
  551. pos += buf.length
  552. }
  553. return buffer
  554. }
  555. function byteLength (string, encoding) {
  556. if (Buffer.isBuffer(string)) {
  557. return string.length
  558. }
  559. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  560. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  561. return string.byteLength
  562. }
  563. if (typeof string !== 'string') {
  564. string = '' + string
  565. }
  566. var len = string.length
  567. if (len === 0) return 0
  568. // Use a for loop to avoid recursion
  569. var loweredCase = false
  570. for (;;) {
  571. switch (encoding) {
  572. case 'ascii':
  573. case 'latin1':
  574. case 'binary':
  575. return len
  576. case 'utf8':
  577. case 'utf-8':
  578. case undefined:
  579. return utf8ToBytes(string).length
  580. case 'ucs2':
  581. case 'ucs-2':
  582. case 'utf16le':
  583. case 'utf-16le':
  584. return len * 2
  585. case 'hex':
  586. return len >>> 1
  587. case 'base64':
  588. return base64ToBytes(string).length
  589. default:
  590. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  591. encoding = ('' + encoding).toLowerCase()
  592. loweredCase = true
  593. }
  594. }
  595. }
  596. Buffer.byteLength = byteLength
  597. function slowToString (encoding, start, end) {
  598. var loweredCase = false
  599. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  600. // property of a typed array.
  601. // This behaves neither like String nor Uint8Array in that we set start/end
  602. // to their upper/lower bounds if the value passed is out of range.
  603. // undefined is handled specially as per ECMA-262 6th Edition,
  604. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  605. if (start === undefined || start < 0) {
  606. start = 0
  607. }
  608. // Return early if start > this.length. Done here to prevent potential uint32
  609. // coercion fail below.
  610. if (start > this.length) {
  611. return ''
  612. }
  613. if (end === undefined || end > this.length) {
  614. end = this.length
  615. }
  616. if (end <= 0) {
  617. return ''
  618. }
  619. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  620. end >>>= 0
  621. start >>>= 0
  622. if (end <= start) {
  623. return ''
  624. }
  625. if (!encoding) encoding = 'utf8'
  626. while (true) {
  627. switch (encoding) {
  628. case 'hex':
  629. return hexSlice(this, start, end)
  630. case 'utf8':
  631. case 'utf-8':
  632. return utf8Slice(this, start, end)
  633. case 'ascii':
  634. return asciiSlice(this, start, end)
  635. case 'latin1':
  636. case 'binary':
  637. return latin1Slice(this, start, end)
  638. case 'base64':
  639. return base64Slice(this, start, end)
  640. case 'ucs2':
  641. case 'ucs-2':
  642. case 'utf16le':
  643. case 'utf-16le':
  644. return utf16leSlice(this, start, end)
  645. default:
  646. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  647. encoding = (encoding + '').toLowerCase()
  648. loweredCase = true
  649. }
  650. }
  651. }
  652. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  653. // Buffer instances.
  654. Buffer.prototype._isBuffer = true
  655. function swap (b, n, m) {
  656. var i = b[n]
  657. b[n] = b[m]
  658. b[m] = i
  659. }
  660. Buffer.prototype.swap16 = function swap16 () {
  661. var len = this.length
  662. if (len % 2 !== 0) {
  663. throw new RangeError('Buffer size must be a multiple of 16-bits')
  664. }
  665. for (var i = 0; i < len; i += 2) {
  666. swap(this, i, i + 1)
  667. }
  668. return this
  669. }
  670. Buffer.prototype.swap32 = function swap32 () {
  671. var len = this.length
  672. if (len % 4 !== 0) {
  673. throw new RangeError('Buffer size must be a multiple of 32-bits')
  674. }
  675. for (var i = 0; i < len; i += 4) {
  676. swap(this, i, i + 3)
  677. swap(this, i + 1, i + 2)
  678. }
  679. return this
  680. }
  681. Buffer.prototype.swap64 = function swap64 () {
  682. var len = this.length
  683. if (len % 8 !== 0) {
  684. throw new RangeError('Buffer size must be a multiple of 64-bits')
  685. }
  686. for (var i = 0; i < len; i += 8) {
  687. swap(this, i, i + 7)
  688. swap(this, i + 1, i + 6)
  689. swap(this, i + 2, i + 5)
  690. swap(this, i + 3, i + 4)
  691. }
  692. return this
  693. }
  694. Buffer.prototype.toString = function toString () {
  695. var length = this.length | 0
  696. if (length === 0) return ''
  697. if (arguments.length === 0) return utf8Slice(this, 0, length)
  698. return slowToString.apply(this, arguments)
  699. }
  700. Buffer.prototype.equals = function equals (b) {
  701. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  702. if (this === b) return true
  703. return Buffer.compare(this, b) === 0
  704. }
  705. Buffer.prototype.inspect = function inspect () {
  706. var str = ''
  707. var max = exports.INSPECT_MAX_BYTES
  708. if (this.length > 0) {
  709. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  710. if (this.length > max) str += ' ... '
  711. }
  712. return '<Buffer ' + str + '>'
  713. }
  714. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  715. if (!Buffer.isBuffer(target)) {
  716. throw new TypeError('Argument must be a Buffer')
  717. }
  718. if (start === undefined) {
  719. start = 0
  720. }
  721. if (end === undefined) {
  722. end = target ? target.length : 0
  723. }
  724. if (thisStart === undefined) {
  725. thisStart = 0
  726. }
  727. if (thisEnd === undefined) {
  728. thisEnd = this.length
  729. }
  730. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  731. throw new RangeError('out of range index')
  732. }
  733. if (thisStart >= thisEnd && start >= end) {
  734. return 0
  735. }
  736. if (thisStart >= thisEnd) {
  737. return -1
  738. }
  739. if (start >= end) {
  740. return 1
  741. }
  742. start >>>= 0
  743. end >>>= 0
  744. thisStart >>>= 0
  745. thisEnd >>>= 0
  746. if (this === target) return 0
  747. var x = thisEnd - thisStart
  748. var y = end - start
  749. var len = Math.min(x, y)
  750. var thisCopy = this.slice(thisStart, thisEnd)
  751. var targetCopy = target.slice(start, end)
  752. for (var i = 0; i < len; ++i) {
  753. if (thisCopy[i] !== targetCopy[i]) {
  754. x = thisCopy[i]
  755. y = targetCopy[i]
  756. break
  757. }
  758. }
  759. if (x < y) return -1
  760. if (y < x) return 1
  761. return 0
  762. }
  763. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  764. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  765. //
  766. // Arguments:
  767. // - buffer - a Buffer to search
  768. // - val - a string, Buffer, or number
  769. // - byteOffset - an index into `buffer`; will be clamped to an int32
  770. // - encoding - an optional encoding, relevant is val is a string
  771. // - dir - true for indexOf, false for lastIndexOf
  772. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  773. // Empty buffer means no match
  774. if (buffer.length === 0) return -1
  775. // Normalize byteOffset
  776. if (typeof byteOffset === 'string') {
  777. encoding = byteOffset
  778. byteOffset = 0
  779. } else if (byteOffset > 0x7fffffff) {
  780. byteOffset = 0x7fffffff
  781. } else if (byteOffset < -0x80000000) {
  782. byteOffset = -0x80000000
  783. }
  784. byteOffset = +byteOffset // Coerce to Number.
  785. if (isNaN(byteOffset)) {
  786. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  787. byteOffset = dir ? 0 : (buffer.length - 1)
  788. }
  789. // Normalize byteOffset: negative offsets start from the end of the buffer
  790. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  791. if (byteOffset >= buffer.length) {
  792. if (dir) return -1
  793. else byteOffset = buffer.length - 1
  794. } else if (byteOffset < 0) {
  795. if (dir) byteOffset = 0
  796. else return -1
  797. }
  798. // Normalize val
  799. if (typeof val === 'string') {
  800. val = Buffer.from(val, encoding)
  801. }
  802. // Finally, search either indexOf (if dir is true) or lastIndexOf
  803. if (Buffer.isBuffer(val)) {
  804. // Special case: looking for empty string/buffer always fails
  805. if (val.length === 0) {
  806. return -1
  807. }
  808. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  809. } else if (typeof val === 'number') {
  810. val = val & 0xFF // Search for a byte value [0-255]
  811. if (Buffer.TYPED_ARRAY_SUPPORT &&
  812. typeof Uint8Array.prototype.indexOf === 'function') {
  813. if (dir) {
  814. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  815. } else {
  816. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  817. }
  818. }
  819. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  820. }
  821. throw new TypeError('val must be string, number or Buffer')
  822. }
  823. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  824. var indexSize = 1
  825. var arrLength = arr.length
  826. var valLength = val.length
  827. if (encoding !== undefined) {
  828. encoding = String(encoding).toLowerCase()
  829. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  830. encoding === 'utf16le' || encoding === 'utf-16le') {
  831. if (arr.length < 2 || val.length < 2) {
  832. return -1
  833. }
  834. indexSize = 2
  835. arrLength /= 2
  836. valLength /= 2
  837. byteOffset /= 2
  838. }
  839. }
  840. function read (buf, i) {
  841. if (indexSize === 1) {
  842. return buf[i]
  843. } else {
  844. return buf.readUInt16BE(i * indexSize)
  845. }
  846. }
  847. var i
  848. if (dir) {
  849. var foundIndex = -1
  850. for (i = byteOffset; i < arrLength; i++) {
  851. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  852. if (foundIndex === -1) foundIndex = i
  853. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  854. } else {
  855. if (foundIndex !== -1) i -= i - foundIndex
  856. foundIndex = -1
  857. }
  858. }
  859. } else {
  860. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  861. for (i = byteOffset; i >= 0; i--) {
  862. var found = true
  863. for (var j = 0; j < valLength; j++) {
  864. if (read(arr, i + j) !== read(val, j)) {
  865. found = false
  866. break
  867. }
  868. }
  869. if (found) return i
  870. }
  871. }
  872. return -1
  873. }
  874. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  875. return this.indexOf(val, byteOffset, encoding) !== -1
  876. }
  877. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  878. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  879. }
  880. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  881. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  882. }
  883. function hexWrite (buf, string, offset, length) {
  884. offset = Number(offset) || 0
  885. var remaining = buf.length - offset
  886. if (!length) {
  887. length = remaining
  888. } else {
  889. length = Number(length)
  890. if (length > remaining) {
  891. length = remaining
  892. }
  893. }
  894. // must be an even number of digits
  895. var strLen = string.length
  896. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  897. if (length > strLen / 2) {
  898. length = strLen / 2
  899. }
  900. for (var i = 0; i < length; ++i) {
  901. var parsed = parseInt(string.substr(i * 2, 2), 16)
  902. if (isNaN(parsed)) return i
  903. buf[offset + i] = parsed
  904. }
  905. return i
  906. }
  907. function utf8Write (buf, string, offset, length) {
  908. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  909. }
  910. function asciiWrite (buf, string, offset, length) {
  911. return blitBuffer(asciiToBytes(string), buf, offset, length)
  912. }
  913. function latin1Write (buf, string, offset, length) {
  914. return asciiWrite(buf, string, offset, length)
  915. }
  916. function base64Write (buf, string, offset, length) {
  917. return blitBuffer(base64ToBytes(string), buf, offset, length)
  918. }
  919. function ucs2Write (buf, string, offset, length) {
  920. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  921. }
  922. Buffer.prototype.write = function write (string, offset, length, encoding) {
  923. // Buffer#write(string)
  924. if (offset === undefined) {
  925. encoding = 'utf8'
  926. length = this.length
  927. offset = 0
  928. // Buffer#write(string, encoding)
  929. } else if (length === undefined && typeof offset === 'string') {
  930. encoding = offset
  931. length = this.length
  932. offset = 0
  933. // Buffer#write(string, offset[, length][, encoding])
  934. } else if (isFinite(offset)) {
  935. offset = offset | 0
  936. if (isFinite(length)) {
  937. length = length | 0
  938. if (encoding === undefined) encoding = 'utf8'
  939. } else {
  940. encoding = length
  941. length = undefined
  942. }
  943. // legacy write(string, encoding, offset, length) - remove in v0.13
  944. } else {
  945. throw new Error(
  946. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  947. )
  948. }
  949. var remaining = this.length - offset
  950. if (length === undefined || length > remaining) length = remaining
  951. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  952. throw new RangeError('Attempt to write outside buffer bounds')
  953. }
  954. if (!encoding) encoding = 'utf8'
  955. var loweredCase = false
  956. for (;;) {
  957. switch (encoding) {
  958. case 'hex':
  959. return hexWrite(this, string, offset, length)
  960. case 'utf8':
  961. case 'utf-8':
  962. return utf8Write(this, string, offset, length)
  963. case 'ascii':
  964. return asciiWrite(this, string, offset, length)
  965. case 'latin1':
  966. case 'binary':
  967. return latin1Write(this, string, offset, length)
  968. case 'base64':
  969. // Warning: maxLength not taken into account in base64Write
  970. return base64Write(this, string, offset, length)
  971. case 'ucs2':
  972. case 'ucs-2':
  973. case 'utf16le':
  974. case 'utf-16le':
  975. return ucs2Write(this, string, offset, length)
  976. default:
  977. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  978. encoding = ('' + encoding).toLowerCase()
  979. loweredCase = true
  980. }
  981. }
  982. }
  983. Buffer.prototype.toJSON = function toJSON () {
  984. return {
  985. type: 'Buffer',
  986. data: Array.prototype.slice.call(this._arr || this, 0)
  987. }
  988. }
  989. function base64Slice (buf, start, end) {
  990. if (start === 0 && end === buf.length) {
  991. return base64.fromByteArray(buf)
  992. } else {
  993. return base64.fromByteArray(buf.slice(start, end))
  994. }
  995. }
  996. function utf8Slice (buf, start, end) {
  997. end = Math.min(buf.length, end)
  998. var res = []
  999. var i = start
  1000. while (i < end) {
  1001. var firstByte = buf[i]
  1002. var codePoint = null
  1003. var bytesPerSequence = (firstByte > 0xEF) ? 4
  1004. : (firstByte > 0xDF) ? 3
  1005. : (firstByte > 0xBF) ? 2
  1006. : 1
  1007. if (i + bytesPerSequence <= end) {
  1008. var secondByte, thirdByte, fourthByte, tempCodePoint
  1009. switch (bytesPerSequence) {
  1010. case 1:
  1011. if (firstByte < 0x80) {
  1012. codePoint = firstByte
  1013. }
  1014. break
  1015. case 2:
  1016. secondByte = buf[i + 1]
  1017. if ((secondByte & 0xC0) === 0x80) {
  1018. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  1019. if (tempCodePoint > 0x7F) {
  1020. codePoint = tempCodePoint
  1021. }
  1022. }
  1023. break
  1024. case 3:
  1025. secondByte = buf[i + 1]
  1026. thirdByte = buf[i + 2]
  1027. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  1028. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  1029. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  1030. codePoint = tempCodePoint
  1031. }
  1032. }
  1033. break
  1034. case 4:
  1035. secondByte = buf[i + 1]
  1036. thirdByte = buf[i + 2]
  1037. fourthByte = buf[i + 3]
  1038. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  1039. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  1040. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  1041. codePoint = tempCodePoint
  1042. }
  1043. }
  1044. }
  1045. }
  1046. if (codePoint === null) {
  1047. // we did not generate a valid codePoint so insert a
  1048. // replacement char (U+FFFD) and advance only 1 byte
  1049. codePoint = 0xFFFD
  1050. bytesPerSequence = 1
  1051. } else if (codePoint > 0xFFFF) {
  1052. // encode to utf16 (surrogate pair dance)
  1053. codePoint -= 0x10000
  1054. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  1055. codePoint = 0xDC00 | codePoint & 0x3FF
  1056. }
  1057. res.push(codePoint)
  1058. i += bytesPerSequence
  1059. }
  1060. return decodeCodePointsArray(res)
  1061. }
  1062. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  1063. // the lowest limit is Chrome, with 0x10000 args.
  1064. // We go 1 magnitude less, for safety
  1065. var MAX_ARGUMENTS_LENGTH = 0x1000
  1066. function decodeCodePointsArray (codePoints) {
  1067. var len = codePoints.length
  1068. if (len <= MAX_ARGUMENTS_LENGTH) {
  1069. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  1070. }
  1071. // Decode in chunks to avoid "call stack size exceeded".
  1072. var res = ''
  1073. var i = 0
  1074. while (i < len) {
  1075. res += String.fromCharCode.apply(
  1076. String,
  1077. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1078. )
  1079. }
  1080. return res
  1081. }
  1082. function asciiSlice (buf, start, end) {
  1083. var ret = ''
  1084. end = Math.min(buf.length, end)
  1085. for (var i = start; i < end; ++i) {
  1086. ret += String.fromCharCode(buf[i] & 0x7F)
  1087. }
  1088. return ret
  1089. }
  1090. function latin1Slice (buf, start, end) {
  1091. var ret = ''
  1092. end = Math.min(buf.length, end)
  1093. for (var i = start; i < end; ++i) {
  1094. ret += String.fromCharCode(buf[i])
  1095. }
  1096. return ret
  1097. }
  1098. function hexSlice (buf, start, end) {
  1099. var len = buf.length
  1100. if (!start || start < 0) start = 0
  1101. if (!end || end < 0 || end > len) end = len
  1102. var out = ''
  1103. for (var i = start; i < end; ++i) {
  1104. out += toHex(buf[i])
  1105. }
  1106. return out
  1107. }
  1108. function utf16leSlice (buf, start, end) {
  1109. var bytes = buf.slice(start, end)
  1110. var res = ''
  1111. for (var i = 0; i < bytes.length; i += 2) {
  1112. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  1113. }
  1114. return res
  1115. }
  1116. Buffer.prototype.slice = function slice (start, end) {
  1117. var len = this.length
  1118. start = ~~start
  1119. end = end === undefined ? len : ~~end
  1120. if (start < 0) {
  1121. start += len
  1122. if (start < 0) start = 0
  1123. } else if (start > len) {
  1124. start = len
  1125. }
  1126. if (end < 0) {
  1127. end += len
  1128. if (end < 0) end = 0
  1129. } else if (end > len) {
  1130. end = len
  1131. }
  1132. if (end < start) end = start
  1133. var newBuf
  1134. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1135. newBuf = this.subarray(start, end)
  1136. newBuf.__proto__ = Buffer.prototype
  1137. } else {
  1138. var sliceLen = end - start
  1139. newBuf = new Buffer(sliceLen, undefined)
  1140. for (var i = 0; i < sliceLen; ++i) {
  1141. newBuf[i] = this[i + start]
  1142. }
  1143. }
  1144. return newBuf
  1145. }
  1146. /*
  1147. * Need to make sure that buffer isn't trying to write out of bounds.
  1148. */
  1149. function checkOffset (offset, ext, length) {
  1150. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1151. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1152. }
  1153. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  1154. offset = offset | 0
  1155. byteLength = byteLength | 0
  1156. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1157. var val = this[offset]
  1158. var mul = 1
  1159. var i = 0
  1160. while (++i < byteLength && (mul *= 0x100)) {
  1161. val += this[offset + i] * mul
  1162. }
  1163. return val
  1164. }
  1165. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  1166. offset = offset | 0
  1167. byteLength = byteLength | 0
  1168. if (!noAssert) {
  1169. checkOffset(offset, byteLength, this.length)
  1170. }
  1171. var val = this[offset + --byteLength]
  1172. var mul = 1
  1173. while (byteLength > 0 && (mul *= 0x100)) {
  1174. val += this[offset + --byteLength] * mul
  1175. }
  1176. return val
  1177. }
  1178. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1179. if (!noAssert) checkOffset(offset, 1, this.length)
  1180. return this[offset]
  1181. }
  1182. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1183. if (!noAssert) checkOffset(offset, 2, this.length)
  1184. return this[offset] | (this[offset + 1] << 8)
  1185. }
  1186. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1187. if (!noAssert) checkOffset(offset, 2, this.length)
  1188. return (this[offset] << 8) | this[offset + 1]
  1189. }
  1190. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1191. if (!noAssert) checkOffset(offset, 4, this.length)
  1192. return ((this[offset]) |
  1193. (this[offset + 1] << 8) |
  1194. (this[offset + 2] << 16)) +
  1195. (this[offset + 3] * 0x1000000)
  1196. }
  1197. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1198. if (!noAssert) checkOffset(offset, 4, this.length)
  1199. return (this[offset] * 0x1000000) +
  1200. ((this[offset + 1] << 16) |
  1201. (this[offset + 2] << 8) |
  1202. this[offset + 3])
  1203. }
  1204. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1205. offset = offset | 0
  1206. byteLength = byteLength | 0
  1207. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1208. var val = this[offset]
  1209. var mul = 1
  1210. var i = 0
  1211. while (++i < byteLength && (mul *= 0x100)) {
  1212. val += this[offset + i] * mul
  1213. }
  1214. mul *= 0x80
  1215. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1216. return val
  1217. }
  1218. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1219. offset = offset | 0
  1220. byteLength = byteLength | 0
  1221. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1222. var i = byteLength
  1223. var mul = 1
  1224. var val = this[offset + --i]
  1225. while (i > 0 && (mul *= 0x100)) {
  1226. val += this[offset + --i] * mul
  1227. }
  1228. mul *= 0x80
  1229. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1230. return val
  1231. }
  1232. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1233. if (!noAssert) checkOffset(offset, 1, this.length)
  1234. if (!(this[offset] & 0x80)) return (this[offset])
  1235. return ((0xff - this[offset] + 1) * -1)
  1236. }
  1237. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1238. if (!noAssert) checkOffset(offset, 2, this.length)
  1239. var val = this[offset] | (this[offset + 1] << 8)
  1240. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1241. }
  1242. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1243. if (!noAssert) checkOffset(offset, 2, this.length)
  1244. var val = this[offset + 1] | (this[offset] << 8)
  1245. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1246. }
  1247. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1248. if (!noAssert) checkOffset(offset, 4, this.length)
  1249. return (this[offset]) |
  1250. (this[offset + 1] << 8) |
  1251. (this[offset + 2] << 16) |
  1252. (this[offset + 3] << 24)
  1253. }
  1254. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1255. if (!noAssert) checkOffset(offset, 4, this.length)
  1256. return (this[offset] << 24) |
  1257. (this[offset + 1] << 16) |
  1258. (this[offset + 2] << 8) |
  1259. (this[offset + 3])
  1260. }
  1261. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1262. if (!noAssert) checkOffset(offset, 4, this.length)
  1263. return ieee754.read(this, offset, true, 23, 4)
  1264. }
  1265. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1266. if (!noAssert) checkOffset(offset, 4, this.length)
  1267. return ieee754.read(this, offset, false, 23, 4)
  1268. }
  1269. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1270. if (!noAssert) checkOffset(offset, 8, this.length)
  1271. return ieee754.read(this, offset, true, 52, 8)
  1272. }
  1273. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1274. if (!noAssert) checkOffset(offset, 8, this.length)
  1275. return ieee754.read(this, offset, false, 52, 8)
  1276. }
  1277. function checkInt (buf, value, offset, ext, max, min) {
  1278. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1279. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1280. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1281. }
  1282. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  1283. value = +value
  1284. offset = offset | 0
  1285. byteLength = byteLength | 0
  1286. if (!noAssert) {
  1287. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1288. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1289. }
  1290. var mul = 1
  1291. var i = 0
  1292. this[offset] = value & 0xFF
  1293. while (++i < byteLength && (mul *= 0x100)) {
  1294. this[offset + i] = (value / mul) & 0xFF
  1295. }
  1296. return offset + byteLength
  1297. }
  1298. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  1299. value = +value
  1300. offset = offset | 0
  1301. byteLength = byteLength | 0
  1302. if (!noAssert) {
  1303. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1304. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1305. }
  1306. var i = byteLength - 1
  1307. var mul = 1
  1308. this[offset + i] = value & 0xFF
  1309. while (--i >= 0 && (mul *= 0x100)) {
  1310. this[offset + i] = (value / mul) & 0xFF
  1311. }
  1312. return offset + byteLength
  1313. }
  1314. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  1315. value = +value
  1316. offset = offset | 0
  1317. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  1318. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1319. this[offset] = (value & 0xff)
  1320. return offset + 1
  1321. }
  1322. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  1323. if (value < 0) value = 0xffff + value + 1
  1324. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  1325. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  1326. (littleEndian ? i : 1 - i) * 8
  1327. }
  1328. }
  1329. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  1330. value = +value
  1331. offset = offset | 0
  1332. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1333. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1334. this[offset] = (value & 0xff)
  1335. this[offset + 1] = (value >>> 8)
  1336. } else {
  1337. objectWriteUInt16(this, value, offset, true)
  1338. }
  1339. return offset + 2
  1340. }
  1341. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  1342. value = +value
  1343. offset = offset | 0
  1344. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1345. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1346. this[offset] = (value >>> 8)
  1347. this[offset + 1] = (value & 0xff)
  1348. } else {
  1349. objectWriteUInt16(this, value, offset, false)
  1350. }
  1351. return offset + 2
  1352. }
  1353. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1354. if (value < 0) value = 0xffffffff + value + 1
  1355. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  1356. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  1357. }
  1358. }
  1359. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1360. value = +value
  1361. offset = offset | 0
  1362. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1363. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1364. this[offset + 3] = (value >>> 24)
  1365. this[offset + 2] = (value >>> 16)
  1366. this[offset + 1] = (value >>> 8)
  1367. this[offset] = (value & 0xff)
  1368. } else {
  1369. objectWriteUInt32(this, value, offset, true)
  1370. }
  1371. return offset + 4
  1372. }
  1373. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1374. value = +value
  1375. offset = offset | 0
  1376. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1377. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1378. this[offset] = (value >>> 24)
  1379. this[offset + 1] = (value >>> 16)
  1380. this[offset + 2] = (value >>> 8)
  1381. this[offset + 3] = (value & 0xff)
  1382. } else {
  1383. objectWriteUInt32(this, value, offset, false)
  1384. }
  1385. return offset + 4
  1386. }
  1387. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1388. value = +value
  1389. offset = offset | 0
  1390. if (!noAssert) {
  1391. var limit = Math.pow(2, 8 * byteLength - 1)
  1392. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1393. }
  1394. var i = 0
  1395. var mul = 1
  1396. var sub = 0
  1397. this[offset] = value & 0xFF
  1398. while (++i < byteLength && (mul *= 0x100)) {
  1399. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1400. sub = 1
  1401. }
  1402. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1403. }
  1404. return offset + byteLength
  1405. }
  1406. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1407. value = +value
  1408. offset = offset | 0
  1409. if (!noAssert) {
  1410. var limit = Math.pow(2, 8 * byteLength - 1)
  1411. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1412. }
  1413. var i = byteLength - 1
  1414. var mul = 1
  1415. var sub = 0
  1416. this[offset + i] = value & 0xFF
  1417. while (--i >= 0 && (mul *= 0x100)) {
  1418. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1419. sub = 1
  1420. }
  1421. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1422. }
  1423. return offset + byteLength
  1424. }
  1425. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1426. value = +value
  1427. offset = offset | 0
  1428. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  1429. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1430. if (value < 0) value = 0xff + value + 1
  1431. this[offset] = (value & 0xff)
  1432. return offset + 1
  1433. }
  1434. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1435. value = +value
  1436. offset = offset | 0
  1437. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1438. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1439. this[offset] = (value & 0xff)
  1440. this[offset + 1] = (value >>> 8)
  1441. } else {
  1442. objectWriteUInt16(this, value, offset, true)
  1443. }
  1444. return offset + 2
  1445. }
  1446. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1447. value = +value
  1448. offset = offset | 0
  1449. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1450. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1451. this[offset] = (value >>> 8)
  1452. this[offset + 1] = (value & 0xff)
  1453. } else {
  1454. objectWriteUInt16(this, value, offset, false)
  1455. }
  1456. return offset + 2
  1457. }
  1458. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1459. value = +value
  1460. offset = offset | 0
  1461. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1462. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1463. this[offset] = (value & 0xff)
  1464. this[offset + 1] = (value >>> 8)
  1465. this[offset + 2] = (value >>> 16)
  1466. this[offset + 3] = (value >>> 24)
  1467. } else {
  1468. objectWriteUInt32(this, value, offset, true)
  1469. }
  1470. return offset + 4
  1471. }
  1472. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  1473. value = +value
  1474. offset = offset | 0
  1475. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1476. if (value < 0) value = 0xffffffff + value + 1
  1477. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1478. this[offset] = (value >>> 24)
  1479. this[offset + 1] = (value >>> 16)
  1480. this[offset + 2] = (value >>> 8)
  1481. this[offset + 3] = (value & 0xff)
  1482. } else {
  1483. objectWriteUInt32(this, value, offset, false)
  1484. }
  1485. return offset + 4
  1486. }
  1487. function checkIEEE754 (buf, value, offset, ext, max, min) {
  1488. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1489. if (offset < 0) throw new RangeError('Index out of range')
  1490. }
  1491. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  1492. if (!noAssert) {
  1493. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  1494. }
  1495. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  1496. return offset + 4
  1497. }
  1498. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  1499. return writeFloat(this, value, offset, true, noAssert)
  1500. }
  1501. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  1502. return writeFloat(this, value, offset, false, noAssert)
  1503. }
  1504. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  1505. if (!noAssert) {
  1506. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  1507. }
  1508. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  1509. return offset + 8
  1510. }
  1511. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  1512. return writeDouble(this, value, offset, true, noAssert)
  1513. }
  1514. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  1515. return writeDouble(this, value, offset, false, noAssert)
  1516. }
  1517. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  1518. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  1519. if (!start) start = 0
  1520. if (!end && end !== 0) end = this.length
  1521. if (targetStart >= target.length) targetStart = target.length
  1522. if (!targetStart) targetStart = 0
  1523. if (end > 0 && end < start) end = start
  1524. // Copy 0 bytes; we're done
  1525. if (end === start) return 0
  1526. if (target.length === 0 || this.length === 0) return 0
  1527. // Fatal error conditions
  1528. if (targetStart < 0) {
  1529. throw new RangeError('targetStart out of bounds')
  1530. }
  1531. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  1532. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  1533. // Are we oob?
  1534. if (end > this.length) end = this.length
  1535. if (target.length - targetStart < end - start) {
  1536. end = target.length - targetStart + start
  1537. }
  1538. var len = end - start
  1539. var i
  1540. if (this === target && start < targetStart && targetStart < end) {
  1541. // descending copy from end
  1542. for (i = len - 1; i >= 0; --i) {
  1543. target[i + targetStart] = this[i + start]
  1544. }
  1545. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  1546. // ascending copy from start
  1547. for (i = 0; i < len; ++i) {
  1548. target[i + targetStart] = this[i + start]
  1549. }
  1550. } else {
  1551. Uint8Array.prototype.set.call(
  1552. target,
  1553. this.subarray(start, start + len),
  1554. targetStart
  1555. )
  1556. }
  1557. return len
  1558. }
  1559. // Usage:
  1560. // buffer.fill(number[, offset[, end]])
  1561. // buffer.fill(buffer[, offset[, end]])
  1562. // buffer.fill(string[, offset[, end]][, encoding])
  1563. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  1564. // Handle string cases:
  1565. if (typeof val === 'string') {
  1566. if (typeof start === 'string') {
  1567. encoding = start
  1568. start = 0
  1569. end = this.length
  1570. } else if (typeof end === 'string') {
  1571. encoding = end
  1572. end = this.length
  1573. }
  1574. if (val.length === 1) {
  1575. var code = val.charCodeAt(0)
  1576. if (code < 256) {
  1577. val = code
  1578. }
  1579. }
  1580. if (encoding !== undefined && typeof encoding !== 'string') {
  1581. throw new TypeError('encoding must be a string')
  1582. }
  1583. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  1584. throw new TypeError('Unknown encoding: ' + encoding)
  1585. }
  1586. } else if (typeof val === 'number') {
  1587. val = val & 255
  1588. }
  1589. // Invalid ranges are not set to a default, so can range check early.
  1590. if (start < 0 || this.length < start || this.length < end) {
  1591. throw new RangeError('Out of range index')
  1592. }
  1593. if (end <= start) {
  1594. return this
  1595. }
  1596. start = start >>> 0
  1597. end = end === undefined ? this.length : end >>> 0
  1598. if (!val) val = 0
  1599. var i
  1600. if (typeof val === 'number') {
  1601. for (i = start; i < end; ++i) {
  1602. this[i] = val
  1603. }
  1604. } else {
  1605. var bytes = Buffer.isBuffer(val)
  1606. ? val
  1607. : utf8ToBytes(new Buffer(val, encoding).toString())
  1608. var len = bytes.length
  1609. for (i = 0; i < end - start; ++i) {
  1610. this[i + start] = bytes[i % len]
  1611. }
  1612. }
  1613. return this
  1614. }
  1615. // HELPER FUNCTIONS
  1616. // ================
  1617. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  1618. function base64clean (str) {
  1619. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  1620. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  1621. // Node converts strings with length < 2 to ''
  1622. if (str.length < 2) return ''
  1623. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  1624. while (str.length % 4 !== 0) {
  1625. str = str + '='
  1626. }
  1627. return str
  1628. }
  1629. function stringtrim (str) {
  1630. if (str.trim) return str.trim()
  1631. return str.replace(/^\s+|\s+$/g, '')
  1632. }
  1633. function toHex (n) {
  1634. if (n < 16) return '0' + n.toString(16)
  1635. return n.toString(16)
  1636. }
  1637. function utf8ToBytes (string, units) {
  1638. units = units || Infinity
  1639. var codePoint
  1640. var length = string.length
  1641. var leadSurrogate = null
  1642. var bytes = []
  1643. for (var i = 0; i < length; ++i) {
  1644. codePoint = string.charCodeAt(i)
  1645. // is surrogate component
  1646. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  1647. // last char was a lead
  1648. if (!leadSurrogate) {
  1649. // no lead yet
  1650. if (codePoint > 0xDBFF) {
  1651. // unexpected trail
  1652. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1653. continue
  1654. } else if (i + 1 === length) {
  1655. // unpaired lead
  1656. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1657. continue
  1658. }
  1659. // valid lead
  1660. leadSurrogate = codePoint
  1661. continue
  1662. }
  1663. // 2 leads in a row
  1664. if (codePoint < 0xDC00) {
  1665. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1666. leadSurrogate = codePoint
  1667. continue
  1668. }
  1669. // valid surrogate pair
  1670. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  1671. } else if (leadSurrogate) {
  1672. // valid bmp char, but last char was a lead
  1673. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1674. }
  1675. leadSurrogate = null
  1676. // encode utf8
  1677. if (codePoint < 0x80) {
  1678. if ((units -= 1) < 0) break
  1679. bytes.push(codePoint)
  1680. } else if (codePoint < 0x800) {
  1681. if ((units -= 2) < 0) break
  1682. bytes.push(
  1683. codePoint >> 0x6 | 0xC0,
  1684. codePoint & 0x3F | 0x80
  1685. )
  1686. } else if (codePoint < 0x10000) {
  1687. if ((units -= 3) < 0) break
  1688. bytes.push(
  1689. codePoint >> 0xC | 0xE0,
  1690. codePoint >> 0x6 & 0x3F | 0x80,
  1691. codePoint & 0x3F | 0x80
  1692. )
  1693. } else if (codePoint < 0x110000) {
  1694. if ((units -= 4) < 0) break
  1695. bytes.push(
  1696. codePoint >> 0x12 | 0xF0,
  1697. codePoint >> 0xC & 0x3F | 0x80,
  1698. codePoint >> 0x6 & 0x3F | 0x80,
  1699. codePoint & 0x3F | 0x80
  1700. )
  1701. } else {
  1702. throw new Error('Invalid code point')
  1703. }
  1704. }
  1705. return bytes
  1706. }
  1707. function asciiToBytes (str) {
  1708. var byteArray = []
  1709. for (var i = 0; i < str.length; ++i) {
  1710. // Node's code seems to be doing this and not & 0x7F..
  1711. byteArray.push(str.charCodeAt(i) & 0xFF)
  1712. }
  1713. return byteArray
  1714. }
  1715. function utf16leToBytes (str, units) {
  1716. var c, hi, lo
  1717. var byteArray = []
  1718. for (var i = 0; i < str.length; ++i) {
  1719. if ((units -= 2) < 0) break
  1720. c = str.charCodeAt(i)
  1721. hi = c >> 8
  1722. lo = c % 256
  1723. byteArray.push(lo)
  1724. byteArray.push(hi)
  1725. }
  1726. return byteArray
  1727. }
  1728. function base64ToBytes (str) {
  1729. return base64.toByteArray(base64clean(str))
  1730. }
  1731. function blitBuffer (src, dst, offset, length) {
  1732. for (var i = 0; i < length; ++i) {
  1733. if ((i + offset >= dst.length) || (i >= src.length)) break
  1734. dst[i + offset] = src[i]
  1735. }
  1736. return i
  1737. }
  1738. function isnan (val) {
  1739. return val !== val // eslint-disable-line no-self-compare
  1740. }
  1741. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1742. },{"base64-js":4,"ieee754":16,"isarray":21}],8:[function(_dereq_,module,exports){
  1743. /**
  1744. * This is the web browser implementation of `debug()`.
  1745. *
  1746. * Expose `debug()` as the module.
  1747. */
  1748. exports = module.exports = _dereq_('./debug');
  1749. exports.log = log;
  1750. exports.formatArgs = formatArgs;
  1751. exports.save = save;
  1752. exports.load = load;
  1753. exports.useColors = useColors;
  1754. exports.storage = 'undefined' != typeof chrome
  1755. && 'undefined' != typeof chrome.storage
  1756. ? chrome.storage.local
  1757. : localstorage();
  1758. /**
  1759. * Colors.
  1760. */
  1761. exports.colors = [
  1762. 'lightseagreen',
  1763. 'forestgreen',
  1764. 'goldenrod',
  1765. 'dodgerblue',
  1766. 'darkorchid',
  1767. 'crimson'
  1768. ];
  1769. /**
  1770. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  1771. * and the Firebug extension (any Firefox version) are known
  1772. * to support "%c" CSS customizations.
  1773. *
  1774. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  1775. */
  1776. function useColors() {
  1777. // is webkit? http://stackoverflow.com/a/16459606/376773
  1778. return ('WebkitAppearance' in document.documentElement.style) ||
  1779. // is firebug? http://stackoverflow.com/a/398120/376773
  1780. (window.console && (console.firebug || (console.exception && console.table))) ||
  1781. // is firefox >= v31?
  1782. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  1783. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  1784. }
  1785. /**
  1786. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  1787. */
  1788. exports.formatters.j = function(v) {
  1789. return JSON.stringify(v);
  1790. };
  1791. /**
  1792. * Colorize log arguments if enabled.
  1793. *
  1794. * @api public
  1795. */
  1796. function formatArgs() {
  1797. var args = arguments;
  1798. var useColors = this.useColors;
  1799. args[0] = (useColors ? '%c' : '')
  1800. + this.namespace
  1801. + (useColors ? ' %c' : ' ')
  1802. + args[0]
  1803. + (useColors ? '%c ' : ' ');
  1804. if (!useColors) return args;
  1805. var c = 'color: ' + this.color;
  1806. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  1807. // the final "%c" is somewhat tricky, because there could be other
  1808. // arguments passed either before or after the %c, so we need to
  1809. // figure out the correct index to insert the CSS into
  1810. var index = 0;
  1811. var lastC = 0;
  1812. args[0].replace(/%[a-z%]/g, function(match) {
  1813. if ('%%' === match) return;
  1814. index++;
  1815. if ('%c' === match) {
  1816. // we only are interested in the *last* %c
  1817. // (the user may have provided their own)
  1818. lastC = index;
  1819. }
  1820. });
  1821. args.splice(lastC, 0, c);
  1822. return args;
  1823. }
  1824. /**
  1825. * Invokes `console.log()` when available.
  1826. * No-op when `console.log` is not a "function".
  1827. *
  1828. * @api public
  1829. */
  1830. function log() {
  1831. // this hackery is required for IE8/9, where
  1832. // the `console.log` function doesn't have 'apply'
  1833. return 'object' === typeof console
  1834. && console.log
  1835. && Function.prototype.apply.call(console.log, console, arguments);
  1836. }
  1837. /**
  1838. * Save `namespaces`.
  1839. *
  1840. * @param {String} namespaces
  1841. * @api private
  1842. */
  1843. function save(namespaces) {
  1844. try {
  1845. if (null == namespaces) {
  1846. exports.storage.removeItem('debug');
  1847. } else {
  1848. exports.storage.debug = namespaces;
  1849. }
  1850. } catch(e) {}
  1851. }
  1852. /**
  1853. * Load `namespaces`.
  1854. *
  1855. * @return {String} returns the previously persisted debug modes
  1856. * @api private
  1857. */
  1858. function load() {
  1859. var r;
  1860. try {
  1861. r = exports.storage.debug;
  1862. } catch(e) {}
  1863. return r;
  1864. }
  1865. /**
  1866. * Enable namespaces listed in `localStorage.debug` initially.
  1867. */
  1868. exports.enable(load());
  1869. /**
  1870. * Localstorage attempts to return the localstorage.
  1871. *
  1872. * This is necessary because safari throws
  1873. * when a user disables cookies/localstorage
  1874. * and you attempt to access it.
  1875. *
  1876. * @return {LocalStorage}
  1877. * @api private
  1878. */
  1879. function localstorage(){
  1880. try {
  1881. return window.localStorage;
  1882. } catch (e) {}
  1883. }
  1884. },{"./debug":9}],9:[function(_dereq_,module,exports){
  1885. /**
  1886. * This is the common logic for both the Node.js and web browser
  1887. * implementations of `debug()`.
  1888. *
  1889. * Expose `debug()` as the module.
  1890. */
  1891. exports = module.exports = debug;
  1892. exports.coerce = coerce;
  1893. exports.disable = disable;
  1894. exports.enable = enable;
  1895. exports.enabled = enabled;
  1896. /**
  1897. * The currently active debug mode names, and names to skip.
  1898. */
  1899. exports.names = [];
  1900. exports.skips = [];
  1901. /**
  1902. * Map of special "%n" handling functions, for the debug "format" argument.
  1903. *
  1904. * Valid key names are a single, lowercased letter, i.e. "n".
  1905. */
  1906. exports.formatters = {};
  1907. /**
  1908. * Previously assigned color.
  1909. */
  1910. var prevColor = 0;
  1911. /**
  1912. * Select a color.
  1913. *
  1914. * @return {Number}
  1915. * @api private
  1916. */
  1917. function selectColor() {
  1918. return exports.colors[prevColor++ % exports.colors.length];
  1919. }
  1920. /**
  1921. * Create a debugger with the given `namespace`.
  1922. *
  1923. * @param {String} namespace
  1924. * @return {Function}
  1925. * @api public
  1926. */
  1927. function debug(namespace) {
  1928. // define the `disabled` version
  1929. function disabled() {
  1930. }
  1931. disabled.enabled = false;
  1932. // define the `enabled` version
  1933. function enabled() {
  1934. var self = enabled;
  1935. // add the `color` if not set
  1936. if (null == self.useColors) self.useColors = exports.useColors();
  1937. if (null == self.color && self.useColors) self.color = selectColor();
  1938. var args = Array.prototype.slice.call(arguments);
  1939. args[0] = exports.coerce(args[0]);
  1940. if ('string' !== typeof args[0]) {
  1941. // anything else let's inspect with %o
  1942. args = ['%o'].concat(args);
  1943. }
  1944. // apply any `formatters` transformations
  1945. var index = 0;
  1946. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  1947. // if we encounter an escaped % then don't increase the array index
  1948. if (match === '%%') return match;
  1949. index++;
  1950. var formatter = exports.formatters[format];
  1951. if ('function' === typeof formatter) {
  1952. var val = args[index];
  1953. match = formatter.call(self, val);
  1954. // now we need to remove `args[index]` since it's inlined in the `format`
  1955. args.splice(index, 1);
  1956. index--;
  1957. }
  1958. return match;
  1959. });
  1960. if ('function' === typeof exports.formatArgs) {
  1961. args = exports.formatArgs.apply(self, args);
  1962. }
  1963. var logFn = enabled.log || exports.log || console.log.bind(console);
  1964. logFn.apply(self, args);
  1965. }
  1966. enabled.enabled = true;
  1967. var fn = exports.enabled(namespace) ? enabled : disabled;
  1968. fn.namespace = namespace;
  1969. return fn;
  1970. }
  1971. /**
  1972. * Enables a debug mode by namespaces. This can include modes
  1973. * separated by a colon and wildcards.
  1974. *
  1975. * @param {String} namespaces
  1976. * @api public
  1977. */
  1978. function enable(namespaces) {
  1979. exports.save(namespaces);
  1980. var split = (namespaces || '').split(/[\s,]+/);
  1981. var len = split.length;
  1982. for (var i = 0; i < len; i++) {
  1983. if (!split[i]) continue; // ignore empty strings
  1984. namespaces = split[i].replace(/\*/g, '.*?');
  1985. if (namespaces[0] === '-') {
  1986. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  1987. } else {
  1988. exports.names.push(new RegExp('^' + namespaces + '$'));
  1989. }
  1990. }
  1991. }
  1992. /**
  1993. * Disable debug output.
  1994. *
  1995. * @api public
  1996. */
  1997. function disable() {
  1998. exports.enable('');
  1999. }
  2000. /**
  2001. * Returns true if the given mode name is enabled, false otherwise.
  2002. *
  2003. * @param {String} name
  2004. * @return {Boolean}
  2005. * @api public
  2006. */
  2007. function enabled(name) {
  2008. var i, len;
  2009. for (i = 0, len = exports.skips.length; i < len; i++) {
  2010. if (exports.skips[i].test(name)) {
  2011. return false;
  2012. }
  2013. }
  2014. for (i = 0, len = exports.names.length; i < len; i++) {
  2015. if (exports.names[i].test(name)) {
  2016. return true;
  2017. }
  2018. }
  2019. return false;
  2020. }
  2021. /**
  2022. * Coerce `val`.
  2023. *
  2024. * @param {Mixed} val
  2025. * @return {Mixed}
  2026. * @api private
  2027. */
  2028. function coerce(val) {
  2029. if (val instanceof Error) return val.stack || val.message;
  2030. return val;
  2031. }
  2032. },{}],10:[function(_dereq_,module,exports){
  2033. 'use strict';
  2034. var isObj = _dereq_('is-obj');
  2035. var hasOwnProperty = Object.prototype.hasOwnProperty;
  2036. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  2037. function toObject(val) {
  2038. if (val === null || val === undefined) {
  2039. throw new TypeError('Sources cannot be null or undefined');
  2040. }
  2041. return Object(val);
  2042. }
  2043. function assignKey(to, from, key) {
  2044. var val = from[key];
  2045. if (val === undefined || val === null) {
  2046. return;
  2047. }
  2048. if (hasOwnProperty.call(to, key)) {
  2049. if (to[key] === undefined || to[key] === null) {
  2050. throw new TypeError('Cannot convert undefined or null to object (' + key + ')');
  2051. }
  2052. }
  2053. if (!hasOwnProperty.call(to, key) || !isObj(val)) {
  2054. to[key] = val;
  2055. } else {
  2056. to[key] = assign(Object(to[key]), from[key]);
  2057. }
  2058. }
  2059. function assign(to, from) {
  2060. if (to === from) {
  2061. return to;
  2062. }
  2063. from = Object(from);
  2064. for (var key in from) {
  2065. if (hasOwnProperty.call(from, key)) {
  2066. assignKey(to, from, key);
  2067. }
  2068. }
  2069. if (Object.getOwnPropertySymbols) {
  2070. var symbols = Object.getOwnPropertySymbols(from);
  2071. for (var i = 0; i < symbols.length; i++) {
  2072. if (propIsEnumerable.call(from, symbols[i])) {
  2073. assignKey(to, from, symbols[i]);
  2074. }
  2075. }
  2076. }
  2077. return to;
  2078. }
  2079. module.exports = function deepAssign(target) {
  2080. target = toObject(target);
  2081. for (var s = 1; s < arguments.length; s++) {
  2082. assign(target, arguments[s]);
  2083. }
  2084. return target;
  2085. };
  2086. },{"is-obj":20}],11:[function(_dereq_,module,exports){
  2087. /*! (C) WebReflection Mit Style License */
  2088. (function(t,n,r,i){"use strict";function st(e,t){for(var n=0,r=e.length;n<r;n++)gt(e[n],t)}function ot(e){for(var t=0,n=e.length,r;t<n;t++)r=e[t],it(r,w[at(r)])}function ut(e){return function(t){F(t)&&(gt(t,e),st(t.querySelectorAll(E),e))}}function at(e){var t=R.call(e,"is"),n=e.nodeName.toUpperCase(),r=x.call(b,t?m+t.toUpperCase():v+n);return t&&-1<r&&!ft(n,t)?-1:r}function ft(e,t){return-1<E.indexOf(e+'[is="'+t+'"]')}function lt(e){var t=e.currentTarget,n=e.attrChange,r=e.attrName,i=e.target;Y&&(!i||i===t)&&t.attributeChangedCallback&&r!=="style"&&e.prevValue!==e.newValue&&t.attributeChangedCallback(r,n===e[f]?null:e.prevValue,n===e[c]?null:e.newValue)}function ct(e){var t=ut(e);return function(e){$.push(t,e.target)}}function ht(e){G&&(G=!1,e.currentTarget.removeEventListener(p,ht)),st((e.target||n).querySelectorAll(E),e.detail===u?u:o),j&&vt()}function pt(e,t){var n=this;U.call(n,e,t),Z.call(n,{target:n})}function dt(e,t){P(e,t),nt?nt.observe(e,X):(Q&&(e.setAttribute=pt,e[s]=tt(e),e.addEventListener(d,Z)),e.addEventListener(h,lt)),e.createdCallback&&Y&&(e.created=!0,e.createdCallback(),e.created=!1)}function vt(){for(var e,t=0,n=I.length;t<n;t++)e=I[t],S.contains(e)||(n--,I.splice(t--,1),gt(e,u))}function mt(e){throw new Error("A "+e+" type is already registered")}function gt(e,t){var n,r=at(e);-1<r&&(rt(e,w[r]),r=0,t===o&&!e[o]?(e[u]=!1,e[o]=!0,r=1,j&&x.call(I,e)<0&&I.push(e)):t===u&&!e[u]&&(e[o]=!1,e[u]=!0,r=1),r&&(n=e[t+"Callback"])&&n.call(e))}if(i in n)return;var s="__"+i+(Math.random()*1e5>>0),o="attached",u="detached",a="extends",f="ADDITION",l="MODIFICATION",c="REMOVAL",h="DOMAttrModified",p="DOMContentLoaded",d="DOMSubtreeModified",v="<",m="=",g=/^[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+$/,y=["ANNOTATION-XML","COLOR-PROFILE","FONT-FACE","FONT-FACE-SRC","FONT-FACE-URI","FONT-FACE-FORMAT","FONT-FACE-NAME","MISSING-GLYPH"],b=[],w=[],E="",S=n.documentElement,x=b.indexOf||function(e){for(var t=this.length;t--&&this[t]!==e;);return t},T=r.prototype,N=T.hasOwnProperty,C=T.isPrototypeOf,k=r.defineProperty,L=r.getOwnPropertyDescriptor,A=r.getOwnPropertyNames,O=r.getPrototypeOf,M=r.setPrototypeOf,_=!!r.__proto__,D=r.create||function yt(e){return e?(yt.prototype=e,new yt):this},P=M||(_?function(e,t){return e.__proto__=t,e}:A&&L?function(){function e(e,t){for(var n,r=A(t),i=0,s=r.length;i<s;i++)n=r[i],N.call(e,n)||k(e,n,L(t,n))}return function(t,n){do e(t,n);while((n=O(n))&&!C.call(n,t));return t}}():function(e,t){for(var n in t)e[n]=t[n];return e}),H=t.MutationObserver||t.WebKitMutationObserver,B=(t.HTMLElement||t.Element||t.Node).prototype,j=!C.call(B,S),F=j?function(e){return e.nodeType===1}:function(e){return C.call(B,e)},I=j&&[],q=B.cloneNode,R=B.getAttribute,U=B.setAttribute,z=B.removeAttribute,W=n.createElement,X=H&&{attributes:!0,characterData:!0,attributeOldValue:!0},V=H||function(e){Q=!1,S.removeEventListener(h,V)},$,J=t.requestAnimationFrame||t.webkitRequestAnimationFrame||t.mozRequestAnimationFrame||t.msRequestAnimationFrame||function(e){setTimeout(e,10)},K=!1,Q=!0,G=!0,Y=!0,Z,et,tt,nt,rt,it;M||_?(rt=function(e,t){C.call(t,e)||dt(e,t)},it=dt):(rt=function(e,t){e[s]||(e[s]=r(!0),dt(e,t))},it=rt),j?(Q=!1,function(){var t=L(B,"addEventListener"),n=t.value,r=function(e){var t=new CustomEvent(h,{bubbles:!0});t.attrName=e,t.prevValue=R.call(this,e),t.newValue=null,t[c]=t.attrChange=2,z.call(this,e),this.dispatchEvent(t)},i=function(t,n){var r=this.hasAttribute(t),i=r&&R.call(this,t);e=new CustomEvent(h,{bubbles:!0}),U.call(this,t,n),e.attrName=t,e.prevValue=r?i:null,e.newValue=n,r?e[l]=e.attrChange=1:e[f]=e.attrChange=0,this.dispatchEvent(e)},o=function(e){var t=e.currentTarget,n=t[s],r=e.propertyName,i;n.hasOwnProperty(r)&&(n=n[r],i=new CustomEvent(h,{bubbles:!0}),i.attrName=n.name,i.prevValue=n.value||null,i.newValue=n.value=t[r]||null,i.prevValue==null?i[f]=i.attrChange=0:i[l]=i.attrChange=1,t.dispatchEvent(i))};t.value=function(e,t,u){e===h&&this.attributeChangedCallback&&this.setAttribute!==i&&(this[s]={className:{name:"class",value:this.className}},this.setAttribute=i,this.removeAttribute=r,n.call(this,"propertychange",o)),n.call(this,e,t,u)},k(B,"addEventListener",t)}()):H||(S.addEventListener(h,V),S.setAttribute(s,1),S.removeAttribute(s),Q&&(Z=function(e){var t=this,n,r,i;if(t===e.target){n=t[s],t[s]=r=tt(t);for(i in r){if(!(i in n))return et(0,t,i,n[i],r[i],f);if(r[i]!==n[i])return et(1,t,i,n[i],r[i],l)}for(i in n)if(!(i in r))return et(2,t,i,n[i],r[i],c)}},et=function(e,t,n,r,i,s){var o={attrChange:e,currentTarget:t,attrName:n,prevValue:r,newValue:i};o[s]=e,lt(o)},tt=function(e){for(var t,n,r={},i=e.attributes,s=0,o=i.length;s<o;s++)t=i[s],n=t.name,n!=="setAttribute"&&(r[n]=t.value);return r})),n[i]=function(t,r){c=t.toUpperCase(),K||(K=!0,H?(nt=function(e,t){function n(e,t){for(var n=0,r=e.length;n<r;t(e[n++]));}return new H(function(r){for(var i,s,o,u=0,a=r.length;u<a;u++)i=r[u],i.type==="childList"?(n(i.addedNodes,e),n(i.removedNodes,t)):(s=i.target,Y&&s.attributeChangedCallback&&i.attributeName!=="style"&&(o=R.call(s,i.attributeName),o!==i.oldValue&&s.attributeChangedCallback(i.attributeName,i.oldValue,o)))})}(ut(o),ut(u)),nt.observe(n,{childList:!0,subtree:!0})):($=[],J(function d(){while($.length)$.shift().call(null,$.shift());J(d)}),n.addEventListener("DOMNodeInserted",ct(o)),n.addEventListener("DOMNodeRemoved",ct(u))),n.addEventListener(p,ht),n.addEventListener("readystatechange",ht),n.createElement=function(e,t){var r=W.apply(n,arguments),i=""+e,s=x.call(b,(t?m:v)+(t||i).toUpperCase()),o=-1<s;return t&&(r.setAttribute("is",t=t.toLowerCase()),o&&(o=ft(i.toUpperCase(),t))),Y=!n.createElement.innerHTMLHelper,o&&it(r,w[s]),r},B.cloneNode=function(e){var t=q.call(this,!!e),n=at(t);return-1<n&&it(t,w[n]),e&&ot(t.querySelectorAll(E)),t}),-2<x.call(b,m+c)+x.call(b,v+c)&&mt(t);if(!g.test(c)||-1<x.call(y,c))throw new Error("The type "+t+" is invalid");var i=function(){return f?n.createElement(l,c):n.createElement(l)},s=r||T,f=N.call(s,a),l=f?r[a].toUpperCase():c,c,h;return f&&-1<x.call(b,v+l)&&mt(l),h=b.push((f?m:v)+c)-1,E=E.concat(E.length?",":"",f?l+'[is="'+t.toLowerCase()+'"]':l),i.prototype=w[h]=N.call(s,"prototype")?s.prototype:D(B),st(n.querySelectorAll(E),o),i}})(window,document,Object,"registerElement");
  2089. },{}],12:[function(_dereq_,module,exports){
  2090. module.exports = function(dtype) {
  2091. switch (dtype) {
  2092. case 'int8':
  2093. return Int8Array
  2094. case 'int16':
  2095. return Int16Array
  2096. case 'int32':
  2097. return Int32Array
  2098. case 'uint8':
  2099. return Uint8Array
  2100. case 'uint16':
  2101. return Uint16Array
  2102. case 'uint32':
  2103. return Uint32Array
  2104. case 'float32':
  2105. return Float32Array
  2106. case 'float64':
  2107. return Float64Array
  2108. case 'array':
  2109. return Array
  2110. case 'uint8_clamped':
  2111. return Uint8ClampedArray
  2112. }
  2113. }
  2114. },{}],13:[function(_dereq_,module,exports){
  2115. /*eslint new-cap:0*/
  2116. var dtype = _dereq_('dtype')
  2117. module.exports = flattenVertexData
  2118. function flattenVertexData (data, output, offset) {
  2119. if (!data) throw new TypeError('must specify data as first parameter')
  2120. offset = +(offset || 0) | 0
  2121. if (Array.isArray(data) && Array.isArray(data[0])) {
  2122. var dim = data[0].length
  2123. var length = data.length * dim
  2124. // no output specified, create a new typed array
  2125. if (!output || typeof output === 'string') {
  2126. output = new (dtype(output || 'float32'))(length + offset)
  2127. }
  2128. var dstLength = output.length - offset
  2129. if (length !== dstLength) {
  2130. throw new Error('source length ' + length + ' (' + dim + 'x' + data.length + ')' +
  2131. ' does not match destination length ' + dstLength)
  2132. }
  2133. for (var i = 0, k = offset; i < data.length; i++) {
  2134. for (var j = 0; j < dim; j++) {
  2135. output[k++] = data[i][j]
  2136. }
  2137. }
  2138. } else {
  2139. if (!output || typeof output === 'string') {
  2140. // no output, create a new one
  2141. var Ctor = dtype(output || 'float32')
  2142. if (offset === 0) {
  2143. output = new Ctor(data)
  2144. } else {
  2145. output = new Ctor(data.length + offset)
  2146. output.set(data, offset)
  2147. }
  2148. } else {
  2149. // store output in existing array
  2150. output.set(data, offset)
  2151. }
  2152. }
  2153. return output
  2154. }
  2155. },{"dtype":12}],14:[function(_dereq_,module,exports){
  2156. var isFunction = _dereq_('is-function')
  2157. module.exports = forEach
  2158. var toString = Object.prototype.toString
  2159. var hasOwnProperty = Object.prototype.hasOwnProperty
  2160. function forEach(list, iterator, context) {
  2161. if (!isFunction(iterator)) {
  2162. throw new TypeError('iterator must be a function')
  2163. }
  2164. if (arguments.length < 3) {
  2165. context = this
  2166. }
  2167. if (toString.call(list) === '[object Array]')
  2168. forEachArray(list, iterator, context)
  2169. else if (typeof list === 'string')
  2170. forEachString(list, iterator, context)
  2171. else
  2172. forEachObject(list, iterator, context)
  2173. }
  2174. function forEachArray(array, iterator, context) {
  2175. for (var i = 0, len = array.length; i < len; i++) {
  2176. if (hasOwnProperty.call(array, i)) {
  2177. iterator.call(context, array[i], i, array)
  2178. }
  2179. }
  2180. }
  2181. function forEachString(string, iterator, context) {
  2182. for (var i = 0, len = string.length; i < len; i++) {
  2183. // no such thing as a sparse string.
  2184. iterator.call(context, string.charAt(i), i, string)
  2185. }
  2186. }
  2187. function forEachObject(object, iterator, context) {
  2188. for (var k in object) {
  2189. if (hasOwnProperty.call(object, k)) {
  2190. iterator.call(context, object[k], k, object)
  2191. }
  2192. }
  2193. }
  2194. },{"is-function":19}],15:[function(_dereq_,module,exports){
  2195. (function (global){
  2196. var win;
  2197. if (typeof window !== "undefined") {
  2198. win = window;
  2199. } else if (typeof global !== "undefined") {
  2200. win = global;
  2201. } else if (typeof self !== "undefined"){
  2202. win = self;
  2203. } else {
  2204. win = {};
  2205. }
  2206. module.exports = win;
  2207. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2208. },{}],16:[function(_dereq_,module,exports){
  2209. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  2210. var e, m
  2211. var eLen = nBytes * 8 - mLen - 1
  2212. var eMax = (1 << eLen) - 1
  2213. var eBias = eMax >> 1
  2214. var nBits = -7
  2215. var i = isLE ? (nBytes - 1) : 0
  2216. var d = isLE ? -1 : 1
  2217. var s = buffer[offset + i]
  2218. i += d
  2219. e = s & ((1 << (-nBits)) - 1)
  2220. s >>= (-nBits)
  2221. nBits += eLen
  2222. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  2223. m = e & ((1 << (-nBits)) - 1)
  2224. e >>= (-nBits)
  2225. nBits += mLen
  2226. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  2227. if (e === 0) {
  2228. e = 1 - eBias
  2229. } else if (e === eMax) {
  2230. return m ? NaN : ((s ? -1 : 1) * Infinity)
  2231. } else {
  2232. m = m + Math.pow(2, mLen)
  2233. e = e - eBias
  2234. }
  2235. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  2236. }
  2237. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  2238. var e, m, c
  2239. var eLen = nBytes * 8 - mLen - 1
  2240. var eMax = (1 << eLen) - 1
  2241. var eBias = eMax >> 1
  2242. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  2243. var i = isLE ? 0 : (nBytes - 1)
  2244. var d = isLE ? 1 : -1
  2245. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  2246. value = Math.abs(value)
  2247. if (isNaN(value) || value === Infinity) {
  2248. m = isNaN(value) ? 1 : 0
  2249. e = eMax
  2250. } else {
  2251. e = Math.floor(Math.log(value) / Math.LN2)
  2252. if (value * (c = Math.pow(2, -e)) < 1) {
  2253. e--
  2254. c *= 2
  2255. }
  2256. if (e + eBias >= 1) {
  2257. value += rt / c
  2258. } else {
  2259. value += rt * Math.pow(2, 1 - eBias)
  2260. }
  2261. if (value * c >= 2) {
  2262. e++
  2263. c /= 2
  2264. }
  2265. if (e + eBias >= eMax) {
  2266. m = 0
  2267. e = eMax
  2268. } else if (e + eBias >= 1) {
  2269. m = (value * c - 1) * Math.pow(2, mLen)
  2270. e = e + eBias
  2271. } else {
  2272. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  2273. e = 0
  2274. }
  2275. }
  2276. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  2277. e = (e << mLen) | m
  2278. eLen += mLen
  2279. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  2280. buffer[offset + i - d] |= s * 128
  2281. }
  2282. },{}],17:[function(_dereq_,module,exports){
  2283. if (typeof Object.create === 'function') {
  2284. // implementation from standard node.js 'util' module
  2285. module.exports = function inherits(ctor, superCtor) {
  2286. ctor.super_ = superCtor
  2287. ctor.prototype = Object.create(superCtor.prototype, {
  2288. constructor: {
  2289. value: ctor,
  2290. enumerable: false,
  2291. writable: true,
  2292. configurable: true
  2293. }
  2294. });
  2295. };
  2296. } else {
  2297. // old school shim for old browsers
  2298. module.exports = function inherits(ctor, superCtor) {
  2299. ctor.super_ = superCtor
  2300. var TempCtor = function () {}
  2301. TempCtor.prototype = superCtor.prototype
  2302. ctor.prototype = new TempCtor()
  2303. ctor.prototype.constructor = ctor
  2304. }
  2305. }
  2306. },{}],18:[function(_dereq_,module,exports){
  2307. /*!
  2308. * Determine if an object is a Buffer
  2309. *
  2310. * @author Feross Aboukhadijeh <https://feross.org>
  2311. * @license MIT
  2312. */
  2313. // The _isBuffer check is for Safari 5-7 support, because it's missing
  2314. // Object.prototype.constructor. Remove this eventually
  2315. module.exports = function (obj) {
  2316. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  2317. }
  2318. function isBuffer (obj) {
  2319. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  2320. }
  2321. // For Node v0.10 support. Remove this eventually.
  2322. function isSlowBuffer (obj) {
  2323. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  2324. }
  2325. },{}],19:[function(_dereq_,module,exports){
  2326. module.exports = isFunction
  2327. var toString = Object.prototype.toString
  2328. function isFunction (fn) {
  2329. var string = toString.call(fn)
  2330. return string === '[object Function]' ||
  2331. (typeof fn === 'function' && string !== '[object RegExp]') ||
  2332. (typeof window !== 'undefined' &&
  2333. // IE8 and below
  2334. (fn === window.setTimeout ||
  2335. fn === window.alert ||
  2336. fn === window.confirm ||
  2337. fn === window.prompt))
  2338. };
  2339. },{}],20:[function(_dereq_,module,exports){
  2340. 'use strict';
  2341. module.exports = function (x) {
  2342. var type = typeof x;
  2343. return x !== null && (type === 'object' || type === 'function');
  2344. };
  2345. },{}],21:[function(_dereq_,module,exports){
  2346. var toString = {}.toString;
  2347. module.exports = Array.isArray || function (arr) {
  2348. return toString.call(arr) == '[object Array]';
  2349. };
  2350. },{}],22:[function(_dereq_,module,exports){
  2351. var wordWrap = _dereq_('word-wrapper')
  2352. var xtend = _dereq_('xtend')
  2353. var number = _dereq_('as-number')
  2354. var X_HEIGHTS = ['x', 'e', 'a', 'o', 'n', 's', 'r', 'c', 'u', 'm', 'v', 'w', 'z']
  2355. var M_WIDTHS = ['m', 'w']
  2356. var CAP_HEIGHTS = ['H', 'I', 'N', 'E', 'F', 'K', 'L', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  2357. var TAB_ID = '\t'.charCodeAt(0)
  2358. var SPACE_ID = ' '.charCodeAt(0)
  2359. var ALIGN_LEFT = 0,
  2360. ALIGN_CENTER = 1,
  2361. ALIGN_RIGHT = 2
  2362. module.exports = function createLayout(opt) {
  2363. return new TextLayout(opt)
  2364. }
  2365. function TextLayout(opt) {
  2366. this.glyphs = []
  2367. this._measure = this.computeMetrics.bind(this)
  2368. this.update(opt)
  2369. }
  2370. TextLayout.prototype.update = function(opt) {
  2371. opt = xtend({
  2372. measure: this._measure
  2373. }, opt)
  2374. this._opt = opt
  2375. this._opt.tabSize = number(this._opt.tabSize, 4)
  2376. if (!opt.font)
  2377. throw new Error('must provide a valid bitmap font')
  2378. var glyphs = this.glyphs
  2379. var text = opt.text||''
  2380. var font = opt.font
  2381. this._setupSpaceGlyphs(font)
  2382. var lines = wordWrap.lines(text, opt)
  2383. var minWidth = opt.width || 0
  2384. //clear glyphs
  2385. glyphs.length = 0
  2386. //get max line width
  2387. var maxLineWidth = lines.reduce(function(prev, line) {
  2388. return Math.max(prev, line.width, minWidth)
  2389. }, 0)
  2390. //the pen position
  2391. var x = 0
  2392. var y = 0
  2393. var lineHeight = number(opt.lineHeight, font.common.lineHeight)
  2394. var baseline = font.common.base
  2395. var descender = lineHeight-baseline
  2396. var letterSpacing = opt.letterSpacing || 0
  2397. var height = lineHeight * lines.length - descender
  2398. var align = getAlignType(this._opt.align)
  2399. //draw text along baseline
  2400. y -= height
  2401. //the metrics for this text layout
  2402. this._width = maxLineWidth
  2403. this._height = height
  2404. this._descender = lineHeight - baseline
  2405. this._baseline = baseline
  2406. this._xHeight = getXHeight(font)
  2407. this._capHeight = getCapHeight(font)
  2408. this._lineHeight = lineHeight
  2409. this._ascender = lineHeight - descender - this._xHeight
  2410. //layout each glyph
  2411. var self = this
  2412. lines.forEach(function(line, lineIndex) {
  2413. var start = line.start
  2414. var end = line.end
  2415. var lineWidth = line.width
  2416. var lastGlyph
  2417. //for each glyph in that line...
  2418. for (var i=start; i<end; i++) {
  2419. var id = text.charCodeAt(i)
  2420. var glyph = self.getGlyph(font, id)
  2421. if (glyph) {
  2422. if (lastGlyph)
  2423. x += getKerning(font, lastGlyph.id, glyph.id)
  2424. var tx = x
  2425. if (align === ALIGN_CENTER)
  2426. tx += (maxLineWidth-lineWidth)/2
  2427. else if (align === ALIGN_RIGHT)
  2428. tx += (maxLineWidth-lineWidth)
  2429. glyphs.push({
  2430. position: [tx, y],
  2431. data: glyph,
  2432. index: i,
  2433. line: lineIndex
  2434. })
  2435. //move pen forward
  2436. x += glyph.xadvance + letterSpacing
  2437. lastGlyph = glyph
  2438. }
  2439. }
  2440. //next line down
  2441. y += lineHeight
  2442. x = 0
  2443. })
  2444. this._linesTotal = lines.length;
  2445. }
  2446. TextLayout.prototype._setupSpaceGlyphs = function(font) {
  2447. //These are fallbacks, when the font doesn't include
  2448. //' ' or '\t' glyphs
  2449. this._fallbackSpaceGlyph = null
  2450. this._fallbackTabGlyph = null
  2451. if (!font.chars || font.chars.length === 0)
  2452. return
  2453. //try to get space glyph
  2454. //then fall back to the 'm' or 'w' glyphs
  2455. //then fall back to the first glyph available
  2456. var space = getGlyphById(font, SPACE_ID)
  2457. || getMGlyph(font)
  2458. || font.chars[0]
  2459. //and create a fallback for tab
  2460. var tabWidth = this._opt.tabSize * space.xadvance
  2461. this._fallbackSpaceGlyph = space
  2462. this._fallbackTabGlyph = xtend(space, {
  2463. x: 0, y: 0, xadvance: tabWidth, id: TAB_ID,
  2464. xoffset: 0, yoffset: 0, width: 0, height: 0
  2465. })
  2466. }
  2467. TextLayout.prototype.getGlyph = function(font, id) {
  2468. var glyph = getGlyphById(font, id)
  2469. if (glyph)
  2470. return glyph
  2471. else if (id === TAB_ID)
  2472. return this._fallbackTabGlyph
  2473. else if (id === SPACE_ID)
  2474. return this._fallbackSpaceGlyph
  2475. return null
  2476. }
  2477. TextLayout.prototype.computeMetrics = function(text, start, end, width) {
  2478. var letterSpacing = this._opt.letterSpacing || 0
  2479. var font = this._opt.font
  2480. var curPen = 0
  2481. var curWidth = 0
  2482. var count = 0
  2483. var glyph
  2484. var lastGlyph
  2485. if (!font.chars || font.chars.length === 0) {
  2486. return {
  2487. start: start,
  2488. end: start,
  2489. width: 0
  2490. }
  2491. }
  2492. end = Math.min(text.length, end)
  2493. for (var i=start; i < end; i++) {
  2494. var id = text.charCodeAt(i)
  2495. var glyph = this.getGlyph(font, id)
  2496. if (glyph) {
  2497. //move pen forward
  2498. var xoff = glyph.xoffset
  2499. var kern = lastGlyph ? getKerning(font, lastGlyph.id, glyph.id) : 0
  2500. curPen += kern
  2501. var nextPen = curPen + glyph.xadvance + letterSpacing
  2502. var nextWidth = curPen + glyph.width
  2503. //we've hit our limit; we can't move onto the next glyph
  2504. if (nextWidth >= width || nextPen >= width)
  2505. break
  2506. //otherwise continue along our line
  2507. curPen = nextPen
  2508. curWidth = nextWidth
  2509. lastGlyph = glyph
  2510. }
  2511. count++
  2512. }
  2513. //make sure rightmost edge lines up with rendered glyphs
  2514. if (lastGlyph)
  2515. curWidth += lastGlyph.xoffset
  2516. return {
  2517. start: start,
  2518. end: start + count,
  2519. width: curWidth
  2520. }
  2521. }
  2522. //getters for the private vars
  2523. ;['width', 'height',
  2524. 'descender', 'ascender',
  2525. 'xHeight', 'baseline',
  2526. 'capHeight',
  2527. 'lineHeight' ].forEach(addGetter)
  2528. function addGetter(name) {
  2529. Object.defineProperty(TextLayout.prototype, name, {
  2530. get: wrapper(name),
  2531. configurable: true
  2532. })
  2533. }
  2534. //create lookups for private vars
  2535. function wrapper(name) {
  2536. return (new Function([
  2537. 'return function '+name+'() {',
  2538. ' return this._'+name,
  2539. '}'
  2540. ].join('\n')))()
  2541. }
  2542. function getGlyphById(font, id) {
  2543. if (!font.chars || font.chars.length === 0)
  2544. return null
  2545. var glyphIdx = findChar(font.chars, id)
  2546. if (glyphIdx >= 0)
  2547. return font.chars[glyphIdx]
  2548. return null
  2549. }
  2550. function getXHeight(font) {
  2551. for (var i=0; i<X_HEIGHTS.length; i++) {
  2552. var id = X_HEIGHTS[i].charCodeAt(0)
  2553. var idx = findChar(font.chars, id)
  2554. if (idx >= 0)
  2555. return font.chars[idx].height
  2556. }
  2557. return 0
  2558. }
  2559. function getMGlyph(font) {
  2560. for (var i=0; i<M_WIDTHS.length; i++) {
  2561. var id = M_WIDTHS[i].charCodeAt(0)
  2562. var idx = findChar(font.chars, id)
  2563. if (idx >= 0)
  2564. return font.chars[idx]
  2565. }
  2566. return 0
  2567. }
  2568. function getCapHeight(font) {
  2569. for (var i=0; i<CAP_HEIGHTS.length; i++) {
  2570. var id = CAP_HEIGHTS[i].charCodeAt(0)
  2571. var idx = findChar(font.chars, id)
  2572. if (idx >= 0)
  2573. return font.chars[idx].height
  2574. }
  2575. return 0
  2576. }
  2577. function getKerning(font, left, right) {
  2578. if (!font.kernings || font.kernings.length === 0)
  2579. return 0
  2580. var table = font.kernings
  2581. for (var i=0; i<table.length; i++) {
  2582. var kern = table[i]
  2583. if (kern.first === left && kern.second === right)
  2584. return kern.amount
  2585. }
  2586. return 0
  2587. }
  2588. function getAlignType(align) {
  2589. if (align === 'center')
  2590. return ALIGN_CENTER
  2591. else if (align === 'right')
  2592. return ALIGN_RIGHT
  2593. return ALIGN_LEFT
  2594. }
  2595. function findChar (array, value, start) {
  2596. start = start || 0
  2597. for (var i = start; i < array.length; i++) {
  2598. if (array[i].id === value) {
  2599. return i
  2600. }
  2601. }
  2602. return -1
  2603. }
  2604. },{"as-number":3,"word-wrapper":47,"xtend":50}],23:[function(_dereq_,module,exports){
  2605. (function (Buffer){
  2606. var xhr = _dereq_('xhr')
  2607. var noop = function(){}
  2608. var parseASCII = _dereq_('parse-bmfont-ascii')
  2609. var parseXML = _dereq_('parse-bmfont-xml')
  2610. var readBinary = _dereq_('parse-bmfont-binary')
  2611. var isBinaryFormat = _dereq_('./lib/is-binary')
  2612. var xtend = _dereq_('xtend')
  2613. var xml2 = (function hasXML2() {
  2614. return self.XMLHttpRequest && "withCredentials" in new XMLHttpRequest
  2615. })()
  2616. module.exports = function(opt, cb) {
  2617. cb = typeof cb === 'function' ? cb : noop
  2618. if (typeof opt === 'string')
  2619. opt = { uri: opt }
  2620. else if (!opt)
  2621. opt = {}
  2622. var expectBinary = opt.binary
  2623. if (expectBinary)
  2624. opt = getBinaryOpts(opt)
  2625. xhr(opt, function(err, res, body) {
  2626. if (err)
  2627. return cb(err)
  2628. if (!/^2/.test(res.statusCode))
  2629. return cb(new Error('http status code: '+res.statusCode))
  2630. if (!body)
  2631. return cb(new Error('no body result'))
  2632. var binary = false
  2633. //if the response type is an array buffer,
  2634. //we need to convert it into a regular Buffer object
  2635. if (isArrayBuffer(body)) {
  2636. var array = new Uint8Array(body)
  2637. body = new Buffer(array, 'binary')
  2638. }
  2639. //now check the string/Buffer response
  2640. //and see if it has a binary BMF header
  2641. if (isBinaryFormat(body)) {
  2642. binary = true
  2643. //if we have a string, turn it into a Buffer
  2644. if (typeof body === 'string')
  2645. body = new Buffer(body, 'binary')
  2646. }
  2647. //we are not parsing a binary format, just ASCII/XML/etc
  2648. if (!binary) {
  2649. //might still be a buffer if responseType is 'arraybuffer'
  2650. if (Buffer.isBuffer(body))
  2651. body = body.toString(opt.encoding)
  2652. body = body.trim()
  2653. }
  2654. var result
  2655. try {
  2656. var type = res.headers['content-type']
  2657. if (binary)
  2658. result = readBinary(body)
  2659. else if (/json/.test(type) || body.charAt(0) === '{')
  2660. result = JSON.parse(body)
  2661. else if (/xml/.test(type) || body.charAt(0) === '<')
  2662. result = parseXML(body)
  2663. else
  2664. result = parseASCII(body)
  2665. } catch (e) {
  2666. cb(new Error('error parsing font '+e.message))
  2667. cb = noop
  2668. }
  2669. cb(null, result)
  2670. })
  2671. }
  2672. function isArrayBuffer(arr) {
  2673. var str = Object.prototype.toString
  2674. return str.call(arr) === '[object ArrayBuffer]'
  2675. }
  2676. function getBinaryOpts(opt) {
  2677. //IE10+ and other modern browsers support array buffers
  2678. if (xml2)
  2679. return xtend(opt, { responseType: 'arraybuffer' })
  2680. if (typeof self.XMLHttpRequest === 'undefined')
  2681. throw new Error('your browser does not support XHR loading')
  2682. //IE9 and XML1 browsers could still use an override
  2683. var req = new self.XMLHttpRequest()
  2684. req.overrideMimeType('text/plain; charset=x-user-defined')
  2685. return xtend({
  2686. xhr: req
  2687. }, opt)
  2688. }
  2689. }).call(this,_dereq_("buffer").Buffer)
  2690. },{"./lib/is-binary":24,"buffer":7,"parse-bmfont-ascii":26,"parse-bmfont-binary":27,"parse-bmfont-xml":28,"xhr":48,"xtend":50}],24:[function(_dereq_,module,exports){
  2691. (function (Buffer){
  2692. var equal = _dereq_('buffer-equal')
  2693. var HEADER = new Buffer([66, 77, 70, 3])
  2694. module.exports = function(buf) {
  2695. if (typeof buf === 'string')
  2696. return buf.substring(0, 3) === 'BMF'
  2697. return buf.length > 4 && equal(buf.slice(0, 4), HEADER)
  2698. }
  2699. }).call(this,_dereq_("buffer").Buffer)
  2700. },{"buffer":7,"buffer-equal":6}],25:[function(_dereq_,module,exports){
  2701. /*
  2702. object-assign
  2703. (c) Sindre Sorhus
  2704. @license MIT
  2705. */
  2706. 'use strict';
  2707. /* eslint-disable no-unused-vars */
  2708. var getOwnPropertySymbols = Object.getOwnPropertySymbols;
  2709. var hasOwnProperty = Object.prototype.hasOwnProperty;
  2710. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  2711. function toObject(val) {
  2712. if (val === null || val === undefined) {
  2713. throw new TypeError('Object.assign cannot be called with null or undefined');
  2714. }
  2715. return Object(val);
  2716. }
  2717. function shouldUseNative() {
  2718. try {
  2719. if (!Object.assign) {
  2720. return false;
  2721. }
  2722. // Detect buggy property enumeration order in older V8 versions.
  2723. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  2724. var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
  2725. test1[5] = 'de';
  2726. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  2727. return false;
  2728. }
  2729. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  2730. var test2 = {};
  2731. for (var i = 0; i < 10; i++) {
  2732. test2['_' + String.fromCharCode(i)] = i;
  2733. }
  2734. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  2735. return test2[n];
  2736. });
  2737. if (order2.join('') !== '0123456789') {
  2738. return false;
  2739. }
  2740. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  2741. var test3 = {};
  2742. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  2743. test3[letter] = letter;
  2744. });
  2745. if (Object.keys(Object.assign({}, test3)).join('') !==
  2746. 'abcdefghijklmnopqrst') {
  2747. return false;
  2748. }
  2749. return true;
  2750. } catch (err) {
  2751. // We don't expect any of the above to throw, but better to be safe.
  2752. return false;
  2753. }
  2754. }
  2755. module.exports = shouldUseNative() ? Object.assign : function (target, source) {
  2756. var from;
  2757. var to = toObject(target);
  2758. var symbols;
  2759. for (var s = 1; s < arguments.length; s++) {
  2760. from = Object(arguments[s]);
  2761. for (var key in from) {
  2762. if (hasOwnProperty.call(from, key)) {
  2763. to[key] = from[key];
  2764. }
  2765. }
  2766. if (getOwnPropertySymbols) {
  2767. symbols = getOwnPropertySymbols(from);
  2768. for (var i = 0; i < symbols.length; i++) {
  2769. if (propIsEnumerable.call(from, symbols[i])) {
  2770. to[symbols[i]] = from[symbols[i]];
  2771. }
  2772. }
  2773. }
  2774. }
  2775. return to;
  2776. };
  2777. },{}],26:[function(_dereq_,module,exports){
  2778. module.exports = function parseBMFontAscii(data) {
  2779. if (!data)
  2780. throw new Error('no data provided')
  2781. data = data.toString().trim()
  2782. var output = {
  2783. pages: [],
  2784. chars: [],
  2785. kernings: []
  2786. }
  2787. var lines = data.split(/\r\n?|\n/g)
  2788. if (lines.length === 0)
  2789. throw new Error('no data in BMFont file')
  2790. for (var i = 0; i < lines.length; i++) {
  2791. var lineData = splitLine(lines[i], i)
  2792. if (!lineData) //skip empty lines
  2793. continue
  2794. if (lineData.key === 'page') {
  2795. if (typeof lineData.data.id !== 'number')
  2796. throw new Error('malformed file at line ' + i + ' -- needs page id=N')
  2797. if (typeof lineData.data.file !== 'string')
  2798. throw new Error('malformed file at line ' + i + ' -- needs page file="path"')
  2799. output.pages[lineData.data.id] = lineData.data.file
  2800. } else if (lineData.key === 'chars' || lineData.key === 'kernings') {
  2801. //... do nothing for these two ...
  2802. } else if (lineData.key === 'char') {
  2803. output.chars.push(lineData.data)
  2804. } else if (lineData.key === 'kerning') {
  2805. output.kernings.push(lineData.data)
  2806. } else {
  2807. output[lineData.key] = lineData.data
  2808. }
  2809. }
  2810. return output
  2811. }
  2812. function splitLine(line, idx) {
  2813. line = line.replace(/\t+/g, ' ').trim()
  2814. if (!line)
  2815. return null
  2816. var space = line.indexOf(' ')
  2817. if (space === -1)
  2818. throw new Error("no named row at line " + idx)
  2819. var key = line.substring(0, space)
  2820. line = line.substring(space + 1)
  2821. //clear "letter" field as it is non-standard and
  2822. //requires additional complexity to parse " / = symbols
  2823. line = line.replace(/letter=[\'\"]\S+[\'\"]/gi, '')
  2824. line = line.split("=")
  2825. line = line.map(function(str) {
  2826. return str.trim().match((/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g))
  2827. })
  2828. var data = []
  2829. for (var i = 0; i < line.length; i++) {
  2830. var dt = line[i]
  2831. if (i === 0) {
  2832. data.push({
  2833. key: dt[0],
  2834. data: ""
  2835. })
  2836. } else if (i === line.length - 1) {
  2837. data[data.length - 1].data = parseData(dt[0])
  2838. } else {
  2839. data[data.length - 1].data = parseData(dt[0])
  2840. data.push({
  2841. key: dt[1],
  2842. data: ""
  2843. })
  2844. }
  2845. }
  2846. var out = {
  2847. key: key,
  2848. data: {}
  2849. }
  2850. data.forEach(function(v) {
  2851. out.data[v.key] = v.data;
  2852. })
  2853. return out
  2854. }
  2855. function parseData(data) {
  2856. if (!data || data.length === 0)
  2857. return ""
  2858. if (data.indexOf('"') === 0 || data.indexOf("'") === 0)
  2859. return data.substring(1, data.length - 1)
  2860. if (data.indexOf(',') !== -1)
  2861. return parseIntList(data)
  2862. return parseInt(data, 10)
  2863. }
  2864. function parseIntList(data) {
  2865. return data.split(',').map(function(val) {
  2866. return parseInt(val, 10)
  2867. })
  2868. }
  2869. },{}],27:[function(_dereq_,module,exports){
  2870. var HEADER = [66, 77, 70]
  2871. module.exports = function readBMFontBinary(buf) {
  2872. if (buf.length < 6)
  2873. throw new Error('invalid buffer length for BMFont')
  2874. var header = HEADER.every(function(byte, i) {
  2875. return buf.readUInt8(i) === byte
  2876. })
  2877. if (!header)
  2878. throw new Error('BMFont missing BMF byte header')
  2879. var i = 3
  2880. var vers = buf.readUInt8(i++)
  2881. if (vers > 3)
  2882. throw new Error('Only supports BMFont Binary v3 (BMFont App v1.10)')
  2883. var target = { kernings: [], chars: [] }
  2884. for (var b=0; b<5; b++)
  2885. i += readBlock(target, buf, i)
  2886. return target
  2887. }
  2888. function readBlock(target, buf, i) {
  2889. if (i > buf.length-1)
  2890. return 0
  2891. var blockID = buf.readUInt8(i++)
  2892. var blockSize = buf.readInt32LE(i)
  2893. i += 4
  2894. switch(blockID) {
  2895. case 1:
  2896. target.info = readInfo(buf, i)
  2897. break
  2898. case 2:
  2899. target.common = readCommon(buf, i)
  2900. break
  2901. case 3:
  2902. target.pages = readPages(buf, i, blockSize)
  2903. break
  2904. case 4:
  2905. target.chars = readChars(buf, i, blockSize)
  2906. break
  2907. case 5:
  2908. target.kernings = readKernings(buf, i, blockSize)
  2909. break
  2910. }
  2911. return 5 + blockSize
  2912. }
  2913. function readInfo(buf, i) {
  2914. var info = {}
  2915. info.size = buf.readInt16LE(i)
  2916. var bitField = buf.readUInt8(i+2)
  2917. info.smooth = (bitField >> 7) & 1
  2918. info.unicode = (bitField >> 6) & 1
  2919. info.italic = (bitField >> 5) & 1
  2920. info.bold = (bitField >> 4) & 1
  2921. //fixedHeight is only mentioned in binary spec
  2922. if ((bitField >> 3) & 1)
  2923. info.fixedHeight = 1
  2924. info.charset = buf.readUInt8(i+3) || ''
  2925. info.stretchH = buf.readUInt16LE(i+4)
  2926. info.aa = buf.readUInt8(i+6)
  2927. info.padding = [
  2928. buf.readInt8(i+7),
  2929. buf.readInt8(i+8),
  2930. buf.readInt8(i+9),
  2931. buf.readInt8(i+10)
  2932. ]
  2933. info.spacing = [
  2934. buf.readInt8(i+11),
  2935. buf.readInt8(i+12)
  2936. ]
  2937. info.outline = buf.readUInt8(i+13)
  2938. info.face = readStringNT(buf, i+14)
  2939. return info
  2940. }
  2941. function readCommon(buf, i) {
  2942. var common = {}
  2943. common.lineHeight = buf.readUInt16LE(i)
  2944. common.base = buf.readUInt16LE(i+2)
  2945. common.scaleW = buf.readUInt16LE(i+4)
  2946. common.scaleH = buf.readUInt16LE(i+6)
  2947. common.pages = buf.readUInt16LE(i+8)
  2948. var bitField = buf.readUInt8(i+10)
  2949. common.packed = 0
  2950. common.alphaChnl = buf.readUInt8(i+11)
  2951. common.redChnl = buf.readUInt8(i+12)
  2952. common.greenChnl = buf.readUInt8(i+13)
  2953. common.blueChnl = buf.readUInt8(i+14)
  2954. return common
  2955. }
  2956. function readPages(buf, i, size) {
  2957. var pages = []
  2958. var text = readNameNT(buf, i)
  2959. var len = text.length+1
  2960. var count = size / len
  2961. for (var c=0; c<count; c++) {
  2962. pages[c] = buf.slice(i, i+text.length).toString('utf8')
  2963. i += len
  2964. }
  2965. return pages
  2966. }
  2967. function readChars(buf, i, blockSize) {
  2968. var chars = []
  2969. var count = blockSize / 20
  2970. for (var c=0; c<count; c++) {
  2971. var char = {}
  2972. var off = c*20
  2973. char.id = buf.readUInt32LE(i + 0 + off)
  2974. char.x = buf.readUInt16LE(i + 4 + off)
  2975. char.y = buf.readUInt16LE(i + 6 + off)
  2976. char.width = buf.readUInt16LE(i + 8 + off)
  2977. char.height = buf.readUInt16LE(i + 10 + off)
  2978. char.xoffset = buf.readInt16LE(i + 12 + off)
  2979. char.yoffset = buf.readInt16LE(i + 14 + off)
  2980. char.xadvance = buf.readInt16LE(i + 16 + off)
  2981. char.page = buf.readUInt8(i + 18 + off)
  2982. char.chnl = buf.readUInt8(i + 19 + off)
  2983. chars[c] = char
  2984. }
  2985. return chars
  2986. }
  2987. function readKernings(buf, i, blockSize) {
  2988. var kernings = []
  2989. var count = blockSize / 10
  2990. for (var c=0; c<count; c++) {
  2991. var kern = {}
  2992. var off = c*10
  2993. kern.first = buf.readUInt32LE(i + 0 + off)
  2994. kern.second = buf.readUInt32LE(i + 4 + off)
  2995. kern.amount = buf.readInt16LE(i + 8 + off)
  2996. kernings[c] = kern
  2997. }
  2998. return kernings
  2999. }
  3000. function readNameNT(buf, offset) {
  3001. var pos=offset
  3002. for (; pos<buf.length; pos++) {
  3003. if (buf[pos] === 0x00)
  3004. break
  3005. }
  3006. return buf.slice(offset, pos)
  3007. }
  3008. function readStringNT(buf, offset) {
  3009. return readNameNT(buf, offset).toString('utf8')
  3010. }
  3011. },{}],28:[function(_dereq_,module,exports){
  3012. var parseAttributes = _dereq_('./parse-attribs')
  3013. var parseFromString = _dereq_('xml-parse-from-string')
  3014. //In some cases element.attribute.nodeName can return
  3015. //all lowercase values.. so we need to map them to the correct
  3016. //case
  3017. var NAME_MAP = {
  3018. scaleh: 'scaleH',
  3019. scalew: 'scaleW',
  3020. stretchh: 'stretchH',
  3021. lineheight: 'lineHeight',
  3022. alphachnl: 'alphaChnl',
  3023. redchnl: 'redChnl',
  3024. greenchnl: 'greenChnl',
  3025. bluechnl: 'blueChnl'
  3026. }
  3027. module.exports = function parse(data) {
  3028. data = data.toString()
  3029. var xmlRoot = parseFromString(data)
  3030. var output = {
  3031. pages: [],
  3032. chars: [],
  3033. kernings: []
  3034. }
  3035. //get config settings
  3036. ;['info', 'common'].forEach(function(key) {
  3037. var element = xmlRoot.getElementsByTagName(key)[0]
  3038. if (element)
  3039. output[key] = parseAttributes(getAttribs(element))
  3040. })
  3041. //get page info
  3042. var pageRoot = xmlRoot.getElementsByTagName('pages')[0]
  3043. if (!pageRoot)
  3044. throw new Error('malformed file -- no <pages> element')
  3045. var pages = pageRoot.getElementsByTagName('page')
  3046. for (var i=0; i<pages.length; i++) {
  3047. var p = pages[i]
  3048. var id = parseInt(p.getAttribute('id'), 10)
  3049. var file = p.getAttribute('file')
  3050. if (isNaN(id))
  3051. throw new Error('malformed file -- page "id" attribute is NaN')
  3052. if (!file)
  3053. throw new Error('malformed file -- needs page "file" attribute')
  3054. output.pages[parseInt(id, 10)] = file
  3055. }
  3056. //get kernings / chars
  3057. ;['chars', 'kernings'].forEach(function(key) {
  3058. var element = xmlRoot.getElementsByTagName(key)[0]
  3059. if (!element)
  3060. return
  3061. var childTag = key.substring(0, key.length-1)
  3062. var children = element.getElementsByTagName(childTag)
  3063. for (var i=0; i<children.length; i++) {
  3064. var child = children[i]
  3065. output[key].push(parseAttributes(getAttribs(child)))
  3066. }
  3067. })
  3068. return output
  3069. }
  3070. function getAttribs(element) {
  3071. var attribs = getAttribList(element)
  3072. return attribs.reduce(function(dict, attrib) {
  3073. var key = mapName(attrib.nodeName)
  3074. dict[key] = attrib.nodeValue
  3075. return dict
  3076. }, {})
  3077. }
  3078. function getAttribList(element) {
  3079. //IE8+ and modern browsers
  3080. var attribs = []
  3081. for (var i=0; i<element.attributes.length; i++)
  3082. attribs.push(element.attributes[i])
  3083. return attribs
  3084. }
  3085. function mapName(nodeName) {
  3086. return NAME_MAP[nodeName.toLowerCase()] || nodeName
  3087. }
  3088. },{"./parse-attribs":29,"xml-parse-from-string":49}],29:[function(_dereq_,module,exports){
  3089. //Some versions of GlyphDesigner have a typo
  3090. //that causes some bugs with parsing.
  3091. //Need to confirm with recent version of the software
  3092. //to see whether this is still an issue or not.
  3093. var GLYPH_DESIGNER_ERROR = 'chasrset'
  3094. module.exports = function parseAttributes(obj) {
  3095. if (GLYPH_DESIGNER_ERROR in obj) {
  3096. obj['charset'] = obj[GLYPH_DESIGNER_ERROR]
  3097. delete obj[GLYPH_DESIGNER_ERROR]
  3098. }
  3099. for (var k in obj) {
  3100. if (k === 'face' || k === 'charset')
  3101. continue
  3102. else if (k === 'padding' || k === 'spacing')
  3103. obj[k] = parseIntList(obj[k])
  3104. else
  3105. obj[k] = parseInt(obj[k], 10)
  3106. }
  3107. return obj
  3108. }
  3109. function parseIntList(data) {
  3110. return data.split(',').map(function(val) {
  3111. return parseInt(val, 10)
  3112. })
  3113. }
  3114. },{}],30:[function(_dereq_,module,exports){
  3115. var trim = _dereq_('trim')
  3116. , forEach = _dereq_('for-each')
  3117. , isArray = function(arg) {
  3118. return Object.prototype.toString.call(arg) === '[object Array]';
  3119. }
  3120. module.exports = function (headers) {
  3121. if (!headers)
  3122. return {}
  3123. var result = {}
  3124. forEach(
  3125. trim(headers).split('\n')
  3126. , function (row) {
  3127. var index = row.indexOf(':')
  3128. , key = trim(row.slice(0, index)).toLowerCase()
  3129. , value = trim(row.slice(index + 1))
  3130. if (typeof(result[key]) === 'undefined') {
  3131. result[key] = value
  3132. } else if (isArray(result[key])) {
  3133. result[key].push(value)
  3134. } else {
  3135. result[key] = [ result[key], value ]
  3136. }
  3137. }
  3138. )
  3139. return result
  3140. }
  3141. },{"for-each":14,"trim":45}],31:[function(_dereq_,module,exports){
  3142. (function (global){
  3143. var performance = global.performance || {};
  3144. var present = (function () {
  3145. var names = ['now', 'webkitNow', 'msNow', 'mozNow', 'oNow'];
  3146. while (names.length) {
  3147. var name = names.shift();
  3148. if (name in performance) {
  3149. return performance[name].bind(performance);
  3150. }
  3151. }
  3152. var dateNow = Date.now || function () { return new Date().getTime(); };
  3153. var navigationStart = (performance.timing || {}).navigationStart || dateNow();
  3154. return function () {
  3155. return dateNow() - navigationStart;
  3156. };
  3157. }());
  3158. present.performanceNow = performance.now;
  3159. present.noConflict = function () {
  3160. performance.now = present.performanceNow;
  3161. };
  3162. present.conflict = function () {
  3163. performance.now = present;
  3164. };
  3165. present.conflict();
  3166. module.exports = present;
  3167. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3168. },{}],32:[function(_dereq_,module,exports){
  3169. // shim for using process in browser
  3170. var process = module.exports = {};
  3171. // cached from whatever global is present so that test runners that stub it
  3172. // don't break things. But we need to wrap it in a try catch in case it is
  3173. // wrapped in strict mode code which doesn't define any globals. It's inside a
  3174. // function because try/catches deoptimize in certain engines.
  3175. var cachedSetTimeout;
  3176. var cachedClearTimeout;
  3177. function defaultSetTimout() {
  3178. throw new Error('setTimeout has not been defined');
  3179. }
  3180. function defaultClearTimeout () {
  3181. throw new Error('clearTimeout has not been defined');
  3182. }
  3183. (function () {
  3184. try {
  3185. if (typeof setTimeout === 'function') {
  3186. cachedSetTimeout = setTimeout;
  3187. } else {
  3188. cachedSetTimeout = defaultSetTimout;
  3189. }
  3190. } catch (e) {
  3191. cachedSetTimeout = defaultSetTimout;
  3192. }
  3193. try {
  3194. if (typeof clearTimeout === 'function') {
  3195. cachedClearTimeout = clearTimeout;
  3196. } else {
  3197. cachedClearTimeout = defaultClearTimeout;
  3198. }
  3199. } catch (e) {
  3200. cachedClearTimeout = defaultClearTimeout;
  3201. }
  3202. } ())
  3203. function runTimeout(fun) {
  3204. if (cachedSetTimeout === setTimeout) {
  3205. //normal enviroments in sane situations
  3206. return setTimeout(fun, 0);
  3207. }
  3208. // if setTimeout wasn't available but was latter defined
  3209. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  3210. cachedSetTimeout = setTimeout;
  3211. return setTimeout(fun, 0);
  3212. }
  3213. try {
  3214. // when when somebody has screwed with setTimeout but no I.E. maddness
  3215. return cachedSetTimeout(fun, 0);
  3216. } catch(e){
  3217. try {
  3218. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  3219. return cachedSetTimeout.call(null, fun, 0);
  3220. } catch(e){
  3221. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  3222. return cachedSetTimeout.call(this, fun, 0);
  3223. }
  3224. }
  3225. }
  3226. function runClearTimeout(marker) {
  3227. if (cachedClearTimeout === clearTimeout) {
  3228. //normal enviroments in sane situations
  3229. return clearTimeout(marker);
  3230. }
  3231. // if clearTimeout wasn't available but was latter defined
  3232. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  3233. cachedClearTimeout = clearTimeout;
  3234. return clearTimeout(marker);
  3235. }
  3236. try {
  3237. // when when somebody has screwed with setTimeout but no I.E. maddness
  3238. return cachedClearTimeout(marker);
  3239. } catch (e){
  3240. try {
  3241. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  3242. return cachedClearTimeout.call(null, marker);
  3243. } catch (e){
  3244. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  3245. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  3246. return cachedClearTimeout.call(this, marker);
  3247. }
  3248. }
  3249. }
  3250. var queue = [];
  3251. var draining = false;
  3252. var currentQueue;
  3253. var queueIndex = -1;
  3254. function cleanUpNextTick() {
  3255. if (!draining || !currentQueue) {
  3256. return;
  3257. }
  3258. draining = false;
  3259. if (currentQueue.length) {
  3260. queue = currentQueue.concat(queue);
  3261. } else {
  3262. queueIndex = -1;
  3263. }
  3264. if (queue.length) {
  3265. drainQueue();
  3266. }
  3267. }
  3268. function drainQueue() {
  3269. if (draining) {
  3270. return;
  3271. }
  3272. var timeout = runTimeout(cleanUpNextTick);
  3273. draining = true;
  3274. var len = queue.length;
  3275. while(len) {
  3276. currentQueue = queue;
  3277. queue = [];
  3278. while (++queueIndex < len) {
  3279. if (currentQueue) {
  3280. currentQueue[queueIndex].run();
  3281. }
  3282. }
  3283. queueIndex = -1;
  3284. len = queue.length;
  3285. }
  3286. currentQueue = null;
  3287. draining = false;
  3288. runClearTimeout(timeout);
  3289. }
  3290. process.nextTick = function (fun) {
  3291. var args = new Array(arguments.length - 1);
  3292. if (arguments.length > 1) {
  3293. for (var i = 1; i < arguments.length; i++) {
  3294. args[i - 1] = arguments[i];
  3295. }
  3296. }
  3297. queue.push(new Item(fun, args));
  3298. if (queue.length === 1 && !draining) {
  3299. runTimeout(drainQueue);
  3300. }
  3301. };
  3302. // v8 likes predictible objects
  3303. function Item(fun, array) {
  3304. this.fun = fun;
  3305. this.array = array;
  3306. }
  3307. Item.prototype.run = function () {
  3308. this.fun.apply(null, this.array);
  3309. };
  3310. process.title = 'browser';
  3311. process.browser = true;
  3312. process.env = {};
  3313. process.argv = [];
  3314. process.version = ''; // empty string to avoid regexp issues
  3315. process.versions = {};
  3316. function noop() {}
  3317. process.on = noop;
  3318. process.addListener = noop;
  3319. process.once = noop;
  3320. process.off = noop;
  3321. process.removeListener = noop;
  3322. process.removeAllListeners = noop;
  3323. process.emit = noop;
  3324. process.prependListener = noop;
  3325. process.prependOnceListener = noop;
  3326. process.listeners = function (name) { return [] }
  3327. process.binding = function (name) {
  3328. throw new Error('process.binding is not supported');
  3329. };
  3330. process.cwd = function () { return '/' };
  3331. process.chdir = function (dir) {
  3332. throw new Error('process.chdir is not supported');
  3333. };
  3334. process.umask = function() { return 0; };
  3335. },{}],33:[function(_dereq_,module,exports){
  3336. (function(root) {
  3337. // Store setTimeout reference so promise-polyfill will be unaffected by
  3338. // other code modifying setTimeout (like sinon.useFakeTimers())
  3339. var setTimeoutFunc = setTimeout;
  3340. // Use polyfill for setImmediate for performance gains
  3341. var asap = (typeof setImmediate === 'function' && setImmediate) ||
  3342. function(fn) { setTimeoutFunc(fn, 1); };
  3343. // Polyfill for Function.prototype.bind
  3344. function bind(fn, thisArg) {
  3345. return function() {
  3346. fn.apply(thisArg, arguments);
  3347. }
  3348. }
  3349. var isArray = Array.isArray || function(value) { return Object.prototype.toString.call(value) === "[object Array]" };
  3350. function Promise(fn) {
  3351. if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
  3352. if (typeof fn !== 'function') throw new TypeError('not a function');
  3353. this._state = null;
  3354. this._value = null;
  3355. this._deferreds = []
  3356. doResolve(fn, bind(resolve, this), bind(reject, this))
  3357. }
  3358. function handle(deferred) {
  3359. var me = this;
  3360. if (this._state === null) {
  3361. this._deferreds.push(deferred);
  3362. return
  3363. }
  3364. asap(function() {
  3365. var cb = me._state ? deferred.onFulfilled : deferred.onRejected
  3366. if (cb === null) {
  3367. (me._state ? deferred.resolve : deferred.reject)(me._value);
  3368. return;
  3369. }
  3370. var ret;
  3371. try {
  3372. ret = cb(me._value);
  3373. }
  3374. catch (e) {
  3375. deferred.reject(e);
  3376. return;
  3377. }
  3378. deferred.resolve(ret);
  3379. })
  3380. }
  3381. function resolve(newValue) {
  3382. try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
  3383. if (newValue === this) throw new TypeError('A promise cannot be resolved with itself.');
  3384. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  3385. var then = newValue.then;
  3386. if (typeof then === 'function') {
  3387. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  3388. return;
  3389. }
  3390. }
  3391. this._state = true;
  3392. this._value = newValue;
  3393. finale.call(this);
  3394. } catch (e) { reject.call(this, e); }
  3395. }
  3396. function reject(newValue) {
  3397. this._state = false;
  3398. this._value = newValue;
  3399. finale.call(this);
  3400. }
  3401. function finale() {
  3402. for (var i = 0, len = this._deferreds.length; i < len; i++) {
  3403. handle.call(this, this._deferreds[i]);
  3404. }
  3405. this._deferreds = null;
  3406. }
  3407. function Handler(onFulfilled, onRejected, resolve, reject){
  3408. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  3409. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  3410. this.resolve = resolve;
  3411. this.reject = reject;
  3412. }
  3413. /**
  3414. * Take a potentially misbehaving resolver function and make sure
  3415. * onFulfilled and onRejected are only called once.
  3416. *
  3417. * Makes no guarantees about asynchrony.
  3418. */
  3419. function doResolve(fn, onFulfilled, onRejected) {
  3420. var done = false;
  3421. try {
  3422. fn(function (value) {
  3423. if (done) return;
  3424. done = true;
  3425. onFulfilled(value);
  3426. }, function (reason) {
  3427. if (done) return;
  3428. done = true;
  3429. onRejected(reason);
  3430. })
  3431. } catch (ex) {
  3432. if (done) return;
  3433. done = true;
  3434. onRejected(ex);
  3435. }
  3436. }
  3437. Promise.prototype['catch'] = function (onRejected) {
  3438. return this.then(null, onRejected);
  3439. };
  3440. Promise.prototype.then = function(onFulfilled, onRejected) {
  3441. var me = this;
  3442. return new Promise(function(resolve, reject) {
  3443. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  3444. })
  3445. };
  3446. Promise.all = function () {
  3447. var args = Array.prototype.slice.call(arguments.length === 1 && isArray(arguments[0]) ? arguments[0] : arguments);
  3448. return new Promise(function (resolve, reject) {
  3449. if (args.length === 0) return resolve([]);
  3450. var remaining = args.length;
  3451. function res(i, val) {
  3452. try {
  3453. if (val && (typeof val === 'object' || typeof val === 'function')) {
  3454. var then = val.then;
  3455. if (typeof then === 'function') {
  3456. then.call(val, function (val) { res(i, val) }, reject);
  3457. return;
  3458. }
  3459. }
  3460. args[i] = val;
  3461. if (--remaining === 0) {
  3462. resolve(args);
  3463. }
  3464. } catch (ex) {
  3465. reject(ex);
  3466. }
  3467. }
  3468. for (var i = 0; i < args.length; i++) {
  3469. res(i, args[i]);
  3470. }
  3471. });
  3472. };
  3473. Promise.resolve = function (value) {
  3474. if (value && typeof value === 'object' && value.constructor === Promise) {
  3475. return value;
  3476. }
  3477. return new Promise(function (resolve) {
  3478. resolve(value);
  3479. });
  3480. };
  3481. Promise.reject = function (value) {
  3482. return new Promise(function (resolve, reject) {
  3483. reject(value);
  3484. });
  3485. };
  3486. Promise.race = function (values) {
  3487. return new Promise(function (resolve, reject) {
  3488. for(var i = 0, len = values.length; i < len; i++) {
  3489. values[i].then(resolve, reject);
  3490. }
  3491. });
  3492. };
  3493. /**
  3494. * Set the immediate function to execute callbacks
  3495. * @param fn {function} Function to execute
  3496. * @private
  3497. */
  3498. Promise._setImmediateFn = function _setImmediateFn(fn) {
  3499. asap = fn;
  3500. };
  3501. if (typeof module !== 'undefined' && module.exports) {
  3502. module.exports = Promise;
  3503. } else if (!root.Promise) {
  3504. root.Promise = Promise;
  3505. }
  3506. })(this);
  3507. },{}],34:[function(_dereq_,module,exports){
  3508. var dtype = _dereq_('dtype')
  3509. var anArray = _dereq_('an-array')
  3510. var isBuffer = _dereq_('is-buffer')
  3511. var CW = [0, 2, 3]
  3512. var CCW = [2, 1, 3]
  3513. module.exports = function createQuadElements(array, opt) {
  3514. //if user didn't specify an output array
  3515. if (!array || !(anArray(array) || isBuffer(array))) {
  3516. opt = array || {}
  3517. array = null
  3518. }
  3519. if (typeof opt === 'number') //backwards-compatible
  3520. opt = { count: opt }
  3521. else
  3522. opt = opt || {}
  3523. var type = typeof opt.type === 'string' ? opt.type : 'uint16'
  3524. var count = typeof opt.count === 'number' ? opt.count : 1
  3525. var start = (opt.start || 0)
  3526. var dir = opt.clockwise !== false ? CW : CCW,
  3527. a = dir[0],
  3528. b = dir[1],
  3529. c = dir[2]
  3530. var numIndices = count * 6
  3531. var indices = array || new (dtype(type))(numIndices)
  3532. for (var i = 0, j = 0; i < numIndices; i += 6, j += 4) {
  3533. var x = i + start
  3534. indices[x + 0] = j + 0
  3535. indices[x + 1] = j + 1
  3536. indices[x + 2] = j + 2
  3537. indices[x + 3] = j + a
  3538. indices[x + 4] = j + b
  3539. indices[x + 5] = j + c
  3540. }
  3541. return indices
  3542. }
  3543. },{"an-array":1,"dtype":12,"is-buffer":18}],35:[function(_dereq_,module,exports){
  3544. var createLayout = _dereq_('layout-bmfont-text')
  3545. var inherits = _dereq_('inherits')
  3546. var createIndices = _dereq_('quad-indices')
  3547. var buffer = _dereq_('three-buffer-vertex-data')
  3548. var assign = _dereq_('object-assign')
  3549. var vertices = _dereq_('./lib/vertices')
  3550. var utils = _dereq_('./lib/utils')
  3551. var Base = THREE.BufferGeometry
  3552. module.exports = function createTextGeometry (opt) {
  3553. return new TextGeometry(opt)
  3554. }
  3555. function TextGeometry (opt) {
  3556. Base.call(this)
  3557. if (typeof opt === 'string') {
  3558. opt = { text: opt }
  3559. }
  3560. // use these as default values for any subsequent
  3561. // calls to update()
  3562. this._opt = assign({}, opt)
  3563. // also do an initial setup...
  3564. if (opt) this.update(opt)
  3565. }
  3566. inherits(TextGeometry, Base)
  3567. TextGeometry.prototype.update = function (opt) {
  3568. if (typeof opt === 'string') {
  3569. opt = { text: opt }
  3570. }
  3571. // use constructor defaults
  3572. opt = assign({}, this._opt, opt)
  3573. if (!opt.font) {
  3574. throw new TypeError('must specify a { font } in options')
  3575. }
  3576. this.layout = createLayout(opt)
  3577. // get vec2 texcoords
  3578. var flipY = opt.flipY !== false
  3579. // the desired BMFont data
  3580. var font = opt.font
  3581. // determine texture size from font file
  3582. var texWidth = font.common.scaleW
  3583. var texHeight = font.common.scaleH
  3584. // get visible glyphs
  3585. var glyphs = this.layout.glyphs.filter(function (glyph) {
  3586. var bitmap = glyph.data
  3587. return bitmap.width * bitmap.height > 0
  3588. })
  3589. // provide visible glyphs for convenience
  3590. this.visibleGlyphs = glyphs
  3591. // get common vertex data
  3592. var positions = vertices.positions(glyphs)
  3593. var uvs = vertices.uvs(glyphs, texWidth, texHeight, flipY)
  3594. var indices = createIndices({
  3595. clockwise: true,
  3596. type: 'uint16',
  3597. count: glyphs.length
  3598. })
  3599. // update vertex data
  3600. buffer.index(this, indices, 1, 'uint16')
  3601. buffer.attr(this, 'position', positions, 2)
  3602. buffer.attr(this, 'uv', uvs, 2)
  3603. // update multipage data
  3604. if (!opt.multipage && 'page' in this.attributes) {
  3605. // disable multipage rendering
  3606. this.removeAttribute('page')
  3607. } else if (opt.multipage) {
  3608. var pages = vertices.pages(glyphs)
  3609. // enable multipage rendering
  3610. buffer.attr(this, 'page', pages, 1)
  3611. }
  3612. }
  3613. TextGeometry.prototype.computeBoundingSphere = function () {
  3614. if (this.boundingSphere === null) {
  3615. this.boundingSphere = new THREE.Sphere()
  3616. }
  3617. var positions = this.attributes.position.array
  3618. var itemSize = this.attributes.position.itemSize
  3619. if (!positions || !itemSize || positions.length < 2) {
  3620. this.boundingSphere.radius = 0
  3621. this.boundingSphere.center.set(0, 0, 0)
  3622. return
  3623. }
  3624. utils.computeSphere(positions, this.boundingSphere)
  3625. if (isNaN(this.boundingSphere.radius)) {
  3626. console.error('THREE.BufferGeometry.computeBoundingSphere(): ' +
  3627. 'Computed radius is NaN. The ' +
  3628. '"position" attribute is likely to have NaN values.')
  3629. }
  3630. }
  3631. TextGeometry.prototype.computeBoundingBox = function () {
  3632. if (this.boundingBox === null) {
  3633. this.boundingBox = new THREE.Box3()
  3634. }
  3635. var bbox = this.boundingBox
  3636. var positions = this.attributes.position.array
  3637. var itemSize = this.attributes.position.itemSize
  3638. if (!positions || !itemSize || positions.length < 2) {
  3639. bbox.makeEmpty()
  3640. return
  3641. }
  3642. utils.computeBox(positions, bbox)
  3643. }
  3644. },{"./lib/utils":36,"./lib/vertices":37,"inherits":17,"layout-bmfont-text":22,"object-assign":25,"quad-indices":34,"three-buffer-vertex-data":38}],36:[function(_dereq_,module,exports){
  3645. var itemSize = 2
  3646. var box = { min: [0, 0], max: [0, 0] }
  3647. function bounds (positions) {
  3648. var count = positions.length / itemSize
  3649. box.min[0] = positions[0]
  3650. box.min[1] = positions[1]
  3651. box.max[0] = positions[0]
  3652. box.max[1] = positions[1]
  3653. for (var i = 0; i < count; i++) {
  3654. var x = positions[i * itemSize + 0]
  3655. var y = positions[i * itemSize + 1]
  3656. box.min[0] = Math.min(x, box.min[0])
  3657. box.min[1] = Math.min(y, box.min[1])
  3658. box.max[0] = Math.max(x, box.max[0])
  3659. box.max[1] = Math.max(y, box.max[1])
  3660. }
  3661. }
  3662. module.exports.computeBox = function (positions, output) {
  3663. bounds(positions)
  3664. output.min.set(box.min[0], box.min[1], 0)
  3665. output.max.set(box.max[0], box.max[1], 0)
  3666. }
  3667. module.exports.computeSphere = function (positions, output) {
  3668. bounds(positions)
  3669. var minX = box.min[0]
  3670. var minY = box.min[1]
  3671. var maxX = box.max[0]
  3672. var maxY = box.max[1]
  3673. var width = maxX - minX
  3674. var height = maxY - minY
  3675. var length = Math.sqrt(width * width + height * height)
  3676. output.center.set(minX + width / 2, minY + height / 2, 0)
  3677. output.radius = length / 2
  3678. }
  3679. },{}],37:[function(_dereq_,module,exports){
  3680. module.exports.pages = function pages (glyphs) {
  3681. var pages = new Float32Array(glyphs.length * 4 * 1)
  3682. var i = 0
  3683. glyphs.forEach(function (glyph) {
  3684. var id = glyph.data.page || 0
  3685. pages[i++] = id
  3686. pages[i++] = id
  3687. pages[i++] = id
  3688. pages[i++] = id
  3689. })
  3690. return pages
  3691. }
  3692. module.exports.uvs = function uvs (glyphs, texWidth, texHeight, flipY) {
  3693. var uvs = new Float32Array(glyphs.length * 4 * 2)
  3694. var i = 0
  3695. glyphs.forEach(function (glyph) {
  3696. var bitmap = glyph.data
  3697. var bw = (bitmap.x + bitmap.width)
  3698. var bh = (bitmap.y + bitmap.height)
  3699. // top left position
  3700. var u0 = bitmap.x / texWidth
  3701. var v1 = bitmap.y / texHeight
  3702. var u1 = bw / texWidth
  3703. var v0 = bh / texHeight
  3704. if (flipY) {
  3705. v1 = (texHeight - bitmap.y) / texHeight
  3706. v0 = (texHeight - bh) / texHeight
  3707. }
  3708. // BL
  3709. uvs[i++] = u0
  3710. uvs[i++] = v1
  3711. // TL
  3712. uvs[i++] = u0
  3713. uvs[i++] = v0
  3714. // TR
  3715. uvs[i++] = u1
  3716. uvs[i++] = v0
  3717. // BR
  3718. uvs[i++] = u1
  3719. uvs[i++] = v1
  3720. })
  3721. return uvs
  3722. }
  3723. module.exports.positions = function positions (glyphs) {
  3724. var positions = new Float32Array(glyphs.length * 4 * 2)
  3725. var i = 0
  3726. glyphs.forEach(function (glyph) {
  3727. var bitmap = glyph.data
  3728. // bottom left position
  3729. var x = glyph.position[0] + bitmap.xoffset
  3730. var y = glyph.position[1] + bitmap.yoffset
  3731. // quad size
  3732. var w = bitmap.width
  3733. var h = bitmap.height
  3734. // BL
  3735. positions[i++] = x
  3736. positions[i++] = y
  3737. // TL
  3738. positions[i++] = x
  3739. positions[i++] = y + h
  3740. // TR
  3741. positions[i++] = x + w
  3742. positions[i++] = y + h
  3743. // BR
  3744. positions[i++] = x + w
  3745. positions[i++] = y
  3746. })
  3747. return positions
  3748. }
  3749. },{}],38:[function(_dereq_,module,exports){
  3750. var flatten = _dereq_('flatten-vertex-data')
  3751. var warned = false;
  3752. module.exports.attr = setAttribute
  3753. module.exports.index = setIndex
  3754. function setIndex (geometry, data, itemSize, dtype) {
  3755. if (typeof itemSize !== 'number') itemSize = 1
  3756. if (typeof dtype !== 'string') dtype = 'uint16'
  3757. var isR69 = !geometry.index && typeof geometry.setIndex !== 'function'
  3758. var attrib = isR69 ? geometry.getAttribute('index') : geometry.index
  3759. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  3760. if (newAttrib) {
  3761. if (isR69) geometry.addAttribute('index', newAttrib)
  3762. else geometry.index = newAttrib
  3763. }
  3764. }
  3765. function setAttribute (geometry, key, data, itemSize, dtype) {
  3766. if (typeof itemSize !== 'number') itemSize = 3
  3767. if (typeof dtype !== 'string') dtype = 'float32'
  3768. if (Array.isArray(data) &&
  3769. Array.isArray(data[0]) &&
  3770. data[0].length !== itemSize) {
  3771. throw new Error('Nested vertex array has unexpected size; expected ' +
  3772. itemSize + ' but found ' + data[0].length)
  3773. }
  3774. var attrib = geometry.getAttribute(key)
  3775. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  3776. if (newAttrib) {
  3777. geometry.addAttribute(key, newAttrib)
  3778. }
  3779. }
  3780. function updateAttribute (attrib, data, itemSize, dtype) {
  3781. data = data || []
  3782. if (!attrib || rebuildAttribute(attrib, data, itemSize)) {
  3783. // create a new array with desired type
  3784. data = flatten(data, dtype)
  3785. var needsNewBuffer = attrib && typeof attrib.setArray !== 'function'
  3786. if (!attrib || needsNewBuffer) {
  3787. // We are on an old version of ThreeJS which can't
  3788. // support growing / shrinking buffers, so we need
  3789. // to build a new buffer
  3790. if (needsNewBuffer && !warned) {
  3791. warned = true
  3792. console.warn([
  3793. 'A WebGL buffer is being updated with a new size or itemSize, ',
  3794. 'however this version of ThreeJS only supports fixed-size buffers.',
  3795. '\nThe old buffer may still be kept in memory.\n',
  3796. 'To avoid memory leaks, it is recommended that you dispose ',
  3797. 'your geometries and create new ones, or update to ThreeJS r82 or newer.\n',
  3798. 'See here for discussion:\n',
  3799. 'https://github.com/mrdoob/three.js/pull/9631'
  3800. ].join(''))
  3801. }
  3802. // Build a new attribute
  3803. attrib = new THREE.BufferAttribute(data, itemSize);
  3804. }
  3805. attrib.itemSize = itemSize
  3806. attrib.needsUpdate = true
  3807. // New versions of ThreeJS suggest using setArray
  3808. // to change the data. It will use bufferData internally,
  3809. // so you can change the array size without any issues
  3810. if (typeof attrib.setArray === 'function') {
  3811. attrib.setArray(data)
  3812. }
  3813. return attrib
  3814. } else {
  3815. // copy data into the existing array
  3816. flatten(data, attrib.array)
  3817. attrib.needsUpdate = true
  3818. return null
  3819. }
  3820. }
  3821. // Test whether the attribute needs to be re-created,
  3822. // returns false if we can re-use it as-is.
  3823. function rebuildAttribute (attrib, data, itemSize) {
  3824. if (attrib.itemSize !== itemSize) return true
  3825. if (!attrib.array) return true
  3826. var attribLength = attrib.array.length
  3827. if (Array.isArray(data) && Array.isArray(data[0])) {
  3828. // [ [ x, y, z ] ]
  3829. return attribLength !== data.length * itemSize
  3830. } else {
  3831. // [ x, y, z ]
  3832. return attribLength !== data.length
  3833. }
  3834. return false
  3835. }
  3836. },{"flatten-vertex-data":13}],39:[function(_dereq_,module,exports){
  3837. (function (global, factory) {
  3838. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3839. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  3840. (factory((global.THREE = {})));
  3841. }(this, (function (exports) { 'use strict';
  3842. // Polyfills
  3843. if ( Number.EPSILON === undefined ) {
  3844. Number.EPSILON = Math.pow( 2, - 52 );
  3845. }
  3846. if ( Number.isInteger === undefined ) {
  3847. // Missing in IE
  3848. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  3849. Number.isInteger = function ( value ) {
  3850. return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value;
  3851. };
  3852. }
  3853. //
  3854. if ( Math.sign === undefined ) {
  3855. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  3856. Math.sign = function ( x ) {
  3857. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  3858. };
  3859. }
  3860. if ( 'name' in Function.prototype === false ) {
  3861. // Missing in IE
  3862. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  3863. Object.defineProperty( Function.prototype, 'name', {
  3864. get: function () {
  3865. return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
  3866. }
  3867. } );
  3868. }
  3869. if ( Object.assign === undefined ) {
  3870. // Missing in IE
  3871. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  3872. ( function () {
  3873. Object.assign = function ( target ) {
  3874. if ( target === undefined || target === null ) {
  3875. throw new TypeError( 'Cannot convert undefined or null to object' );
  3876. }
  3877. var output = Object( target );
  3878. for ( var index = 1; index < arguments.length; index ++ ) {
  3879. var source = arguments[ index ];
  3880. if ( source !== undefined && source !== null ) {
  3881. for ( var nextKey in source ) {
  3882. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  3883. output[ nextKey ] = source[ nextKey ];
  3884. }
  3885. }
  3886. }
  3887. }
  3888. return output;
  3889. };
  3890. } )();
  3891. }
  3892. /**
  3893. * https://github.com/mrdoob/eventdispatcher.js/
  3894. */
  3895. function EventDispatcher() {}
  3896. Object.assign( EventDispatcher.prototype, {
  3897. addEventListener: function ( type, listener ) {
  3898. if ( this._listeners === undefined ) this._listeners = {};
  3899. var listeners = this._listeners;
  3900. if ( listeners[ type ] === undefined ) {
  3901. listeners[ type ] = [];
  3902. }
  3903. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3904. listeners[ type ].push( listener );
  3905. }
  3906. },
  3907. hasEventListener: function ( type, listener ) {
  3908. if ( this._listeners === undefined ) return false;
  3909. var listeners = this._listeners;
  3910. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  3911. },
  3912. removeEventListener: function ( type, listener ) {
  3913. if ( this._listeners === undefined ) return;
  3914. var listeners = this._listeners;
  3915. var listenerArray = listeners[ type ];
  3916. if ( listenerArray !== undefined ) {
  3917. var index = listenerArray.indexOf( listener );
  3918. if ( index !== - 1 ) {
  3919. listenerArray.splice( index, 1 );
  3920. }
  3921. }
  3922. },
  3923. dispatchEvent: function ( event ) {
  3924. if ( this._listeners === undefined ) return;
  3925. var listeners = this._listeners;
  3926. var listenerArray = listeners[ event.type ];
  3927. if ( listenerArray !== undefined ) {
  3928. event.target = this;
  3929. var array = listenerArray.slice( 0 );
  3930. for ( var i = 0, l = array.length; i < l; i ++ ) {
  3931. array[ i ].call( this, event );
  3932. }
  3933. }
  3934. }
  3935. } );
  3936. var REVISION = '99dev';
  3937. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  3938. var CullFaceNone = 0;
  3939. var CullFaceBack = 1;
  3940. var CullFaceFront = 2;
  3941. var CullFaceFrontBack = 3;
  3942. var FrontFaceDirectionCW = 0;
  3943. var FrontFaceDirectionCCW = 1;
  3944. var BasicShadowMap = 0;
  3945. var PCFShadowMap = 1;
  3946. var PCFSoftShadowMap = 2;
  3947. var FrontSide = 0;
  3948. var BackSide = 1;
  3949. var DoubleSide = 2;
  3950. var FlatShading = 1;
  3951. var SmoothShading = 2;
  3952. var NoColors = 0;
  3953. var FaceColors = 1;
  3954. var VertexColors = 2;
  3955. var NoBlending = 0;
  3956. var NormalBlending = 1;
  3957. var AdditiveBlending = 2;
  3958. var SubtractiveBlending = 3;
  3959. var MultiplyBlending = 4;
  3960. var CustomBlending = 5;
  3961. var AddEquation = 100;
  3962. var SubtractEquation = 101;
  3963. var ReverseSubtractEquation = 102;
  3964. var MinEquation = 103;
  3965. var MaxEquation = 104;
  3966. var ZeroFactor = 200;
  3967. var OneFactor = 201;
  3968. var SrcColorFactor = 202;
  3969. var OneMinusSrcColorFactor = 203;
  3970. var SrcAlphaFactor = 204;
  3971. var OneMinusSrcAlphaFactor = 205;
  3972. var DstAlphaFactor = 206;
  3973. var OneMinusDstAlphaFactor = 207;
  3974. var DstColorFactor = 208;
  3975. var OneMinusDstColorFactor = 209;
  3976. var SrcAlphaSaturateFactor = 210;
  3977. var NeverDepth = 0;
  3978. var AlwaysDepth = 1;
  3979. var LessDepth = 2;
  3980. var LessEqualDepth = 3;
  3981. var EqualDepth = 4;
  3982. var GreaterEqualDepth = 5;
  3983. var GreaterDepth = 6;
  3984. var NotEqualDepth = 7;
  3985. var MultiplyOperation = 0;
  3986. var MixOperation = 1;
  3987. var AddOperation = 2;
  3988. var NoToneMapping = 0;
  3989. var LinearToneMapping = 1;
  3990. var ReinhardToneMapping = 2;
  3991. var Uncharted2ToneMapping = 3;
  3992. var CineonToneMapping = 4;
  3993. var UVMapping = 300;
  3994. var CubeReflectionMapping = 301;
  3995. var CubeRefractionMapping = 302;
  3996. var EquirectangularReflectionMapping = 303;
  3997. var EquirectangularRefractionMapping = 304;
  3998. var SphericalReflectionMapping = 305;
  3999. var CubeUVReflectionMapping = 306;
  4000. var CubeUVRefractionMapping = 307;
  4001. var RepeatWrapping = 1000;
  4002. var ClampToEdgeWrapping = 1001;
  4003. var MirroredRepeatWrapping = 1002;
  4004. var NearestFilter = 1003;
  4005. var NearestMipMapNearestFilter = 1004;
  4006. var NearestMipMapLinearFilter = 1005;
  4007. var LinearFilter = 1006;
  4008. var LinearMipMapNearestFilter = 1007;
  4009. var LinearMipMapLinearFilter = 1008;
  4010. var UnsignedByteType = 1009;
  4011. var ByteType = 1010;
  4012. var ShortType = 1011;
  4013. var UnsignedShortType = 1012;
  4014. var IntType = 1013;
  4015. var UnsignedIntType = 1014;
  4016. var FloatType = 1015;
  4017. var HalfFloatType = 1016;
  4018. var UnsignedShort4444Type = 1017;
  4019. var UnsignedShort5551Type = 1018;
  4020. var UnsignedShort565Type = 1019;
  4021. var UnsignedInt248Type = 1020;
  4022. var AlphaFormat = 1021;
  4023. var RGBFormat = 1022;
  4024. var RGBAFormat = 1023;
  4025. var LuminanceFormat = 1024;
  4026. var LuminanceAlphaFormat = 1025;
  4027. var RGBEFormat = RGBAFormat;
  4028. var DepthFormat = 1026;
  4029. var DepthStencilFormat = 1027;
  4030. var RedFormat = 1028;
  4031. var RGB_S3TC_DXT1_Format = 33776;
  4032. var RGBA_S3TC_DXT1_Format = 33777;
  4033. var RGBA_S3TC_DXT3_Format = 33778;
  4034. var RGBA_S3TC_DXT5_Format = 33779;
  4035. var RGB_PVRTC_4BPPV1_Format = 35840;
  4036. var RGB_PVRTC_2BPPV1_Format = 35841;
  4037. var RGBA_PVRTC_4BPPV1_Format = 35842;
  4038. var RGBA_PVRTC_2BPPV1_Format = 35843;
  4039. var RGB_ETC1_Format = 36196;
  4040. var RGBA_ASTC_4x4_Format = 37808;
  4041. var RGBA_ASTC_5x4_Format = 37809;
  4042. var RGBA_ASTC_5x5_Format = 37810;
  4043. var RGBA_ASTC_6x5_Format = 37811;
  4044. var RGBA_ASTC_6x6_Format = 37812;
  4045. var RGBA_ASTC_8x5_Format = 37813;
  4046. var RGBA_ASTC_8x6_Format = 37814;
  4047. var RGBA_ASTC_8x8_Format = 37815;
  4048. var RGBA_ASTC_10x5_Format = 37816;
  4049. var RGBA_ASTC_10x6_Format = 37817;
  4050. var RGBA_ASTC_10x8_Format = 37818;
  4051. var RGBA_ASTC_10x10_Format = 37819;
  4052. var RGBA_ASTC_12x10_Format = 37820;
  4053. var RGBA_ASTC_12x12_Format = 37821;
  4054. var LoopOnce = 2200;
  4055. var LoopRepeat = 2201;
  4056. var LoopPingPong = 2202;
  4057. var InterpolateDiscrete = 2300;
  4058. var InterpolateLinear = 2301;
  4059. var InterpolateSmooth = 2302;
  4060. var ZeroCurvatureEnding = 2400;
  4061. var ZeroSlopeEnding = 2401;
  4062. var WrapAroundEnding = 2402;
  4063. var TrianglesDrawMode = 0;
  4064. var TriangleStripDrawMode = 1;
  4065. var TriangleFanDrawMode = 2;
  4066. var LinearEncoding = 3000;
  4067. var sRGBEncoding = 3001;
  4068. var GammaEncoding = 3007;
  4069. var RGBEEncoding = 3002;
  4070. var LogLuvEncoding = 3003;
  4071. var RGBM7Encoding = 3004;
  4072. var RGBM16Encoding = 3005;
  4073. var RGBDEncoding = 3006;
  4074. var BasicDepthPacking = 3200;
  4075. var RGBADepthPacking = 3201;
  4076. var TangentSpaceNormalMap = 0;
  4077. var ObjectSpaceNormalMap = 1;
  4078. /**
  4079. * @author alteredq / http://alteredqualia.com/
  4080. * @author mrdoob / http://mrdoob.com/
  4081. */
  4082. var _Math = {
  4083. DEG2RAD: Math.PI / 180,
  4084. RAD2DEG: 180 / Math.PI,
  4085. generateUUID: ( function () {
  4086. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  4087. var lut = [];
  4088. for ( var i = 0; i < 256; i ++ ) {
  4089. lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
  4090. }
  4091. return function generateUUID() {
  4092. var d0 = Math.random() * 0xffffffff | 0;
  4093. var d1 = Math.random() * 0xffffffff | 0;
  4094. var d2 = Math.random() * 0xffffffff | 0;
  4095. var d3 = Math.random() * 0xffffffff | 0;
  4096. var uuid = lut[ d0 & 0xff ] + lut[ d0 >> 8 & 0xff ] + lut[ d0 >> 16 & 0xff ] + lut[ d0 >> 24 & 0xff ] + '-' +
  4097. lut[ d1 & 0xff ] + lut[ d1 >> 8 & 0xff ] + '-' + lut[ d1 >> 16 & 0x0f | 0x40 ] + lut[ d1 >> 24 & 0xff ] + '-' +
  4098. lut[ d2 & 0x3f | 0x80 ] + lut[ d2 >> 8 & 0xff ] + '-' + lut[ d2 >> 16 & 0xff ] + lut[ d2 >> 24 & 0xff ] +
  4099. lut[ d3 & 0xff ] + lut[ d3 >> 8 & 0xff ] + lut[ d3 >> 16 & 0xff ] + lut[ d3 >> 24 & 0xff ];
  4100. // .toUpperCase() here flattens concatenated strings to save heap memory space.
  4101. return uuid.toUpperCase();
  4102. };
  4103. } )(),
  4104. clamp: function ( value, min, max ) {
  4105. return Math.max( min, Math.min( max, value ) );
  4106. },
  4107. // compute euclidian modulo of m % n
  4108. // https://en.wikipedia.org/wiki/Modulo_operation
  4109. euclideanModulo: function ( n, m ) {
  4110. return ( ( n % m ) + m ) % m;
  4111. },
  4112. // Linear mapping from range <a1, a2> to range <b1, b2>
  4113. mapLinear: function ( x, a1, a2, b1, b2 ) {
  4114. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  4115. },
  4116. // https://en.wikipedia.org/wiki/Linear_interpolation
  4117. lerp: function ( x, y, t ) {
  4118. return ( 1 - t ) * x + t * y;
  4119. },
  4120. // http://en.wikipedia.org/wiki/Smoothstep
  4121. smoothstep: function ( x, min, max ) {
  4122. if ( x <= min ) return 0;
  4123. if ( x >= max ) return 1;
  4124. x = ( x - min ) / ( max - min );
  4125. return x * x * ( 3 - 2 * x );
  4126. },
  4127. smootherstep: function ( x, min, max ) {
  4128. if ( x <= min ) return 0;
  4129. if ( x >= max ) return 1;
  4130. x = ( x - min ) / ( max - min );
  4131. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  4132. },
  4133. // Random integer from <low, high> interval
  4134. randInt: function ( low, high ) {
  4135. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  4136. },
  4137. // Random float from <low, high> interval
  4138. randFloat: function ( low, high ) {
  4139. return low + Math.random() * ( high - low );
  4140. },
  4141. // Random float from <-range/2, range/2> interval
  4142. randFloatSpread: function ( range ) {
  4143. return range * ( 0.5 - Math.random() );
  4144. },
  4145. degToRad: function ( degrees ) {
  4146. return degrees * _Math.DEG2RAD;
  4147. },
  4148. radToDeg: function ( radians ) {
  4149. return radians * _Math.RAD2DEG;
  4150. },
  4151. isPowerOfTwo: function ( value ) {
  4152. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  4153. },
  4154. ceilPowerOfTwo: function ( value ) {
  4155. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  4156. },
  4157. floorPowerOfTwo: function ( value ) {
  4158. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  4159. }
  4160. };
  4161. /**
  4162. * @author mrdoob / http://mrdoob.com/
  4163. * @author philogb / http://blog.thejit.org/
  4164. * @author egraether / http://egraether.com/
  4165. * @author zz85 / http://www.lab4games.net/zz85/blog
  4166. */
  4167. function Vector2( x, y ) {
  4168. this.x = x || 0;
  4169. this.y = y || 0;
  4170. }
  4171. Object.defineProperties( Vector2.prototype, {
  4172. "width": {
  4173. get: function () {
  4174. return this.x;
  4175. },
  4176. set: function ( value ) {
  4177. this.x = value;
  4178. }
  4179. },
  4180. "height": {
  4181. get: function () {
  4182. return this.y;
  4183. },
  4184. set: function ( value ) {
  4185. this.y = value;
  4186. }
  4187. }
  4188. } );
  4189. Object.assign( Vector2.prototype, {
  4190. isVector2: true,
  4191. set: function ( x, y ) {
  4192. this.x = x;
  4193. this.y = y;
  4194. return this;
  4195. },
  4196. setScalar: function ( scalar ) {
  4197. this.x = scalar;
  4198. this.y = scalar;
  4199. return this;
  4200. },
  4201. setX: function ( x ) {
  4202. this.x = x;
  4203. return this;
  4204. },
  4205. setY: function ( y ) {
  4206. this.y = y;
  4207. return this;
  4208. },
  4209. setComponent: function ( index, value ) {
  4210. switch ( index ) {
  4211. case 0: this.x = value; break;
  4212. case 1: this.y = value; break;
  4213. default: throw new Error( 'index is out of range: ' + index );
  4214. }
  4215. return this;
  4216. },
  4217. getComponent: function ( index ) {
  4218. switch ( index ) {
  4219. case 0: return this.x;
  4220. case 1: return this.y;
  4221. default: throw new Error( 'index is out of range: ' + index );
  4222. }
  4223. },
  4224. clone: function () {
  4225. return new this.constructor( this.x, this.y );
  4226. },
  4227. copy: function ( v ) {
  4228. this.x = v.x;
  4229. this.y = v.y;
  4230. return this;
  4231. },
  4232. add: function ( v, w ) {
  4233. if ( w !== undefined ) {
  4234. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  4235. return this.addVectors( v, w );
  4236. }
  4237. this.x += v.x;
  4238. this.y += v.y;
  4239. return this;
  4240. },
  4241. addScalar: function ( s ) {
  4242. this.x += s;
  4243. this.y += s;
  4244. return this;
  4245. },
  4246. addVectors: function ( a, b ) {
  4247. this.x = a.x + b.x;
  4248. this.y = a.y + b.y;
  4249. return this;
  4250. },
  4251. addScaledVector: function ( v, s ) {
  4252. this.x += v.x * s;
  4253. this.y += v.y * s;
  4254. return this;
  4255. },
  4256. sub: function ( v, w ) {
  4257. if ( w !== undefined ) {
  4258. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  4259. return this.subVectors( v, w );
  4260. }
  4261. this.x -= v.x;
  4262. this.y -= v.y;
  4263. return this;
  4264. },
  4265. subScalar: function ( s ) {
  4266. this.x -= s;
  4267. this.y -= s;
  4268. return this;
  4269. },
  4270. subVectors: function ( a, b ) {
  4271. this.x = a.x - b.x;
  4272. this.y = a.y - b.y;
  4273. return this;
  4274. },
  4275. multiply: function ( v ) {
  4276. this.x *= v.x;
  4277. this.y *= v.y;
  4278. return this;
  4279. },
  4280. multiplyScalar: function ( scalar ) {
  4281. this.x *= scalar;
  4282. this.y *= scalar;
  4283. return this;
  4284. },
  4285. divide: function ( v ) {
  4286. this.x /= v.x;
  4287. this.y /= v.y;
  4288. return this;
  4289. },
  4290. divideScalar: function ( scalar ) {
  4291. return this.multiplyScalar( 1 / scalar );
  4292. },
  4293. applyMatrix3: function ( m ) {
  4294. var x = this.x, y = this.y;
  4295. var e = m.elements;
  4296. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  4297. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  4298. return this;
  4299. },
  4300. min: function ( v ) {
  4301. this.x = Math.min( this.x, v.x );
  4302. this.y = Math.min( this.y, v.y );
  4303. return this;
  4304. },
  4305. max: function ( v ) {
  4306. this.x = Math.max( this.x, v.x );
  4307. this.y = Math.max( this.y, v.y );
  4308. return this;
  4309. },
  4310. clamp: function ( min, max ) {
  4311. // assumes min < max, componentwise
  4312. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  4313. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  4314. return this;
  4315. },
  4316. clampScalar: function () {
  4317. var min = new Vector2();
  4318. var max = new Vector2();
  4319. return function clampScalar( minVal, maxVal ) {
  4320. min.set( minVal, minVal );
  4321. max.set( maxVal, maxVal );
  4322. return this.clamp( min, max );
  4323. };
  4324. }(),
  4325. clampLength: function ( min, max ) {
  4326. var length = this.length();
  4327. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  4328. },
  4329. floor: function () {
  4330. this.x = Math.floor( this.x );
  4331. this.y = Math.floor( this.y );
  4332. return this;
  4333. },
  4334. ceil: function () {
  4335. this.x = Math.ceil( this.x );
  4336. this.y = Math.ceil( this.y );
  4337. return this;
  4338. },
  4339. round: function () {
  4340. this.x = Math.round( this.x );
  4341. this.y = Math.round( this.y );
  4342. return this;
  4343. },
  4344. roundToZero: function () {
  4345. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  4346. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  4347. return this;
  4348. },
  4349. negate: function () {
  4350. this.x = - this.x;
  4351. this.y = - this.y;
  4352. return this;
  4353. },
  4354. dot: function ( v ) {
  4355. return this.x * v.x + this.y * v.y;
  4356. },
  4357. cross: function ( v ) {
  4358. return this.x * v.y - this.y * v.x;
  4359. },
  4360. lengthSq: function () {
  4361. return this.x * this.x + this.y * this.y;
  4362. },
  4363. length: function () {
  4364. return Math.sqrt( this.x * this.x + this.y * this.y );
  4365. },
  4366. manhattanLength: function () {
  4367. return Math.abs( this.x ) + Math.abs( this.y );
  4368. },
  4369. normalize: function () {
  4370. return this.divideScalar( this.length() || 1 );
  4371. },
  4372. angle: function () {
  4373. // computes the angle in radians with respect to the positive x-axis
  4374. var angle = Math.atan2( this.y, this.x );
  4375. if ( angle < 0 ) angle += 2 * Math.PI;
  4376. return angle;
  4377. },
  4378. distanceTo: function ( v ) {
  4379. return Math.sqrt( this.distanceToSquared( v ) );
  4380. },
  4381. distanceToSquared: function ( v ) {
  4382. var dx = this.x - v.x, dy = this.y - v.y;
  4383. return dx * dx + dy * dy;
  4384. },
  4385. manhattanDistanceTo: function ( v ) {
  4386. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  4387. },
  4388. setLength: function ( length ) {
  4389. return this.normalize().multiplyScalar( length );
  4390. },
  4391. lerp: function ( v, alpha ) {
  4392. this.x += ( v.x - this.x ) * alpha;
  4393. this.y += ( v.y - this.y ) * alpha;
  4394. return this;
  4395. },
  4396. lerpVectors: function ( v1, v2, alpha ) {
  4397. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  4398. },
  4399. equals: function ( v ) {
  4400. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  4401. },
  4402. fromArray: function ( array, offset ) {
  4403. if ( offset === undefined ) offset = 0;
  4404. this.x = array[ offset ];
  4405. this.y = array[ offset + 1 ];
  4406. return this;
  4407. },
  4408. toArray: function ( array, offset ) {
  4409. if ( array === undefined ) array = [];
  4410. if ( offset === undefined ) offset = 0;
  4411. array[ offset ] = this.x;
  4412. array[ offset + 1 ] = this.y;
  4413. return array;
  4414. },
  4415. fromBufferAttribute: function ( attribute, index, offset ) {
  4416. if ( offset !== undefined ) {
  4417. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  4418. }
  4419. this.x = attribute.getX( index );
  4420. this.y = attribute.getY( index );
  4421. return this;
  4422. },
  4423. rotateAround: function ( center, angle ) {
  4424. var c = Math.cos( angle ), s = Math.sin( angle );
  4425. var x = this.x - center.x;
  4426. var y = this.y - center.y;
  4427. this.x = x * c - y * s + center.x;
  4428. this.y = x * s + y * c + center.y;
  4429. return this;
  4430. }
  4431. } );
  4432. /**
  4433. * @author mrdoob / http://mrdoob.com/
  4434. * @author supereggbert / http://www.paulbrunt.co.uk/
  4435. * @author philogb / http://blog.thejit.org/
  4436. * @author jordi_ros / http://plattsoft.com
  4437. * @author D1plo1d / http://github.com/D1plo1d
  4438. * @author alteredq / http://alteredqualia.com/
  4439. * @author mikael emtinger / http://gomo.se/
  4440. * @author timknip / http://www.floorplanner.com/
  4441. * @author bhouston / http://clara.io
  4442. * @author WestLangley / http://github.com/WestLangley
  4443. */
  4444. function Matrix4() {
  4445. this.elements = [
  4446. 1, 0, 0, 0,
  4447. 0, 1, 0, 0,
  4448. 0, 0, 1, 0,
  4449. 0, 0, 0, 1
  4450. ];
  4451. if ( arguments.length > 0 ) {
  4452. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  4453. }
  4454. }
  4455. Object.assign( Matrix4.prototype, {
  4456. isMatrix4: true,
  4457. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  4458. var te = this.elements;
  4459. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  4460. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  4461. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  4462. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  4463. return this;
  4464. },
  4465. identity: function () {
  4466. this.set(
  4467. 1, 0, 0, 0,
  4468. 0, 1, 0, 0,
  4469. 0, 0, 1, 0,
  4470. 0, 0, 0, 1
  4471. );
  4472. return this;
  4473. },
  4474. clone: function () {
  4475. return new Matrix4().fromArray( this.elements );
  4476. },
  4477. copy: function ( m ) {
  4478. var te = this.elements;
  4479. var me = m.elements;
  4480. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  4481. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  4482. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  4483. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  4484. return this;
  4485. },
  4486. copyPosition: function ( m ) {
  4487. var te = this.elements, me = m.elements;
  4488. te[ 12 ] = me[ 12 ];
  4489. te[ 13 ] = me[ 13 ];
  4490. te[ 14 ] = me[ 14 ];
  4491. return this;
  4492. },
  4493. extractBasis: function ( xAxis, yAxis, zAxis ) {
  4494. xAxis.setFromMatrixColumn( this, 0 );
  4495. yAxis.setFromMatrixColumn( this, 1 );
  4496. zAxis.setFromMatrixColumn( this, 2 );
  4497. return this;
  4498. },
  4499. makeBasis: function ( xAxis, yAxis, zAxis ) {
  4500. this.set(
  4501. xAxis.x, yAxis.x, zAxis.x, 0,
  4502. xAxis.y, yAxis.y, zAxis.y, 0,
  4503. xAxis.z, yAxis.z, zAxis.z, 0,
  4504. 0, 0, 0, 1
  4505. );
  4506. return this;
  4507. },
  4508. extractRotation: function () {
  4509. var v1 = new Vector3();
  4510. return function extractRotation( m ) {
  4511. // this method does not support reflection matrices
  4512. var te = this.elements;
  4513. var me = m.elements;
  4514. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  4515. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  4516. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  4517. te[ 0 ] = me[ 0 ] * scaleX;
  4518. te[ 1 ] = me[ 1 ] * scaleX;
  4519. te[ 2 ] = me[ 2 ] * scaleX;
  4520. te[ 3 ] = 0;
  4521. te[ 4 ] = me[ 4 ] * scaleY;
  4522. te[ 5 ] = me[ 5 ] * scaleY;
  4523. te[ 6 ] = me[ 6 ] * scaleY;
  4524. te[ 7 ] = 0;
  4525. te[ 8 ] = me[ 8 ] * scaleZ;
  4526. te[ 9 ] = me[ 9 ] * scaleZ;
  4527. te[ 10 ] = me[ 10 ] * scaleZ;
  4528. te[ 11 ] = 0;
  4529. te[ 12 ] = 0;
  4530. te[ 13 ] = 0;
  4531. te[ 14 ] = 0;
  4532. te[ 15 ] = 1;
  4533. return this;
  4534. };
  4535. }(),
  4536. makeRotationFromEuler: function ( euler ) {
  4537. if ( ! ( euler && euler.isEuler ) ) {
  4538. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  4539. }
  4540. var te = this.elements;
  4541. var x = euler.x, y = euler.y, z = euler.z;
  4542. var a = Math.cos( x ), b = Math.sin( x );
  4543. var c = Math.cos( y ), d = Math.sin( y );
  4544. var e = Math.cos( z ), f = Math.sin( z );
  4545. if ( euler.order === 'XYZ' ) {
  4546. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  4547. te[ 0 ] = c * e;
  4548. te[ 4 ] = - c * f;
  4549. te[ 8 ] = d;
  4550. te[ 1 ] = af + be * d;
  4551. te[ 5 ] = ae - bf * d;
  4552. te[ 9 ] = - b * c;
  4553. te[ 2 ] = bf - ae * d;
  4554. te[ 6 ] = be + af * d;
  4555. te[ 10 ] = a * c;
  4556. } else if ( euler.order === 'YXZ' ) {
  4557. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  4558. te[ 0 ] = ce + df * b;
  4559. te[ 4 ] = de * b - cf;
  4560. te[ 8 ] = a * d;
  4561. te[ 1 ] = a * f;
  4562. te[ 5 ] = a * e;
  4563. te[ 9 ] = - b;
  4564. te[ 2 ] = cf * b - de;
  4565. te[ 6 ] = df + ce * b;
  4566. te[ 10 ] = a * c;
  4567. } else if ( euler.order === 'ZXY' ) {
  4568. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  4569. te[ 0 ] = ce - df * b;
  4570. te[ 4 ] = - a * f;
  4571. te[ 8 ] = de + cf * b;
  4572. te[ 1 ] = cf + de * b;
  4573. te[ 5 ] = a * e;
  4574. te[ 9 ] = df - ce * b;
  4575. te[ 2 ] = - a * d;
  4576. te[ 6 ] = b;
  4577. te[ 10 ] = a * c;
  4578. } else if ( euler.order === 'ZYX' ) {
  4579. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  4580. te[ 0 ] = c * e;
  4581. te[ 4 ] = be * d - af;
  4582. te[ 8 ] = ae * d + bf;
  4583. te[ 1 ] = c * f;
  4584. te[ 5 ] = bf * d + ae;
  4585. te[ 9 ] = af * d - be;
  4586. te[ 2 ] = - d;
  4587. te[ 6 ] = b * c;
  4588. te[ 10 ] = a * c;
  4589. } else if ( euler.order === 'YZX' ) {
  4590. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  4591. te[ 0 ] = c * e;
  4592. te[ 4 ] = bd - ac * f;
  4593. te[ 8 ] = bc * f + ad;
  4594. te[ 1 ] = f;
  4595. te[ 5 ] = a * e;
  4596. te[ 9 ] = - b * e;
  4597. te[ 2 ] = - d * e;
  4598. te[ 6 ] = ad * f + bc;
  4599. te[ 10 ] = ac - bd * f;
  4600. } else if ( euler.order === 'XZY' ) {
  4601. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  4602. te[ 0 ] = c * e;
  4603. te[ 4 ] = - f;
  4604. te[ 8 ] = d * e;
  4605. te[ 1 ] = ac * f + bd;
  4606. te[ 5 ] = a * e;
  4607. te[ 9 ] = ad * f - bc;
  4608. te[ 2 ] = bc * f - ad;
  4609. te[ 6 ] = b * e;
  4610. te[ 10 ] = bd * f + ac;
  4611. }
  4612. // bottom row
  4613. te[ 3 ] = 0;
  4614. te[ 7 ] = 0;
  4615. te[ 11 ] = 0;
  4616. // last column
  4617. te[ 12 ] = 0;
  4618. te[ 13 ] = 0;
  4619. te[ 14 ] = 0;
  4620. te[ 15 ] = 1;
  4621. return this;
  4622. },
  4623. makeRotationFromQuaternion: function () {
  4624. var zero = new Vector3( 0, 0, 0 );
  4625. var one = new Vector3( 1, 1, 1 );
  4626. return function makeRotationFromQuaternion( q ) {
  4627. return this.compose( zero, q, one );
  4628. };
  4629. }(),
  4630. lookAt: function () {
  4631. var x = new Vector3();
  4632. var y = new Vector3();
  4633. var z = new Vector3();
  4634. return function lookAt( eye, target, up ) {
  4635. var te = this.elements;
  4636. z.subVectors( eye, target );
  4637. if ( z.lengthSq() === 0 ) {
  4638. // eye and target are in the same position
  4639. z.z = 1;
  4640. }
  4641. z.normalize();
  4642. x.crossVectors( up, z );
  4643. if ( x.lengthSq() === 0 ) {
  4644. // up and z are parallel
  4645. if ( Math.abs( up.z ) === 1 ) {
  4646. z.x += 0.0001;
  4647. } else {
  4648. z.z += 0.0001;
  4649. }
  4650. z.normalize();
  4651. x.crossVectors( up, z );
  4652. }
  4653. x.normalize();
  4654. y.crossVectors( z, x );
  4655. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  4656. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  4657. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  4658. return this;
  4659. };
  4660. }(),
  4661. multiply: function ( m, n ) {
  4662. if ( n !== undefined ) {
  4663. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  4664. return this.multiplyMatrices( m, n );
  4665. }
  4666. return this.multiplyMatrices( this, m );
  4667. },
  4668. premultiply: function ( m ) {
  4669. return this.multiplyMatrices( m, this );
  4670. },
  4671. multiplyMatrices: function ( a, b ) {
  4672. var ae = a.elements;
  4673. var be = b.elements;
  4674. var te = this.elements;
  4675. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  4676. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  4677. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  4678. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  4679. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  4680. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  4681. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  4682. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  4683. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  4684. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  4685. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  4686. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  4687. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  4688. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  4689. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  4690. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  4691. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  4692. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  4693. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  4694. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  4695. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  4696. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  4697. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  4698. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  4699. return this;
  4700. },
  4701. multiplyScalar: function ( s ) {
  4702. var te = this.elements;
  4703. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  4704. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  4705. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  4706. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  4707. return this;
  4708. },
  4709. applyToBufferAttribute: function () {
  4710. var v1 = new Vector3();
  4711. return function applyToBufferAttribute( attribute ) {
  4712. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  4713. v1.x = attribute.getX( i );
  4714. v1.y = attribute.getY( i );
  4715. v1.z = attribute.getZ( i );
  4716. v1.applyMatrix4( this );
  4717. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  4718. }
  4719. return attribute;
  4720. };
  4721. }(),
  4722. determinant: function () {
  4723. var te = this.elements;
  4724. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  4725. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  4726. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  4727. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  4728. //TODO: make this more efficient
  4729. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4730. return (
  4731. n41 * (
  4732. + n14 * n23 * n32
  4733. - n13 * n24 * n32
  4734. - n14 * n22 * n33
  4735. + n12 * n24 * n33
  4736. + n13 * n22 * n34
  4737. - n12 * n23 * n34
  4738. ) +
  4739. n42 * (
  4740. + n11 * n23 * n34
  4741. - n11 * n24 * n33
  4742. + n14 * n21 * n33
  4743. - n13 * n21 * n34
  4744. + n13 * n24 * n31
  4745. - n14 * n23 * n31
  4746. ) +
  4747. n43 * (
  4748. + n11 * n24 * n32
  4749. - n11 * n22 * n34
  4750. - n14 * n21 * n32
  4751. + n12 * n21 * n34
  4752. + n14 * n22 * n31
  4753. - n12 * n24 * n31
  4754. ) +
  4755. n44 * (
  4756. - n13 * n22 * n31
  4757. - n11 * n23 * n32
  4758. + n11 * n22 * n33
  4759. + n13 * n21 * n32
  4760. - n12 * n21 * n33
  4761. + n12 * n23 * n31
  4762. )
  4763. );
  4764. },
  4765. transpose: function () {
  4766. var te = this.elements;
  4767. var tmp;
  4768. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  4769. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  4770. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  4771. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  4772. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  4773. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  4774. return this;
  4775. },
  4776. setPosition: function ( v ) {
  4777. var te = this.elements;
  4778. te[ 12 ] = v.x;
  4779. te[ 13 ] = v.y;
  4780. te[ 14 ] = v.z;
  4781. return this;
  4782. },
  4783. getInverse: function ( m, throwOnDegenerate ) {
  4784. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4785. var te = this.elements,
  4786. me = m.elements,
  4787. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  4788. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  4789. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  4790. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  4791. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4792. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4793. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4794. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4795. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4796. if ( det === 0 ) {
  4797. var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0";
  4798. if ( throwOnDegenerate === true ) {
  4799. throw new Error( msg );
  4800. } else {
  4801. console.warn( msg );
  4802. }
  4803. return this.identity();
  4804. }
  4805. var detInv = 1 / det;
  4806. te[ 0 ] = t11 * detInv;
  4807. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  4808. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  4809. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  4810. te[ 4 ] = t12 * detInv;
  4811. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  4812. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  4813. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  4814. te[ 8 ] = t13 * detInv;
  4815. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  4816. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  4817. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  4818. te[ 12 ] = t14 * detInv;
  4819. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  4820. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  4821. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  4822. return this;
  4823. },
  4824. scale: function ( v ) {
  4825. var te = this.elements;
  4826. var x = v.x, y = v.y, z = v.z;
  4827. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  4828. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  4829. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  4830. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  4831. return this;
  4832. },
  4833. getMaxScaleOnAxis: function () {
  4834. var te = this.elements;
  4835. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  4836. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  4837. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  4838. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  4839. },
  4840. makeTranslation: function ( x, y, z ) {
  4841. this.set(
  4842. 1, 0, 0, x,
  4843. 0, 1, 0, y,
  4844. 0, 0, 1, z,
  4845. 0, 0, 0, 1
  4846. );
  4847. return this;
  4848. },
  4849. makeRotationX: function ( theta ) {
  4850. var c = Math.cos( theta ), s = Math.sin( theta );
  4851. this.set(
  4852. 1, 0, 0, 0,
  4853. 0, c, - s, 0,
  4854. 0, s, c, 0,
  4855. 0, 0, 0, 1
  4856. );
  4857. return this;
  4858. },
  4859. makeRotationY: function ( theta ) {
  4860. var c = Math.cos( theta ), s = Math.sin( theta );
  4861. this.set(
  4862. c, 0, s, 0,
  4863. 0, 1, 0, 0,
  4864. - s, 0, c, 0,
  4865. 0, 0, 0, 1
  4866. );
  4867. return this;
  4868. },
  4869. makeRotationZ: function ( theta ) {
  4870. var c = Math.cos( theta ), s = Math.sin( theta );
  4871. this.set(
  4872. c, - s, 0, 0,
  4873. s, c, 0, 0,
  4874. 0, 0, 1, 0,
  4875. 0, 0, 0, 1
  4876. );
  4877. return this;
  4878. },
  4879. makeRotationAxis: function ( axis, angle ) {
  4880. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4881. var c = Math.cos( angle );
  4882. var s = Math.sin( angle );
  4883. var t = 1 - c;
  4884. var x = axis.x, y = axis.y, z = axis.z;
  4885. var tx = t * x, ty = t * y;
  4886. this.set(
  4887. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  4888. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  4889. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  4890. 0, 0, 0, 1
  4891. );
  4892. return this;
  4893. },
  4894. makeScale: function ( x, y, z ) {
  4895. this.set(
  4896. x, 0, 0, 0,
  4897. 0, y, 0, 0,
  4898. 0, 0, z, 0,
  4899. 0, 0, 0, 1
  4900. );
  4901. return this;
  4902. },
  4903. makeShear: function ( x, y, z ) {
  4904. this.set(
  4905. 1, y, z, 0,
  4906. x, 1, z, 0,
  4907. x, y, 1, 0,
  4908. 0, 0, 0, 1
  4909. );
  4910. return this;
  4911. },
  4912. compose: function ( position, quaternion, scale ) {
  4913. var te = this.elements;
  4914. var x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  4915. var x2 = x + x, y2 = y + y, z2 = z + z;
  4916. var xx = x * x2, xy = x * y2, xz = x * z2;
  4917. var yy = y * y2, yz = y * z2, zz = z * z2;
  4918. var wx = w * x2, wy = w * y2, wz = w * z2;
  4919. var sx = scale.x, sy = scale.y, sz = scale.z;
  4920. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  4921. te[ 1 ] = ( xy + wz ) * sx;
  4922. te[ 2 ] = ( xz - wy ) * sx;
  4923. te[ 3 ] = 0;
  4924. te[ 4 ] = ( xy - wz ) * sy;
  4925. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  4926. te[ 6 ] = ( yz + wx ) * sy;
  4927. te[ 7 ] = 0;
  4928. te[ 8 ] = ( xz + wy ) * sz;
  4929. te[ 9 ] = ( yz - wx ) * sz;
  4930. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  4931. te[ 11 ] = 0;
  4932. te[ 12 ] = position.x;
  4933. te[ 13 ] = position.y;
  4934. te[ 14 ] = position.z;
  4935. te[ 15 ] = 1;
  4936. return this;
  4937. },
  4938. decompose: function () {
  4939. var vector = new Vector3();
  4940. var matrix = new Matrix4();
  4941. return function decompose( position, quaternion, scale ) {
  4942. var te = this.elements;
  4943. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4944. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4945. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4946. // if determine is negative, we need to invert one scale
  4947. var det = this.determinant();
  4948. if ( det < 0 ) sx = - sx;
  4949. position.x = te[ 12 ];
  4950. position.y = te[ 13 ];
  4951. position.z = te[ 14 ];
  4952. // scale the rotation part
  4953. matrix.copy( this );
  4954. var invSX = 1 / sx;
  4955. var invSY = 1 / sy;
  4956. var invSZ = 1 / sz;
  4957. matrix.elements[ 0 ] *= invSX;
  4958. matrix.elements[ 1 ] *= invSX;
  4959. matrix.elements[ 2 ] *= invSX;
  4960. matrix.elements[ 4 ] *= invSY;
  4961. matrix.elements[ 5 ] *= invSY;
  4962. matrix.elements[ 6 ] *= invSY;
  4963. matrix.elements[ 8 ] *= invSZ;
  4964. matrix.elements[ 9 ] *= invSZ;
  4965. matrix.elements[ 10 ] *= invSZ;
  4966. quaternion.setFromRotationMatrix( matrix );
  4967. scale.x = sx;
  4968. scale.y = sy;
  4969. scale.z = sz;
  4970. return this;
  4971. };
  4972. }(),
  4973. makePerspective: function ( left, right, top, bottom, near, far ) {
  4974. if ( far === undefined ) {
  4975. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  4976. }
  4977. var te = this.elements;
  4978. var x = 2 * near / ( right - left );
  4979. var y = 2 * near / ( top - bottom );
  4980. var a = ( right + left ) / ( right - left );
  4981. var b = ( top + bottom ) / ( top - bottom );
  4982. var c = - ( far + near ) / ( far - near );
  4983. var d = - 2 * far * near / ( far - near );
  4984. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4985. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4986. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4987. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4988. return this;
  4989. },
  4990. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  4991. var te = this.elements;
  4992. var w = 1.0 / ( right - left );
  4993. var h = 1.0 / ( top - bottom );
  4994. var p = 1.0 / ( far - near );
  4995. var x = ( right + left ) * w;
  4996. var y = ( top + bottom ) * h;
  4997. var z = ( far + near ) * p;
  4998. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4999. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  5000. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  5001. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  5002. return this;
  5003. },
  5004. equals: function ( matrix ) {
  5005. var te = this.elements;
  5006. var me = matrix.elements;
  5007. for ( var i = 0; i < 16; i ++ ) {
  5008. if ( te[ i ] !== me[ i ] ) return false;
  5009. }
  5010. return true;
  5011. },
  5012. fromArray: function ( array, offset ) {
  5013. if ( offset === undefined ) offset = 0;
  5014. for ( var i = 0; i < 16; i ++ ) {
  5015. this.elements[ i ] = array[ i + offset ];
  5016. }
  5017. return this;
  5018. },
  5019. toArray: function ( array, offset ) {
  5020. if ( array === undefined ) array = [];
  5021. if ( offset === undefined ) offset = 0;
  5022. var te = this.elements;
  5023. array[ offset ] = te[ 0 ];
  5024. array[ offset + 1 ] = te[ 1 ];
  5025. array[ offset + 2 ] = te[ 2 ];
  5026. array[ offset + 3 ] = te[ 3 ];
  5027. array[ offset + 4 ] = te[ 4 ];
  5028. array[ offset + 5 ] = te[ 5 ];
  5029. array[ offset + 6 ] = te[ 6 ];
  5030. array[ offset + 7 ] = te[ 7 ];
  5031. array[ offset + 8 ] = te[ 8 ];
  5032. array[ offset + 9 ] = te[ 9 ];
  5033. array[ offset + 10 ] = te[ 10 ];
  5034. array[ offset + 11 ] = te[ 11 ];
  5035. array[ offset + 12 ] = te[ 12 ];
  5036. array[ offset + 13 ] = te[ 13 ];
  5037. array[ offset + 14 ] = te[ 14 ];
  5038. array[ offset + 15 ] = te[ 15 ];
  5039. return array;
  5040. }
  5041. } );
  5042. /**
  5043. * @author mikael emtinger / http://gomo.se/
  5044. * @author alteredq / http://alteredqualia.com/
  5045. * @author WestLangley / http://github.com/WestLangley
  5046. * @author bhouston / http://clara.io
  5047. */
  5048. function Quaternion( x, y, z, w ) {
  5049. this._x = x || 0;
  5050. this._y = y || 0;
  5051. this._z = z || 0;
  5052. this._w = ( w !== undefined ) ? w : 1;
  5053. }
  5054. Object.assign( Quaternion, {
  5055. slerp: function ( qa, qb, qm, t ) {
  5056. return qm.copy( qa ).slerp( qb, t );
  5057. },
  5058. slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  5059. // fuzz-free, array-based Quaternion SLERP operation
  5060. var x0 = src0[ srcOffset0 + 0 ],
  5061. y0 = src0[ srcOffset0 + 1 ],
  5062. z0 = src0[ srcOffset0 + 2 ],
  5063. w0 = src0[ srcOffset0 + 3 ],
  5064. x1 = src1[ srcOffset1 + 0 ],
  5065. y1 = src1[ srcOffset1 + 1 ],
  5066. z1 = src1[ srcOffset1 + 2 ],
  5067. w1 = src1[ srcOffset1 + 3 ];
  5068. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  5069. var s = 1 - t,
  5070. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  5071. dir = ( cos >= 0 ? 1 : - 1 ),
  5072. sqrSin = 1 - cos * cos;
  5073. // Skip the Slerp for tiny steps to avoid numeric problems:
  5074. if ( sqrSin > Number.EPSILON ) {
  5075. var sin = Math.sqrt( sqrSin ),
  5076. len = Math.atan2( sin, cos * dir );
  5077. s = Math.sin( s * len ) / sin;
  5078. t = Math.sin( t * len ) / sin;
  5079. }
  5080. var tDir = t * dir;
  5081. x0 = x0 * s + x1 * tDir;
  5082. y0 = y0 * s + y1 * tDir;
  5083. z0 = z0 * s + z1 * tDir;
  5084. w0 = w0 * s + w1 * tDir;
  5085. // Normalize in case we just did a lerp:
  5086. if ( s === 1 - t ) {
  5087. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  5088. x0 *= f;
  5089. y0 *= f;
  5090. z0 *= f;
  5091. w0 *= f;
  5092. }
  5093. }
  5094. dst[ dstOffset ] = x0;
  5095. dst[ dstOffset + 1 ] = y0;
  5096. dst[ dstOffset + 2 ] = z0;
  5097. dst[ dstOffset + 3 ] = w0;
  5098. }
  5099. } );
  5100. Object.defineProperties( Quaternion.prototype, {
  5101. x: {
  5102. get: function () {
  5103. return this._x;
  5104. },
  5105. set: function ( value ) {
  5106. this._x = value;
  5107. this.onChangeCallback();
  5108. }
  5109. },
  5110. y: {
  5111. get: function () {
  5112. return this._y;
  5113. },
  5114. set: function ( value ) {
  5115. this._y = value;
  5116. this.onChangeCallback();
  5117. }
  5118. },
  5119. z: {
  5120. get: function () {
  5121. return this._z;
  5122. },
  5123. set: function ( value ) {
  5124. this._z = value;
  5125. this.onChangeCallback();
  5126. }
  5127. },
  5128. w: {
  5129. get: function () {
  5130. return this._w;
  5131. },
  5132. set: function ( value ) {
  5133. this._w = value;
  5134. this.onChangeCallback();
  5135. }
  5136. }
  5137. } );
  5138. Object.assign( Quaternion.prototype, {
  5139. isQuaternion: true,
  5140. set: function ( x, y, z, w ) {
  5141. this._x = x;
  5142. this._y = y;
  5143. this._z = z;
  5144. this._w = w;
  5145. this.onChangeCallback();
  5146. return this;
  5147. },
  5148. clone: function () {
  5149. return new this.constructor( this._x, this._y, this._z, this._w );
  5150. },
  5151. copy: function ( quaternion ) {
  5152. this._x = quaternion.x;
  5153. this._y = quaternion.y;
  5154. this._z = quaternion.z;
  5155. this._w = quaternion.w;
  5156. this.onChangeCallback();
  5157. return this;
  5158. },
  5159. setFromEuler: function ( euler, update ) {
  5160. if ( ! ( euler && euler.isEuler ) ) {
  5161. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  5162. }
  5163. var x = euler._x, y = euler._y, z = euler._z, order = euler.order;
  5164. // http://www.mathworks.com/matlabcentral/fileexchange/
  5165. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  5166. // content/SpinCalc.m
  5167. var cos = Math.cos;
  5168. var sin = Math.sin;
  5169. var c1 = cos( x / 2 );
  5170. var c2 = cos( y / 2 );
  5171. var c3 = cos( z / 2 );
  5172. var s1 = sin( x / 2 );
  5173. var s2 = sin( y / 2 );
  5174. var s3 = sin( z / 2 );
  5175. if ( order === 'XYZ' ) {
  5176. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5177. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5178. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5179. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5180. } else if ( order === 'YXZ' ) {
  5181. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5182. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5183. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5184. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5185. } else if ( order === 'ZXY' ) {
  5186. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5187. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5188. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5189. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5190. } else if ( order === 'ZYX' ) {
  5191. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5192. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5193. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5194. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5195. } else if ( order === 'YZX' ) {
  5196. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5197. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5198. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5199. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5200. } else if ( order === 'XZY' ) {
  5201. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5202. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5203. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5204. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5205. }
  5206. if ( update !== false ) this.onChangeCallback();
  5207. return this;
  5208. },
  5209. setFromAxisAngle: function ( axis, angle ) {
  5210. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  5211. // assumes axis is normalized
  5212. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  5213. this._x = axis.x * s;
  5214. this._y = axis.y * s;
  5215. this._z = axis.z * s;
  5216. this._w = Math.cos( halfAngle );
  5217. this.onChangeCallback();
  5218. return this;
  5219. },
  5220. setFromRotationMatrix: function ( m ) {
  5221. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  5222. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5223. var te = m.elements,
  5224. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  5225. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  5226. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  5227. trace = m11 + m22 + m33,
  5228. s;
  5229. if ( trace > 0 ) {
  5230. s = 0.5 / Math.sqrt( trace + 1.0 );
  5231. this._w = 0.25 / s;
  5232. this._x = ( m32 - m23 ) * s;
  5233. this._y = ( m13 - m31 ) * s;
  5234. this._z = ( m21 - m12 ) * s;
  5235. } else if ( m11 > m22 && m11 > m33 ) {
  5236. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  5237. this._w = ( m32 - m23 ) / s;
  5238. this._x = 0.25 * s;
  5239. this._y = ( m12 + m21 ) / s;
  5240. this._z = ( m13 + m31 ) / s;
  5241. } else if ( m22 > m33 ) {
  5242. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  5243. this._w = ( m13 - m31 ) / s;
  5244. this._x = ( m12 + m21 ) / s;
  5245. this._y = 0.25 * s;
  5246. this._z = ( m23 + m32 ) / s;
  5247. } else {
  5248. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  5249. this._w = ( m21 - m12 ) / s;
  5250. this._x = ( m13 + m31 ) / s;
  5251. this._y = ( m23 + m32 ) / s;
  5252. this._z = 0.25 * s;
  5253. }
  5254. this.onChangeCallback();
  5255. return this;
  5256. },
  5257. setFromUnitVectors: function () {
  5258. // assumes direction vectors vFrom and vTo are normalized
  5259. var v1 = new Vector3();
  5260. var r;
  5261. var EPS = 0.000001;
  5262. return function setFromUnitVectors( vFrom, vTo ) {
  5263. if ( v1 === undefined ) v1 = new Vector3();
  5264. r = vFrom.dot( vTo ) + 1;
  5265. if ( r < EPS ) {
  5266. r = 0;
  5267. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  5268. v1.set( - vFrom.y, vFrom.x, 0 );
  5269. } else {
  5270. v1.set( 0, - vFrom.z, vFrom.y );
  5271. }
  5272. } else {
  5273. v1.crossVectors( vFrom, vTo );
  5274. }
  5275. this._x = v1.x;
  5276. this._y = v1.y;
  5277. this._z = v1.z;
  5278. this._w = r;
  5279. return this.normalize();
  5280. };
  5281. }(),
  5282. angleTo: function ( q ) {
  5283. return 2 * Math.acos( Math.abs( _Math.clamp( this.dot( q ), - 1, 1 ) ) );
  5284. },
  5285. rotateTowards: function ( q, step ) {
  5286. var angle = this.angleTo( q );
  5287. if ( angle === 0 ) return this;
  5288. var t = Math.min( 1, step / angle );
  5289. this.slerp( q, t );
  5290. return this;
  5291. },
  5292. inverse: function () {
  5293. // quaternion is assumed to have unit length
  5294. return this.conjugate();
  5295. },
  5296. conjugate: function () {
  5297. this._x *= - 1;
  5298. this._y *= - 1;
  5299. this._z *= - 1;
  5300. this.onChangeCallback();
  5301. return this;
  5302. },
  5303. dot: function ( v ) {
  5304. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  5305. },
  5306. lengthSq: function () {
  5307. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  5308. },
  5309. length: function () {
  5310. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  5311. },
  5312. normalize: function () {
  5313. var l = this.length();
  5314. if ( l === 0 ) {
  5315. this._x = 0;
  5316. this._y = 0;
  5317. this._z = 0;
  5318. this._w = 1;
  5319. } else {
  5320. l = 1 / l;
  5321. this._x = this._x * l;
  5322. this._y = this._y * l;
  5323. this._z = this._z * l;
  5324. this._w = this._w * l;
  5325. }
  5326. this.onChangeCallback();
  5327. return this;
  5328. },
  5329. multiply: function ( q, p ) {
  5330. if ( p !== undefined ) {
  5331. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  5332. return this.multiplyQuaternions( q, p );
  5333. }
  5334. return this.multiplyQuaternions( this, q );
  5335. },
  5336. premultiply: function ( q ) {
  5337. return this.multiplyQuaternions( q, this );
  5338. },
  5339. multiplyQuaternions: function ( a, b ) {
  5340. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  5341. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  5342. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  5343. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  5344. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  5345. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  5346. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  5347. this.onChangeCallback();
  5348. return this;
  5349. },
  5350. slerp: function ( qb, t ) {
  5351. if ( t === 0 ) return this;
  5352. if ( t === 1 ) return this.copy( qb );
  5353. var x = this._x, y = this._y, z = this._z, w = this._w;
  5354. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  5355. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  5356. if ( cosHalfTheta < 0 ) {
  5357. this._w = - qb._w;
  5358. this._x = - qb._x;
  5359. this._y = - qb._y;
  5360. this._z = - qb._z;
  5361. cosHalfTheta = - cosHalfTheta;
  5362. } else {
  5363. this.copy( qb );
  5364. }
  5365. if ( cosHalfTheta >= 1.0 ) {
  5366. this._w = w;
  5367. this._x = x;
  5368. this._y = y;
  5369. this._z = z;
  5370. return this;
  5371. }
  5372. var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  5373. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  5374. var s = 1 - t;
  5375. this._w = s * w + t * this._w;
  5376. this._x = s * x + t * this._x;
  5377. this._y = s * y + t * this._y;
  5378. this._z = s * z + t * this._z;
  5379. return this.normalize();
  5380. }
  5381. var sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  5382. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  5383. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  5384. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  5385. this._w = ( w * ratioA + this._w * ratioB );
  5386. this._x = ( x * ratioA + this._x * ratioB );
  5387. this._y = ( y * ratioA + this._y * ratioB );
  5388. this._z = ( z * ratioA + this._z * ratioB );
  5389. this.onChangeCallback();
  5390. return this;
  5391. },
  5392. equals: function ( quaternion ) {
  5393. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  5394. },
  5395. fromArray: function ( array, offset ) {
  5396. if ( offset === undefined ) offset = 0;
  5397. this._x = array[ offset ];
  5398. this._y = array[ offset + 1 ];
  5399. this._z = array[ offset + 2 ];
  5400. this._w = array[ offset + 3 ];
  5401. this.onChangeCallback();
  5402. return this;
  5403. },
  5404. toArray: function ( array, offset ) {
  5405. if ( array === undefined ) array = [];
  5406. if ( offset === undefined ) offset = 0;
  5407. array[ offset ] = this._x;
  5408. array[ offset + 1 ] = this._y;
  5409. array[ offset + 2 ] = this._z;
  5410. array[ offset + 3 ] = this._w;
  5411. return array;
  5412. },
  5413. onChange: function ( callback ) {
  5414. this.onChangeCallback = callback;
  5415. return this;
  5416. },
  5417. onChangeCallback: function () {}
  5418. } );
  5419. /**
  5420. * @author mrdoob / http://mrdoob.com/
  5421. * @author kile / http://kile.stravaganza.org/
  5422. * @author philogb / http://blog.thejit.org/
  5423. * @author mikael emtinger / http://gomo.se/
  5424. * @author egraether / http://egraether.com/
  5425. * @author WestLangley / http://github.com/WestLangley
  5426. */
  5427. function Vector3( x, y, z ) {
  5428. this.x = x || 0;
  5429. this.y = y || 0;
  5430. this.z = z || 0;
  5431. }
  5432. Object.assign( Vector3.prototype, {
  5433. isVector3: true,
  5434. set: function ( x, y, z ) {
  5435. this.x = x;
  5436. this.y = y;
  5437. this.z = z;
  5438. return this;
  5439. },
  5440. setScalar: function ( scalar ) {
  5441. this.x = scalar;
  5442. this.y = scalar;
  5443. this.z = scalar;
  5444. return this;
  5445. },
  5446. setX: function ( x ) {
  5447. this.x = x;
  5448. return this;
  5449. },
  5450. setY: function ( y ) {
  5451. this.y = y;
  5452. return this;
  5453. },
  5454. setZ: function ( z ) {
  5455. this.z = z;
  5456. return this;
  5457. },
  5458. setComponent: function ( index, value ) {
  5459. switch ( index ) {
  5460. case 0: this.x = value; break;
  5461. case 1: this.y = value; break;
  5462. case 2: this.z = value; break;
  5463. default: throw new Error( 'index is out of range: ' + index );
  5464. }
  5465. return this;
  5466. },
  5467. getComponent: function ( index ) {
  5468. switch ( index ) {
  5469. case 0: return this.x;
  5470. case 1: return this.y;
  5471. case 2: return this.z;
  5472. default: throw new Error( 'index is out of range: ' + index );
  5473. }
  5474. },
  5475. clone: function () {
  5476. return new this.constructor( this.x, this.y, this.z );
  5477. },
  5478. copy: function ( v ) {
  5479. this.x = v.x;
  5480. this.y = v.y;
  5481. this.z = v.z;
  5482. return this;
  5483. },
  5484. add: function ( v, w ) {
  5485. if ( w !== undefined ) {
  5486. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  5487. return this.addVectors( v, w );
  5488. }
  5489. this.x += v.x;
  5490. this.y += v.y;
  5491. this.z += v.z;
  5492. return this;
  5493. },
  5494. addScalar: function ( s ) {
  5495. this.x += s;
  5496. this.y += s;
  5497. this.z += s;
  5498. return this;
  5499. },
  5500. addVectors: function ( a, b ) {
  5501. this.x = a.x + b.x;
  5502. this.y = a.y + b.y;
  5503. this.z = a.z + b.z;
  5504. return this;
  5505. },
  5506. addScaledVector: function ( v, s ) {
  5507. this.x += v.x * s;
  5508. this.y += v.y * s;
  5509. this.z += v.z * s;
  5510. return this;
  5511. },
  5512. sub: function ( v, w ) {
  5513. if ( w !== undefined ) {
  5514. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  5515. return this.subVectors( v, w );
  5516. }
  5517. this.x -= v.x;
  5518. this.y -= v.y;
  5519. this.z -= v.z;
  5520. return this;
  5521. },
  5522. subScalar: function ( s ) {
  5523. this.x -= s;
  5524. this.y -= s;
  5525. this.z -= s;
  5526. return this;
  5527. },
  5528. subVectors: function ( a, b ) {
  5529. this.x = a.x - b.x;
  5530. this.y = a.y - b.y;
  5531. this.z = a.z - b.z;
  5532. return this;
  5533. },
  5534. multiply: function ( v, w ) {
  5535. if ( w !== undefined ) {
  5536. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  5537. return this.multiplyVectors( v, w );
  5538. }
  5539. this.x *= v.x;
  5540. this.y *= v.y;
  5541. this.z *= v.z;
  5542. return this;
  5543. },
  5544. multiplyScalar: function ( scalar ) {
  5545. this.x *= scalar;
  5546. this.y *= scalar;
  5547. this.z *= scalar;
  5548. return this;
  5549. },
  5550. multiplyVectors: function ( a, b ) {
  5551. this.x = a.x * b.x;
  5552. this.y = a.y * b.y;
  5553. this.z = a.z * b.z;
  5554. return this;
  5555. },
  5556. applyEuler: function () {
  5557. var quaternion = new Quaternion();
  5558. return function applyEuler( euler ) {
  5559. if ( ! ( euler && euler.isEuler ) ) {
  5560. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  5561. }
  5562. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  5563. };
  5564. }(),
  5565. applyAxisAngle: function () {
  5566. var quaternion = new Quaternion();
  5567. return function applyAxisAngle( axis, angle ) {
  5568. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  5569. };
  5570. }(),
  5571. applyMatrix3: function ( m ) {
  5572. var x = this.x, y = this.y, z = this.z;
  5573. var e = m.elements;
  5574. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  5575. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  5576. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  5577. return this;
  5578. },
  5579. applyMatrix4: function ( m ) {
  5580. var x = this.x, y = this.y, z = this.z;
  5581. var e = m.elements;
  5582. var w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  5583. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  5584. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  5585. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  5586. return this;
  5587. },
  5588. applyQuaternion: function ( q ) {
  5589. var x = this.x, y = this.y, z = this.z;
  5590. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  5591. // calculate quat * vector
  5592. var ix = qw * x + qy * z - qz * y;
  5593. var iy = qw * y + qz * x - qx * z;
  5594. var iz = qw * z + qx * y - qy * x;
  5595. var iw = - qx * x - qy * y - qz * z;
  5596. // calculate result * inverse quat
  5597. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  5598. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  5599. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  5600. return this;
  5601. },
  5602. project: function ( camera ) {
  5603. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  5604. },
  5605. unproject: function () {
  5606. var matrix = new Matrix4();
  5607. return function unproject( camera ) {
  5608. return this.applyMatrix4( matrix.getInverse( camera.projectionMatrix ) ).applyMatrix4( camera.matrixWorld );
  5609. };
  5610. }(),
  5611. transformDirection: function ( m ) {
  5612. // input: THREE.Matrix4 affine matrix
  5613. // vector interpreted as a direction
  5614. var x = this.x, y = this.y, z = this.z;
  5615. var e = m.elements;
  5616. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  5617. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  5618. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  5619. return this.normalize();
  5620. },
  5621. divide: function ( v ) {
  5622. this.x /= v.x;
  5623. this.y /= v.y;
  5624. this.z /= v.z;
  5625. return this;
  5626. },
  5627. divideScalar: function ( scalar ) {
  5628. return this.multiplyScalar( 1 / scalar );
  5629. },
  5630. min: function ( v ) {
  5631. this.x = Math.min( this.x, v.x );
  5632. this.y = Math.min( this.y, v.y );
  5633. this.z = Math.min( this.z, v.z );
  5634. return this;
  5635. },
  5636. max: function ( v ) {
  5637. this.x = Math.max( this.x, v.x );
  5638. this.y = Math.max( this.y, v.y );
  5639. this.z = Math.max( this.z, v.z );
  5640. return this;
  5641. },
  5642. clamp: function ( min, max ) {
  5643. // assumes min < max, componentwise
  5644. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  5645. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  5646. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  5647. return this;
  5648. },
  5649. clampScalar: function () {
  5650. var min = new Vector3();
  5651. var max = new Vector3();
  5652. return function clampScalar( minVal, maxVal ) {
  5653. min.set( minVal, minVal, minVal );
  5654. max.set( maxVal, maxVal, maxVal );
  5655. return this.clamp( min, max );
  5656. };
  5657. }(),
  5658. clampLength: function ( min, max ) {
  5659. var length = this.length();
  5660. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  5661. },
  5662. floor: function () {
  5663. this.x = Math.floor( this.x );
  5664. this.y = Math.floor( this.y );
  5665. this.z = Math.floor( this.z );
  5666. return this;
  5667. },
  5668. ceil: function () {
  5669. this.x = Math.ceil( this.x );
  5670. this.y = Math.ceil( this.y );
  5671. this.z = Math.ceil( this.z );
  5672. return this;
  5673. },
  5674. round: function () {
  5675. this.x = Math.round( this.x );
  5676. this.y = Math.round( this.y );
  5677. this.z = Math.round( this.z );
  5678. return this;
  5679. },
  5680. roundToZero: function () {
  5681. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  5682. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  5683. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  5684. return this;
  5685. },
  5686. negate: function () {
  5687. this.x = - this.x;
  5688. this.y = - this.y;
  5689. this.z = - this.z;
  5690. return this;
  5691. },
  5692. dot: function ( v ) {
  5693. return this.x * v.x + this.y * v.y + this.z * v.z;
  5694. },
  5695. // TODO lengthSquared?
  5696. lengthSq: function () {
  5697. return this.x * this.x + this.y * this.y + this.z * this.z;
  5698. },
  5699. length: function () {
  5700. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  5701. },
  5702. manhattanLength: function () {
  5703. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  5704. },
  5705. normalize: function () {
  5706. return this.divideScalar( this.length() || 1 );
  5707. },
  5708. setLength: function ( length ) {
  5709. return this.normalize().multiplyScalar( length );
  5710. },
  5711. lerp: function ( v, alpha ) {
  5712. this.x += ( v.x - this.x ) * alpha;
  5713. this.y += ( v.y - this.y ) * alpha;
  5714. this.z += ( v.z - this.z ) * alpha;
  5715. return this;
  5716. },
  5717. lerpVectors: function ( v1, v2, alpha ) {
  5718. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  5719. },
  5720. cross: function ( v, w ) {
  5721. if ( w !== undefined ) {
  5722. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  5723. return this.crossVectors( v, w );
  5724. }
  5725. return this.crossVectors( this, v );
  5726. },
  5727. crossVectors: function ( a, b ) {
  5728. var ax = a.x, ay = a.y, az = a.z;
  5729. var bx = b.x, by = b.y, bz = b.z;
  5730. this.x = ay * bz - az * by;
  5731. this.y = az * bx - ax * bz;
  5732. this.z = ax * by - ay * bx;
  5733. return this;
  5734. },
  5735. projectOnVector: function ( vector ) {
  5736. var scalar = vector.dot( this ) / vector.lengthSq();
  5737. return this.copy( vector ).multiplyScalar( scalar );
  5738. },
  5739. projectOnPlane: function () {
  5740. var v1 = new Vector3();
  5741. return function projectOnPlane( planeNormal ) {
  5742. v1.copy( this ).projectOnVector( planeNormal );
  5743. return this.sub( v1 );
  5744. };
  5745. }(),
  5746. reflect: function () {
  5747. // reflect incident vector off plane orthogonal to normal
  5748. // normal is assumed to have unit length
  5749. var v1 = new Vector3();
  5750. return function reflect( normal ) {
  5751. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  5752. };
  5753. }(),
  5754. angleTo: function ( v ) {
  5755. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  5756. // clamp, to handle numerical problems
  5757. return Math.acos( _Math.clamp( theta, - 1, 1 ) );
  5758. },
  5759. distanceTo: function ( v ) {
  5760. return Math.sqrt( this.distanceToSquared( v ) );
  5761. },
  5762. distanceToSquared: function ( v ) {
  5763. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  5764. return dx * dx + dy * dy + dz * dz;
  5765. },
  5766. manhattanDistanceTo: function ( v ) {
  5767. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  5768. },
  5769. setFromSpherical: function ( s ) {
  5770. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  5771. },
  5772. setFromSphericalCoords: function ( radius, phi, theta ) {
  5773. var sinPhiRadius = Math.sin( phi ) * radius;
  5774. this.x = sinPhiRadius * Math.sin( theta );
  5775. this.y = Math.cos( phi ) * radius;
  5776. this.z = sinPhiRadius * Math.cos( theta );
  5777. return this;
  5778. },
  5779. setFromCylindrical: function ( c ) {
  5780. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  5781. },
  5782. setFromCylindricalCoords: function ( radius, theta, y ) {
  5783. this.x = radius * Math.sin( theta );
  5784. this.y = y;
  5785. this.z = radius * Math.cos( theta );
  5786. return this;
  5787. },
  5788. setFromMatrixPosition: function ( m ) {
  5789. var e = m.elements;
  5790. this.x = e[ 12 ];
  5791. this.y = e[ 13 ];
  5792. this.z = e[ 14 ];
  5793. return this;
  5794. },
  5795. setFromMatrixScale: function ( m ) {
  5796. var sx = this.setFromMatrixColumn( m, 0 ).length();
  5797. var sy = this.setFromMatrixColumn( m, 1 ).length();
  5798. var sz = this.setFromMatrixColumn( m, 2 ).length();
  5799. this.x = sx;
  5800. this.y = sy;
  5801. this.z = sz;
  5802. return this;
  5803. },
  5804. setFromMatrixColumn: function ( m, index ) {
  5805. return this.fromArray( m.elements, index * 4 );
  5806. },
  5807. equals: function ( v ) {
  5808. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  5809. },
  5810. fromArray: function ( array, offset ) {
  5811. if ( offset === undefined ) offset = 0;
  5812. this.x = array[ offset ];
  5813. this.y = array[ offset + 1 ];
  5814. this.z = array[ offset + 2 ];
  5815. return this;
  5816. },
  5817. toArray: function ( array, offset ) {
  5818. if ( array === undefined ) array = [];
  5819. if ( offset === undefined ) offset = 0;
  5820. array[ offset ] = this.x;
  5821. array[ offset + 1 ] = this.y;
  5822. array[ offset + 2 ] = this.z;
  5823. return array;
  5824. },
  5825. fromBufferAttribute: function ( attribute, index, offset ) {
  5826. if ( offset !== undefined ) {
  5827. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  5828. }
  5829. this.x = attribute.getX( index );
  5830. this.y = attribute.getY( index );
  5831. this.z = attribute.getZ( index );
  5832. return this;
  5833. }
  5834. } );
  5835. /**
  5836. * @author alteredq / http://alteredqualia.com/
  5837. * @author WestLangley / http://github.com/WestLangley
  5838. * @author bhouston / http://clara.io
  5839. * @author tschw
  5840. */
  5841. function Matrix3() {
  5842. this.elements = [
  5843. 1, 0, 0,
  5844. 0, 1, 0,
  5845. 0, 0, 1
  5846. ];
  5847. if ( arguments.length > 0 ) {
  5848. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  5849. }
  5850. }
  5851. Object.assign( Matrix3.prototype, {
  5852. isMatrix3: true,
  5853. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  5854. var te = this.elements;
  5855. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  5856. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  5857. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  5858. return this;
  5859. },
  5860. identity: function () {
  5861. this.set(
  5862. 1, 0, 0,
  5863. 0, 1, 0,
  5864. 0, 0, 1
  5865. );
  5866. return this;
  5867. },
  5868. clone: function () {
  5869. return new this.constructor().fromArray( this.elements );
  5870. },
  5871. copy: function ( m ) {
  5872. var te = this.elements;
  5873. var me = m.elements;
  5874. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  5875. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  5876. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  5877. return this;
  5878. },
  5879. setFromMatrix4: function ( m ) {
  5880. var me = m.elements;
  5881. this.set(
  5882. me[ 0 ], me[ 4 ], me[ 8 ],
  5883. me[ 1 ], me[ 5 ], me[ 9 ],
  5884. me[ 2 ], me[ 6 ], me[ 10 ]
  5885. );
  5886. return this;
  5887. },
  5888. applyToBufferAttribute: function () {
  5889. var v1 = new Vector3();
  5890. return function applyToBufferAttribute( attribute ) {
  5891. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  5892. v1.x = attribute.getX( i );
  5893. v1.y = attribute.getY( i );
  5894. v1.z = attribute.getZ( i );
  5895. v1.applyMatrix3( this );
  5896. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  5897. }
  5898. return attribute;
  5899. };
  5900. }(),
  5901. multiply: function ( m ) {
  5902. return this.multiplyMatrices( this, m );
  5903. },
  5904. premultiply: function ( m ) {
  5905. return this.multiplyMatrices( m, this );
  5906. },
  5907. multiplyMatrices: function ( a, b ) {
  5908. var ae = a.elements;
  5909. var be = b.elements;
  5910. var te = this.elements;
  5911. var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  5912. var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  5913. var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  5914. var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  5915. var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  5916. var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  5917. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  5918. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  5919. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  5920. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  5921. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  5922. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  5923. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  5924. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  5925. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  5926. return this;
  5927. },
  5928. multiplyScalar: function ( s ) {
  5929. var te = this.elements;
  5930. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  5931. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  5932. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  5933. return this;
  5934. },
  5935. determinant: function () {
  5936. var te = this.elements;
  5937. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  5938. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  5939. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  5940. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  5941. },
  5942. getInverse: function ( matrix, throwOnDegenerate ) {
  5943. if ( matrix && matrix.isMatrix4 ) {
  5944. console.error( "THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument." );
  5945. }
  5946. var me = matrix.elements,
  5947. te = this.elements,
  5948. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  5949. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  5950. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  5951. t11 = n33 * n22 - n32 * n23,
  5952. t12 = n32 * n13 - n33 * n12,
  5953. t13 = n23 * n12 - n22 * n13,
  5954. det = n11 * t11 + n21 * t12 + n31 * t13;
  5955. if ( det === 0 ) {
  5956. var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";
  5957. if ( throwOnDegenerate === true ) {
  5958. throw new Error( msg );
  5959. } else {
  5960. console.warn( msg );
  5961. }
  5962. return this.identity();
  5963. }
  5964. var detInv = 1 / det;
  5965. te[ 0 ] = t11 * detInv;
  5966. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  5967. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  5968. te[ 3 ] = t12 * detInv;
  5969. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  5970. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  5971. te[ 6 ] = t13 * detInv;
  5972. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  5973. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  5974. return this;
  5975. },
  5976. transpose: function () {
  5977. var tmp, m = this.elements;
  5978. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  5979. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  5980. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  5981. return this;
  5982. },
  5983. getNormalMatrix: function ( matrix4 ) {
  5984. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  5985. },
  5986. transposeIntoArray: function ( r ) {
  5987. var m = this.elements;
  5988. r[ 0 ] = m[ 0 ];
  5989. r[ 1 ] = m[ 3 ];
  5990. r[ 2 ] = m[ 6 ];
  5991. r[ 3 ] = m[ 1 ];
  5992. r[ 4 ] = m[ 4 ];
  5993. r[ 5 ] = m[ 7 ];
  5994. r[ 6 ] = m[ 2 ];
  5995. r[ 7 ] = m[ 5 ];
  5996. r[ 8 ] = m[ 8 ];
  5997. return this;
  5998. },
  5999. setUvTransform: function ( tx, ty, sx, sy, rotation, cx, cy ) {
  6000. var c = Math.cos( rotation );
  6001. var s = Math.sin( rotation );
  6002. this.set(
  6003. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  6004. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  6005. 0, 0, 1
  6006. );
  6007. },
  6008. scale: function ( sx, sy ) {
  6009. var te = this.elements;
  6010. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  6011. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  6012. return this;
  6013. },
  6014. rotate: function ( theta ) {
  6015. var c = Math.cos( theta );
  6016. var s = Math.sin( theta );
  6017. var te = this.elements;
  6018. var a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  6019. var a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  6020. te[ 0 ] = c * a11 + s * a21;
  6021. te[ 3 ] = c * a12 + s * a22;
  6022. te[ 6 ] = c * a13 + s * a23;
  6023. te[ 1 ] = - s * a11 + c * a21;
  6024. te[ 4 ] = - s * a12 + c * a22;
  6025. te[ 7 ] = - s * a13 + c * a23;
  6026. return this;
  6027. },
  6028. translate: function ( tx, ty ) {
  6029. var te = this.elements;
  6030. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  6031. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  6032. return this;
  6033. },
  6034. equals: function ( matrix ) {
  6035. var te = this.elements;
  6036. var me = matrix.elements;
  6037. for ( var i = 0; i < 9; i ++ ) {
  6038. if ( te[ i ] !== me[ i ] ) return false;
  6039. }
  6040. return true;
  6041. },
  6042. fromArray: function ( array, offset ) {
  6043. if ( offset === undefined ) offset = 0;
  6044. for ( var i = 0; i < 9; i ++ ) {
  6045. this.elements[ i ] = array[ i + offset ];
  6046. }
  6047. return this;
  6048. },
  6049. toArray: function ( array, offset ) {
  6050. if ( array === undefined ) array = [];
  6051. if ( offset === undefined ) offset = 0;
  6052. var te = this.elements;
  6053. array[ offset ] = te[ 0 ];
  6054. array[ offset + 1 ] = te[ 1 ];
  6055. array[ offset + 2 ] = te[ 2 ];
  6056. array[ offset + 3 ] = te[ 3 ];
  6057. array[ offset + 4 ] = te[ 4 ];
  6058. array[ offset + 5 ] = te[ 5 ];
  6059. array[ offset + 6 ] = te[ 6 ];
  6060. array[ offset + 7 ] = te[ 7 ];
  6061. array[ offset + 8 ] = te[ 8 ];
  6062. return array;
  6063. }
  6064. } );
  6065. /**
  6066. * @author mrdoob / http://mrdoob.com/
  6067. * @author alteredq / http://alteredqualia.com/
  6068. * @author szimek / https://github.com/szimek/
  6069. */
  6070. var ImageUtils = {
  6071. getDataURL: function ( image ) {
  6072. var canvas;
  6073. if ( typeof HTMLCanvasElement == 'undefined' ) {
  6074. return image.src;
  6075. } else if ( image instanceof HTMLCanvasElement ) {
  6076. canvas = image;
  6077. } else {
  6078. canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  6079. canvas.width = image.width;
  6080. canvas.height = image.height;
  6081. var context = canvas.getContext( '2d' );
  6082. if ( image instanceof ImageData ) {
  6083. context.putImageData( image, 0, 0 );
  6084. } else {
  6085. context.drawImage( image, 0, 0, image.width, image.height );
  6086. }
  6087. }
  6088. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  6089. return canvas.toDataURL( 'image/jpeg', 0.6 );
  6090. } else {
  6091. return canvas.toDataURL( 'image/png' );
  6092. }
  6093. }
  6094. };
  6095. /**
  6096. * @author mrdoob / http://mrdoob.com/
  6097. * @author alteredq / http://alteredqualia.com/
  6098. * @author szimek / https://github.com/szimek/
  6099. */
  6100. var textureId = 0;
  6101. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  6102. Object.defineProperty( this, 'id', { value: textureId ++ } );
  6103. this.uuid = _Math.generateUUID();
  6104. this.name = '';
  6105. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  6106. this.mipmaps = [];
  6107. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  6108. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  6109. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  6110. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  6111. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  6112. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  6113. this.format = format !== undefined ? format : RGBAFormat;
  6114. this.type = type !== undefined ? type : UnsignedByteType;
  6115. this.offset = new Vector2( 0, 0 );
  6116. this.repeat = new Vector2( 1, 1 );
  6117. this.center = new Vector2( 0, 0 );
  6118. this.rotation = 0;
  6119. this.matrixAutoUpdate = true;
  6120. this.matrix = new Matrix3();
  6121. this.generateMipmaps = true;
  6122. this.premultiplyAlpha = false;
  6123. this.flipY = true;
  6124. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  6125. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  6126. //
  6127. // Also changing the encoding after already used by a Material will not automatically make the Material
  6128. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  6129. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  6130. this.version = 0;
  6131. this.onUpdate = null;
  6132. }
  6133. Texture.DEFAULT_IMAGE = undefined;
  6134. Texture.DEFAULT_MAPPING = UVMapping;
  6135. Texture.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  6136. constructor: Texture,
  6137. isTexture: true,
  6138. updateMatrix: function () {
  6139. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  6140. },
  6141. clone: function () {
  6142. return new this.constructor().copy( this );
  6143. },
  6144. copy: function ( source ) {
  6145. this.name = source.name;
  6146. this.image = source.image;
  6147. this.mipmaps = source.mipmaps.slice( 0 );
  6148. this.mapping = source.mapping;
  6149. this.wrapS = source.wrapS;
  6150. this.wrapT = source.wrapT;
  6151. this.magFilter = source.magFilter;
  6152. this.minFilter = source.minFilter;
  6153. this.anisotropy = source.anisotropy;
  6154. this.format = source.format;
  6155. this.type = source.type;
  6156. this.offset.copy( source.offset );
  6157. this.repeat.copy( source.repeat );
  6158. this.center.copy( source.center );
  6159. this.rotation = source.rotation;
  6160. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6161. this.matrix.copy( source.matrix );
  6162. this.generateMipmaps = source.generateMipmaps;
  6163. this.premultiplyAlpha = source.premultiplyAlpha;
  6164. this.flipY = source.flipY;
  6165. this.unpackAlignment = source.unpackAlignment;
  6166. this.encoding = source.encoding;
  6167. return this;
  6168. },
  6169. toJSON: function ( meta ) {
  6170. var isRootObject = ( meta === undefined || typeof meta === 'string' );
  6171. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  6172. return meta.textures[ this.uuid ];
  6173. }
  6174. var output = {
  6175. metadata: {
  6176. version: 4.5,
  6177. type: 'Texture',
  6178. generator: 'Texture.toJSON'
  6179. },
  6180. uuid: this.uuid,
  6181. name: this.name,
  6182. mapping: this.mapping,
  6183. repeat: [ this.repeat.x, this.repeat.y ],
  6184. offset: [ this.offset.x, this.offset.y ],
  6185. center: [ this.center.x, this.center.y ],
  6186. rotation: this.rotation,
  6187. wrap: [ this.wrapS, this.wrapT ],
  6188. format: this.format,
  6189. minFilter: this.minFilter,
  6190. magFilter: this.magFilter,
  6191. anisotropy: this.anisotropy,
  6192. flipY: this.flipY
  6193. };
  6194. if ( this.image !== undefined ) {
  6195. // TODO: Move to THREE.Image
  6196. var image = this.image;
  6197. if ( image.uuid === undefined ) {
  6198. image.uuid = _Math.generateUUID(); // UGH
  6199. }
  6200. if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
  6201. var url;
  6202. if ( Array.isArray( image ) ) {
  6203. // process array of images e.g. CubeTexture
  6204. url = [];
  6205. for ( var i = 0, l = image.length; i < l; i ++ ) {
  6206. url.push( ImageUtils.getDataURL( image[ i ] ) );
  6207. }
  6208. } else {
  6209. // process single image
  6210. url = ImageUtils.getDataURL( image );
  6211. }
  6212. meta.images[ image.uuid ] = {
  6213. uuid: image.uuid,
  6214. url: url
  6215. };
  6216. }
  6217. output.image = image.uuid;
  6218. }
  6219. if ( ! isRootObject ) {
  6220. meta.textures[ this.uuid ] = output;
  6221. }
  6222. return output;
  6223. },
  6224. dispose: function () {
  6225. this.dispatchEvent( { type: 'dispose' } );
  6226. },
  6227. transformUv: function ( uv ) {
  6228. if ( this.mapping !== UVMapping ) return uv;
  6229. uv.applyMatrix3( this.matrix );
  6230. if ( uv.x < 0 || uv.x > 1 ) {
  6231. switch ( this.wrapS ) {
  6232. case RepeatWrapping:
  6233. uv.x = uv.x - Math.floor( uv.x );
  6234. break;
  6235. case ClampToEdgeWrapping:
  6236. uv.x = uv.x < 0 ? 0 : 1;
  6237. break;
  6238. case MirroredRepeatWrapping:
  6239. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  6240. uv.x = Math.ceil( uv.x ) - uv.x;
  6241. } else {
  6242. uv.x = uv.x - Math.floor( uv.x );
  6243. }
  6244. break;
  6245. }
  6246. }
  6247. if ( uv.y < 0 || uv.y > 1 ) {
  6248. switch ( this.wrapT ) {
  6249. case RepeatWrapping:
  6250. uv.y = uv.y - Math.floor( uv.y );
  6251. break;
  6252. case ClampToEdgeWrapping:
  6253. uv.y = uv.y < 0 ? 0 : 1;
  6254. break;
  6255. case MirroredRepeatWrapping:
  6256. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  6257. uv.y = Math.ceil( uv.y ) - uv.y;
  6258. } else {
  6259. uv.y = uv.y - Math.floor( uv.y );
  6260. }
  6261. break;
  6262. }
  6263. }
  6264. if ( this.flipY ) {
  6265. uv.y = 1 - uv.y;
  6266. }
  6267. return uv;
  6268. }
  6269. } );
  6270. Object.defineProperty( Texture.prototype, "needsUpdate", {
  6271. set: function ( value ) {
  6272. if ( value === true ) this.version ++;
  6273. }
  6274. } );
  6275. /**
  6276. * @author supereggbert / http://www.paulbrunt.co.uk/
  6277. * @author philogb / http://blog.thejit.org/
  6278. * @author mikael emtinger / http://gomo.se/
  6279. * @author egraether / http://egraether.com/
  6280. * @author WestLangley / http://github.com/WestLangley
  6281. */
  6282. function Vector4( x, y, z, w ) {
  6283. this.x = x || 0;
  6284. this.y = y || 0;
  6285. this.z = z || 0;
  6286. this.w = ( w !== undefined ) ? w : 1;
  6287. }
  6288. Object.assign( Vector4.prototype, {
  6289. isVector4: true,
  6290. set: function ( x, y, z, w ) {
  6291. this.x = x;
  6292. this.y = y;
  6293. this.z = z;
  6294. this.w = w;
  6295. return this;
  6296. },
  6297. setScalar: function ( scalar ) {
  6298. this.x = scalar;
  6299. this.y = scalar;
  6300. this.z = scalar;
  6301. this.w = scalar;
  6302. return this;
  6303. },
  6304. setX: function ( x ) {
  6305. this.x = x;
  6306. return this;
  6307. },
  6308. setY: function ( y ) {
  6309. this.y = y;
  6310. return this;
  6311. },
  6312. setZ: function ( z ) {
  6313. this.z = z;
  6314. return this;
  6315. },
  6316. setW: function ( w ) {
  6317. this.w = w;
  6318. return this;
  6319. },
  6320. setComponent: function ( index, value ) {
  6321. switch ( index ) {
  6322. case 0: this.x = value; break;
  6323. case 1: this.y = value; break;
  6324. case 2: this.z = value; break;
  6325. case 3: this.w = value; break;
  6326. default: throw new Error( 'index is out of range: ' + index );
  6327. }
  6328. return this;
  6329. },
  6330. getComponent: function ( index ) {
  6331. switch ( index ) {
  6332. case 0: return this.x;
  6333. case 1: return this.y;
  6334. case 2: return this.z;
  6335. case 3: return this.w;
  6336. default: throw new Error( 'index is out of range: ' + index );
  6337. }
  6338. },
  6339. clone: function () {
  6340. return new this.constructor( this.x, this.y, this.z, this.w );
  6341. },
  6342. copy: function ( v ) {
  6343. this.x = v.x;
  6344. this.y = v.y;
  6345. this.z = v.z;
  6346. this.w = ( v.w !== undefined ) ? v.w : 1;
  6347. return this;
  6348. },
  6349. add: function ( v, w ) {
  6350. if ( w !== undefined ) {
  6351. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  6352. return this.addVectors( v, w );
  6353. }
  6354. this.x += v.x;
  6355. this.y += v.y;
  6356. this.z += v.z;
  6357. this.w += v.w;
  6358. return this;
  6359. },
  6360. addScalar: function ( s ) {
  6361. this.x += s;
  6362. this.y += s;
  6363. this.z += s;
  6364. this.w += s;
  6365. return this;
  6366. },
  6367. addVectors: function ( a, b ) {
  6368. this.x = a.x + b.x;
  6369. this.y = a.y + b.y;
  6370. this.z = a.z + b.z;
  6371. this.w = a.w + b.w;
  6372. return this;
  6373. },
  6374. addScaledVector: function ( v, s ) {
  6375. this.x += v.x * s;
  6376. this.y += v.y * s;
  6377. this.z += v.z * s;
  6378. this.w += v.w * s;
  6379. return this;
  6380. },
  6381. sub: function ( v, w ) {
  6382. if ( w !== undefined ) {
  6383. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  6384. return this.subVectors( v, w );
  6385. }
  6386. this.x -= v.x;
  6387. this.y -= v.y;
  6388. this.z -= v.z;
  6389. this.w -= v.w;
  6390. return this;
  6391. },
  6392. subScalar: function ( s ) {
  6393. this.x -= s;
  6394. this.y -= s;
  6395. this.z -= s;
  6396. this.w -= s;
  6397. return this;
  6398. },
  6399. subVectors: function ( a, b ) {
  6400. this.x = a.x - b.x;
  6401. this.y = a.y - b.y;
  6402. this.z = a.z - b.z;
  6403. this.w = a.w - b.w;
  6404. return this;
  6405. },
  6406. multiplyScalar: function ( scalar ) {
  6407. this.x *= scalar;
  6408. this.y *= scalar;
  6409. this.z *= scalar;
  6410. this.w *= scalar;
  6411. return this;
  6412. },
  6413. applyMatrix4: function ( m ) {
  6414. var x = this.x, y = this.y, z = this.z, w = this.w;
  6415. var e = m.elements;
  6416. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6417. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6418. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6419. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6420. return this;
  6421. },
  6422. divideScalar: function ( scalar ) {
  6423. return this.multiplyScalar( 1 / scalar );
  6424. },
  6425. setAxisAngleFromQuaternion: function ( q ) {
  6426. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6427. // q is assumed to be normalized
  6428. this.w = 2 * Math.acos( q.w );
  6429. var s = Math.sqrt( 1 - q.w * q.w );
  6430. if ( s < 0.0001 ) {
  6431. this.x = 1;
  6432. this.y = 0;
  6433. this.z = 0;
  6434. } else {
  6435. this.x = q.x / s;
  6436. this.y = q.y / s;
  6437. this.z = q.z / s;
  6438. }
  6439. return this;
  6440. },
  6441. setAxisAngleFromRotationMatrix: function ( m ) {
  6442. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6443. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6444. var angle, x, y, z, // variables for result
  6445. epsilon = 0.01, // margin to allow for rounding errors
  6446. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6447. te = m.elements,
  6448. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6449. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6450. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6451. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6452. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6453. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6454. // singularity found
  6455. // first check for identity matrix which must have +1 for all terms
  6456. // in leading diagonal and zero in other terms
  6457. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6458. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6459. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6460. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6461. // this singularity is identity matrix so angle = 0
  6462. this.set( 1, 0, 0, 0 );
  6463. return this; // zero angle, arbitrary axis
  6464. }
  6465. // otherwise this singularity is angle = 180
  6466. angle = Math.PI;
  6467. var xx = ( m11 + 1 ) / 2;
  6468. var yy = ( m22 + 1 ) / 2;
  6469. var zz = ( m33 + 1 ) / 2;
  6470. var xy = ( m12 + m21 ) / 4;
  6471. var xz = ( m13 + m31 ) / 4;
  6472. var yz = ( m23 + m32 ) / 4;
  6473. if ( ( xx > yy ) && ( xx > zz ) ) {
  6474. // m11 is the largest diagonal term
  6475. if ( xx < epsilon ) {
  6476. x = 0;
  6477. y = 0.707106781;
  6478. z = 0.707106781;
  6479. } else {
  6480. x = Math.sqrt( xx );
  6481. y = xy / x;
  6482. z = xz / x;
  6483. }
  6484. } else if ( yy > zz ) {
  6485. // m22 is the largest diagonal term
  6486. if ( yy < epsilon ) {
  6487. x = 0.707106781;
  6488. y = 0;
  6489. z = 0.707106781;
  6490. } else {
  6491. y = Math.sqrt( yy );
  6492. x = xy / y;
  6493. z = yz / y;
  6494. }
  6495. } else {
  6496. // m33 is the largest diagonal term so base result on this
  6497. if ( zz < epsilon ) {
  6498. x = 0.707106781;
  6499. y = 0.707106781;
  6500. z = 0;
  6501. } else {
  6502. z = Math.sqrt( zz );
  6503. x = xz / z;
  6504. y = yz / z;
  6505. }
  6506. }
  6507. this.set( x, y, z, angle );
  6508. return this; // return 180 deg rotation
  6509. }
  6510. // as we have reached here there are no singularities so we can handle normally
  6511. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6512. ( m13 - m31 ) * ( m13 - m31 ) +
  6513. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6514. if ( Math.abs( s ) < 0.001 ) s = 1;
  6515. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6516. // caught by singularity test above, but I've left it in just in case
  6517. this.x = ( m32 - m23 ) / s;
  6518. this.y = ( m13 - m31 ) / s;
  6519. this.z = ( m21 - m12 ) / s;
  6520. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6521. return this;
  6522. },
  6523. min: function ( v ) {
  6524. this.x = Math.min( this.x, v.x );
  6525. this.y = Math.min( this.y, v.y );
  6526. this.z = Math.min( this.z, v.z );
  6527. this.w = Math.min( this.w, v.w );
  6528. return this;
  6529. },
  6530. max: function ( v ) {
  6531. this.x = Math.max( this.x, v.x );
  6532. this.y = Math.max( this.y, v.y );
  6533. this.z = Math.max( this.z, v.z );
  6534. this.w = Math.max( this.w, v.w );
  6535. return this;
  6536. },
  6537. clamp: function ( min, max ) {
  6538. // assumes min < max, componentwise
  6539. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  6540. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  6541. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  6542. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  6543. return this;
  6544. },
  6545. clampScalar: function () {
  6546. var min, max;
  6547. return function clampScalar( minVal, maxVal ) {
  6548. if ( min === undefined ) {
  6549. min = new Vector4();
  6550. max = new Vector4();
  6551. }
  6552. min.set( minVal, minVal, minVal, minVal );
  6553. max.set( maxVal, maxVal, maxVal, maxVal );
  6554. return this.clamp( min, max );
  6555. };
  6556. }(),
  6557. clampLength: function ( min, max ) {
  6558. var length = this.length();
  6559. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  6560. },
  6561. floor: function () {
  6562. this.x = Math.floor( this.x );
  6563. this.y = Math.floor( this.y );
  6564. this.z = Math.floor( this.z );
  6565. this.w = Math.floor( this.w );
  6566. return this;
  6567. },
  6568. ceil: function () {
  6569. this.x = Math.ceil( this.x );
  6570. this.y = Math.ceil( this.y );
  6571. this.z = Math.ceil( this.z );
  6572. this.w = Math.ceil( this.w );
  6573. return this;
  6574. },
  6575. round: function () {
  6576. this.x = Math.round( this.x );
  6577. this.y = Math.round( this.y );
  6578. this.z = Math.round( this.z );
  6579. this.w = Math.round( this.w );
  6580. return this;
  6581. },
  6582. roundToZero: function () {
  6583. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  6584. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  6585. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  6586. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  6587. return this;
  6588. },
  6589. negate: function () {
  6590. this.x = - this.x;
  6591. this.y = - this.y;
  6592. this.z = - this.z;
  6593. this.w = - this.w;
  6594. return this;
  6595. },
  6596. dot: function ( v ) {
  6597. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6598. },
  6599. lengthSq: function () {
  6600. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6601. },
  6602. length: function () {
  6603. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6604. },
  6605. manhattanLength: function () {
  6606. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6607. },
  6608. normalize: function () {
  6609. return this.divideScalar( this.length() || 1 );
  6610. },
  6611. setLength: function ( length ) {
  6612. return this.normalize().multiplyScalar( length );
  6613. },
  6614. lerp: function ( v, alpha ) {
  6615. this.x += ( v.x - this.x ) * alpha;
  6616. this.y += ( v.y - this.y ) * alpha;
  6617. this.z += ( v.z - this.z ) * alpha;
  6618. this.w += ( v.w - this.w ) * alpha;
  6619. return this;
  6620. },
  6621. lerpVectors: function ( v1, v2, alpha ) {
  6622. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  6623. },
  6624. equals: function ( v ) {
  6625. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6626. },
  6627. fromArray: function ( array, offset ) {
  6628. if ( offset === undefined ) offset = 0;
  6629. this.x = array[ offset ];
  6630. this.y = array[ offset + 1 ];
  6631. this.z = array[ offset + 2 ];
  6632. this.w = array[ offset + 3 ];
  6633. return this;
  6634. },
  6635. toArray: function ( array, offset ) {
  6636. if ( array === undefined ) array = [];
  6637. if ( offset === undefined ) offset = 0;
  6638. array[ offset ] = this.x;
  6639. array[ offset + 1 ] = this.y;
  6640. array[ offset + 2 ] = this.z;
  6641. array[ offset + 3 ] = this.w;
  6642. return array;
  6643. },
  6644. fromBufferAttribute: function ( attribute, index, offset ) {
  6645. if ( offset !== undefined ) {
  6646. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  6647. }
  6648. this.x = attribute.getX( index );
  6649. this.y = attribute.getY( index );
  6650. this.z = attribute.getZ( index );
  6651. this.w = attribute.getW( index );
  6652. return this;
  6653. }
  6654. } );
  6655. /**
  6656. * @author szimek / https://github.com/szimek/
  6657. * @author alteredq / http://alteredqualia.com/
  6658. * @author Marius Kintel / https://github.com/kintel
  6659. */
  6660. /*
  6661. In options, we can specify:
  6662. * Texture parameters for an auto-generated target texture
  6663. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  6664. */
  6665. function WebGLRenderTarget( width, height, options ) {
  6666. this.width = width;
  6667. this.height = height;
  6668. this.scissor = new Vector4( 0, 0, width, height );
  6669. this.scissorTest = false;
  6670. this.viewport = new Vector4( 0, 0, width, height );
  6671. options = options || {};
  6672. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  6673. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  6674. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  6675. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  6676. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  6677. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  6678. }
  6679. WebGLRenderTarget.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  6680. constructor: WebGLRenderTarget,
  6681. isWebGLRenderTarget: true,
  6682. setSize: function ( width, height ) {
  6683. if ( this.width !== width || this.height !== height ) {
  6684. this.width = width;
  6685. this.height = height;
  6686. this.dispose();
  6687. }
  6688. this.viewport.set( 0, 0, width, height );
  6689. this.scissor.set( 0, 0, width, height );
  6690. },
  6691. clone: function () {
  6692. return new this.constructor().copy( this );
  6693. },
  6694. copy: function ( source ) {
  6695. this.width = source.width;
  6696. this.height = source.height;
  6697. this.viewport.copy( source.viewport );
  6698. this.texture = source.texture.clone();
  6699. this.depthBuffer = source.depthBuffer;
  6700. this.stencilBuffer = source.stencilBuffer;
  6701. this.depthTexture = source.depthTexture;
  6702. return this;
  6703. },
  6704. dispose: function () {
  6705. this.dispatchEvent( { type: 'dispose' } );
  6706. }
  6707. } );
  6708. /**
  6709. * @author alteredq / http://alteredqualia.com
  6710. */
  6711. function WebGLRenderTargetCube( width, height, options ) {
  6712. WebGLRenderTarget.call( this, width, height, options );
  6713. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  6714. this.activeMipMapLevel = 0;
  6715. }
  6716. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  6717. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  6718. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  6719. /**
  6720. * @author alteredq / http://alteredqualia.com/
  6721. */
  6722. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  6723. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  6724. this.image = { data: data, width: width, height: height };
  6725. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  6726. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  6727. this.generateMipmaps = false;
  6728. this.flipY = false;
  6729. this.unpackAlignment = 1;
  6730. }
  6731. DataTexture.prototype = Object.create( Texture.prototype );
  6732. DataTexture.prototype.constructor = DataTexture;
  6733. DataTexture.prototype.isDataTexture = true;
  6734. /**
  6735. * @author bhouston / http://clara.io
  6736. * @author WestLangley / http://github.com/WestLangley
  6737. */
  6738. function Box3( min, max ) {
  6739. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  6740. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  6741. }
  6742. Object.assign( Box3.prototype, {
  6743. isBox3: true,
  6744. set: function ( min, max ) {
  6745. this.min.copy( min );
  6746. this.max.copy( max );
  6747. return this;
  6748. },
  6749. setFromArray: function ( array ) {
  6750. var minX = + Infinity;
  6751. var minY = + Infinity;
  6752. var minZ = + Infinity;
  6753. var maxX = - Infinity;
  6754. var maxY = - Infinity;
  6755. var maxZ = - Infinity;
  6756. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  6757. var x = array[ i ];
  6758. var y = array[ i + 1 ];
  6759. var z = array[ i + 2 ];
  6760. if ( x < minX ) minX = x;
  6761. if ( y < minY ) minY = y;
  6762. if ( z < minZ ) minZ = z;
  6763. if ( x > maxX ) maxX = x;
  6764. if ( y > maxY ) maxY = y;
  6765. if ( z > maxZ ) maxZ = z;
  6766. }
  6767. this.min.set( minX, minY, minZ );
  6768. this.max.set( maxX, maxY, maxZ );
  6769. return this;
  6770. },
  6771. setFromBufferAttribute: function ( attribute ) {
  6772. var minX = + Infinity;
  6773. var minY = + Infinity;
  6774. var minZ = + Infinity;
  6775. var maxX = - Infinity;
  6776. var maxY = - Infinity;
  6777. var maxZ = - Infinity;
  6778. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  6779. var x = attribute.getX( i );
  6780. var y = attribute.getY( i );
  6781. var z = attribute.getZ( i );
  6782. if ( x < minX ) minX = x;
  6783. if ( y < minY ) minY = y;
  6784. if ( z < minZ ) minZ = z;
  6785. if ( x > maxX ) maxX = x;
  6786. if ( y > maxY ) maxY = y;
  6787. if ( z > maxZ ) maxZ = z;
  6788. }
  6789. this.min.set( minX, minY, minZ );
  6790. this.max.set( maxX, maxY, maxZ );
  6791. return this;
  6792. },
  6793. setFromPoints: function ( points ) {
  6794. this.makeEmpty();
  6795. for ( var i = 0, il = points.length; i < il; i ++ ) {
  6796. this.expandByPoint( points[ i ] );
  6797. }
  6798. return this;
  6799. },
  6800. setFromCenterAndSize: function () {
  6801. var v1 = new Vector3();
  6802. return function setFromCenterAndSize( center, size ) {
  6803. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  6804. this.min.copy( center ).sub( halfSize );
  6805. this.max.copy( center ).add( halfSize );
  6806. return this;
  6807. };
  6808. }(),
  6809. setFromObject: function ( object ) {
  6810. this.makeEmpty();
  6811. return this.expandByObject( object );
  6812. },
  6813. clone: function () {
  6814. return new this.constructor().copy( this );
  6815. },
  6816. copy: function ( box ) {
  6817. this.min.copy( box.min );
  6818. this.max.copy( box.max );
  6819. return this;
  6820. },
  6821. makeEmpty: function () {
  6822. this.min.x = this.min.y = this.min.z = + Infinity;
  6823. this.max.x = this.max.y = this.max.z = - Infinity;
  6824. return this;
  6825. },
  6826. isEmpty: function () {
  6827. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  6828. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  6829. },
  6830. getCenter: function ( target ) {
  6831. if ( target === undefined ) {
  6832. console.warn( 'THREE.Box3: .getCenter() target is now required' );
  6833. target = new Vector3();
  6834. }
  6835. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  6836. },
  6837. getSize: function ( target ) {
  6838. if ( target === undefined ) {
  6839. console.warn( 'THREE.Box3: .getSize() target is now required' );
  6840. target = new Vector3();
  6841. }
  6842. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  6843. },
  6844. expandByPoint: function ( point ) {
  6845. this.min.min( point );
  6846. this.max.max( point );
  6847. return this;
  6848. },
  6849. expandByVector: function ( vector ) {
  6850. this.min.sub( vector );
  6851. this.max.add( vector );
  6852. return this;
  6853. },
  6854. expandByScalar: function ( scalar ) {
  6855. this.min.addScalar( - scalar );
  6856. this.max.addScalar( scalar );
  6857. return this;
  6858. },
  6859. expandByObject: function () {
  6860. // Computes the world-axis-aligned bounding box of an object (including its children),
  6861. // accounting for both the object's, and children's, world transforms
  6862. var scope, i, l;
  6863. var v1 = new Vector3();
  6864. function traverse( node ) {
  6865. var geometry = node.geometry;
  6866. if ( geometry !== undefined ) {
  6867. if ( geometry.isGeometry ) {
  6868. var vertices = geometry.vertices;
  6869. for ( i = 0, l = vertices.length; i < l; i ++ ) {
  6870. v1.copy( vertices[ i ] );
  6871. v1.applyMatrix4( node.matrixWorld );
  6872. scope.expandByPoint( v1 );
  6873. }
  6874. } else if ( geometry.isBufferGeometry ) {
  6875. var attribute = geometry.attributes.position;
  6876. if ( attribute !== undefined ) {
  6877. for ( i = 0, l = attribute.count; i < l; i ++ ) {
  6878. v1.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
  6879. scope.expandByPoint( v1 );
  6880. }
  6881. }
  6882. }
  6883. }
  6884. }
  6885. return function expandByObject( object ) {
  6886. scope = this;
  6887. object.updateMatrixWorld( true );
  6888. object.traverse( traverse );
  6889. return this;
  6890. };
  6891. }(),
  6892. containsPoint: function ( point ) {
  6893. return point.x < this.min.x || point.x > this.max.x ||
  6894. point.y < this.min.y || point.y > this.max.y ||
  6895. point.z < this.min.z || point.z > this.max.z ? false : true;
  6896. },
  6897. containsBox: function ( box ) {
  6898. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  6899. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  6900. this.min.z <= box.min.z && box.max.z <= this.max.z;
  6901. },
  6902. getParameter: function ( point, target ) {
  6903. // This can potentially have a divide by zero if the box
  6904. // has a size dimension of 0.
  6905. if ( target === undefined ) {
  6906. console.warn( 'THREE.Box3: .getParameter() target is now required' );
  6907. target = new Vector3();
  6908. }
  6909. return target.set(
  6910. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  6911. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  6912. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  6913. );
  6914. },
  6915. intersectsBox: function ( box ) {
  6916. // using 6 splitting planes to rule out intersections.
  6917. return box.max.x < this.min.x || box.min.x > this.max.x ||
  6918. box.max.y < this.min.y || box.min.y > this.max.y ||
  6919. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  6920. },
  6921. intersectsSphere: ( function () {
  6922. var closestPoint = new Vector3();
  6923. return function intersectsSphere( sphere ) {
  6924. // Find the point on the AABB closest to the sphere center.
  6925. this.clampPoint( sphere.center, closestPoint );
  6926. // If that point is inside the sphere, the AABB and sphere intersect.
  6927. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  6928. };
  6929. } )(),
  6930. intersectsPlane: function ( plane ) {
  6931. // We compute the minimum and maximum dot product values. If those values
  6932. // are on the same side (back or front) of the plane, then there is no intersection.
  6933. var min, max;
  6934. if ( plane.normal.x > 0 ) {
  6935. min = plane.normal.x * this.min.x;
  6936. max = plane.normal.x * this.max.x;
  6937. } else {
  6938. min = plane.normal.x * this.max.x;
  6939. max = plane.normal.x * this.min.x;
  6940. }
  6941. if ( plane.normal.y > 0 ) {
  6942. min += plane.normal.y * this.min.y;
  6943. max += plane.normal.y * this.max.y;
  6944. } else {
  6945. min += plane.normal.y * this.max.y;
  6946. max += plane.normal.y * this.min.y;
  6947. }
  6948. if ( plane.normal.z > 0 ) {
  6949. min += plane.normal.z * this.min.z;
  6950. max += plane.normal.z * this.max.z;
  6951. } else {
  6952. min += plane.normal.z * this.max.z;
  6953. max += plane.normal.z * this.min.z;
  6954. }
  6955. return ( min <= - plane.constant && max >= - plane.constant );
  6956. },
  6957. intersectsTriangle: ( function () {
  6958. // triangle centered vertices
  6959. var v0 = new Vector3();
  6960. var v1 = new Vector3();
  6961. var v2 = new Vector3();
  6962. // triangle edge vectors
  6963. var f0 = new Vector3();
  6964. var f1 = new Vector3();
  6965. var f2 = new Vector3();
  6966. var testAxis = new Vector3();
  6967. var center = new Vector3();
  6968. var extents = new Vector3();
  6969. var triangleNormal = new Vector3();
  6970. function satForAxes( axes ) {
  6971. var i, j;
  6972. for ( i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  6973. testAxis.fromArray( axes, i );
  6974. // project the aabb onto the seperating axis
  6975. var r = extents.x * Math.abs( testAxis.x ) + extents.y * Math.abs( testAxis.y ) + extents.z * Math.abs( testAxis.z );
  6976. // project all 3 vertices of the triangle onto the seperating axis
  6977. var p0 = v0.dot( testAxis );
  6978. var p1 = v1.dot( testAxis );
  6979. var p2 = v2.dot( testAxis );
  6980. // actual test, basically see if either of the most extreme of the triangle points intersects r
  6981. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  6982. // points of the projected triangle are outside the projected half-length of the aabb
  6983. // the axis is seperating and we can exit
  6984. return false;
  6985. }
  6986. }
  6987. return true;
  6988. }
  6989. return function intersectsTriangle( triangle ) {
  6990. if ( this.isEmpty() ) {
  6991. return false;
  6992. }
  6993. // compute box center and extents
  6994. this.getCenter( center );
  6995. extents.subVectors( this.max, center );
  6996. // translate triangle to aabb origin
  6997. v0.subVectors( triangle.a, center );
  6998. v1.subVectors( triangle.b, center );
  6999. v2.subVectors( triangle.c, center );
  7000. // compute edge vectors for triangle
  7001. f0.subVectors( v1, v0 );
  7002. f1.subVectors( v2, v1 );
  7003. f2.subVectors( v0, v2 );
  7004. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7005. // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation
  7006. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7007. var axes = [
  7008. 0, - f0.z, f0.y, 0, - f1.z, f1.y, 0, - f2.z, f2.y,
  7009. f0.z, 0, - f0.x, f1.z, 0, - f1.x, f2.z, 0, - f2.x,
  7010. - f0.y, f0.x, 0, - f1.y, f1.x, 0, - f2.y, f2.x, 0
  7011. ];
  7012. if ( ! satForAxes( axes ) ) {
  7013. return false;
  7014. }
  7015. // test 3 face normals from the aabb
  7016. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7017. if ( ! satForAxes( axes ) ) {
  7018. return false;
  7019. }
  7020. // finally testing the face normal of the triangle
  7021. // use already existing triangle edge vectors here
  7022. triangleNormal.crossVectors( f0, f1 );
  7023. axes = [ triangleNormal.x, triangleNormal.y, triangleNormal.z ];
  7024. return satForAxes( axes );
  7025. };
  7026. } )(),
  7027. clampPoint: function ( point, target ) {
  7028. if ( target === undefined ) {
  7029. console.warn( 'THREE.Box3: .clampPoint() target is now required' );
  7030. target = new Vector3();
  7031. }
  7032. return target.copy( point ).clamp( this.min, this.max );
  7033. },
  7034. distanceToPoint: function () {
  7035. var v1 = new Vector3();
  7036. return function distanceToPoint( point ) {
  7037. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  7038. return clampedPoint.sub( point ).length();
  7039. };
  7040. }(),
  7041. getBoundingSphere: function () {
  7042. var v1 = new Vector3();
  7043. return function getBoundingSphere( target ) {
  7044. if ( target === undefined ) {
  7045. console.warn( 'THREE.Box3: .getBoundingSphere() target is now required' );
  7046. target = new Sphere();
  7047. }
  7048. this.getCenter( target.center );
  7049. target.radius = this.getSize( v1 ).length() * 0.5;
  7050. return target;
  7051. };
  7052. }(),
  7053. intersect: function ( box ) {
  7054. this.min.max( box.min );
  7055. this.max.min( box.max );
  7056. // 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.
  7057. if ( this.isEmpty() ) this.makeEmpty();
  7058. return this;
  7059. },
  7060. union: function ( box ) {
  7061. this.min.min( box.min );
  7062. this.max.max( box.max );
  7063. return this;
  7064. },
  7065. applyMatrix4: function () {
  7066. var points = [
  7067. new Vector3(),
  7068. new Vector3(),
  7069. new Vector3(),
  7070. new Vector3(),
  7071. new Vector3(),
  7072. new Vector3(),
  7073. new Vector3(),
  7074. new Vector3()
  7075. ];
  7076. return function applyMatrix4( matrix ) {
  7077. // transform of empty box is an empty box.
  7078. if ( this.isEmpty() ) return this;
  7079. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  7080. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  7081. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  7082. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  7083. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  7084. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  7085. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  7086. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  7087. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  7088. this.setFromPoints( points );
  7089. return this;
  7090. };
  7091. }(),
  7092. translate: function ( offset ) {
  7093. this.min.add( offset );
  7094. this.max.add( offset );
  7095. return this;
  7096. },
  7097. equals: function ( box ) {
  7098. return box.min.equals( this.min ) && box.max.equals( this.max );
  7099. }
  7100. } );
  7101. /**
  7102. * @author bhouston / http://clara.io
  7103. * @author mrdoob / http://mrdoob.com/
  7104. */
  7105. function Sphere( center, radius ) {
  7106. this.center = ( center !== undefined ) ? center : new Vector3();
  7107. this.radius = ( radius !== undefined ) ? radius : 0;
  7108. }
  7109. Object.assign( Sphere.prototype, {
  7110. set: function ( center, radius ) {
  7111. this.center.copy( center );
  7112. this.radius = radius;
  7113. return this;
  7114. },
  7115. setFromPoints: function () {
  7116. var box = new Box3();
  7117. return function setFromPoints( points, optionalCenter ) {
  7118. var center = this.center;
  7119. if ( optionalCenter !== undefined ) {
  7120. center.copy( optionalCenter );
  7121. } else {
  7122. box.setFromPoints( points ).getCenter( center );
  7123. }
  7124. var maxRadiusSq = 0;
  7125. for ( var i = 0, il = points.length; i < il; i ++ ) {
  7126. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  7127. }
  7128. this.radius = Math.sqrt( maxRadiusSq );
  7129. return this;
  7130. };
  7131. }(),
  7132. clone: function () {
  7133. return new this.constructor().copy( this );
  7134. },
  7135. copy: function ( sphere ) {
  7136. this.center.copy( sphere.center );
  7137. this.radius = sphere.radius;
  7138. return this;
  7139. },
  7140. empty: function () {
  7141. return ( this.radius <= 0 );
  7142. },
  7143. containsPoint: function ( point ) {
  7144. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  7145. },
  7146. distanceToPoint: function ( point ) {
  7147. return ( point.distanceTo( this.center ) - this.radius );
  7148. },
  7149. intersectsSphere: function ( sphere ) {
  7150. var radiusSum = this.radius + sphere.radius;
  7151. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  7152. },
  7153. intersectsBox: function ( box ) {
  7154. return box.intersectsSphere( this );
  7155. },
  7156. intersectsPlane: function ( plane ) {
  7157. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  7158. },
  7159. clampPoint: function ( point, target ) {
  7160. var deltaLengthSq = this.center.distanceToSquared( point );
  7161. if ( target === undefined ) {
  7162. console.warn( 'THREE.Sphere: .clampPoint() target is now required' );
  7163. target = new Vector3();
  7164. }
  7165. target.copy( point );
  7166. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  7167. target.sub( this.center ).normalize();
  7168. target.multiplyScalar( this.radius ).add( this.center );
  7169. }
  7170. return target;
  7171. },
  7172. getBoundingBox: function ( target ) {
  7173. if ( target === undefined ) {
  7174. console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' );
  7175. target = new Box3();
  7176. }
  7177. target.set( this.center, this.center );
  7178. target.expandByScalar( this.radius );
  7179. return target;
  7180. },
  7181. applyMatrix4: function ( matrix ) {
  7182. this.center.applyMatrix4( matrix );
  7183. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  7184. return this;
  7185. },
  7186. translate: function ( offset ) {
  7187. this.center.add( offset );
  7188. return this;
  7189. },
  7190. equals: function ( sphere ) {
  7191. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  7192. }
  7193. } );
  7194. /**
  7195. * @author bhouston / http://clara.io
  7196. */
  7197. function Plane( normal, constant ) {
  7198. // normal is assumed to be normalized
  7199. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  7200. this.constant = ( constant !== undefined ) ? constant : 0;
  7201. }
  7202. Object.assign( Plane.prototype, {
  7203. set: function ( normal, constant ) {
  7204. this.normal.copy( normal );
  7205. this.constant = constant;
  7206. return this;
  7207. },
  7208. setComponents: function ( x, y, z, w ) {
  7209. this.normal.set( x, y, z );
  7210. this.constant = w;
  7211. return this;
  7212. },
  7213. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  7214. this.normal.copy( normal );
  7215. this.constant = - point.dot( this.normal );
  7216. return this;
  7217. },
  7218. setFromCoplanarPoints: function () {
  7219. var v1 = new Vector3();
  7220. var v2 = new Vector3();
  7221. return function setFromCoplanarPoints( a, b, c ) {
  7222. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  7223. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7224. this.setFromNormalAndCoplanarPoint( normal, a );
  7225. return this;
  7226. };
  7227. }(),
  7228. clone: function () {
  7229. return new this.constructor().copy( this );
  7230. },
  7231. copy: function ( plane ) {
  7232. this.normal.copy( plane.normal );
  7233. this.constant = plane.constant;
  7234. return this;
  7235. },
  7236. normalize: function () {
  7237. // Note: will lead to a divide by zero if the plane is invalid.
  7238. var inverseNormalLength = 1.0 / this.normal.length();
  7239. this.normal.multiplyScalar( inverseNormalLength );
  7240. this.constant *= inverseNormalLength;
  7241. return this;
  7242. },
  7243. negate: function () {
  7244. this.constant *= - 1;
  7245. this.normal.negate();
  7246. return this;
  7247. },
  7248. distanceToPoint: function ( point ) {
  7249. return this.normal.dot( point ) + this.constant;
  7250. },
  7251. distanceToSphere: function ( sphere ) {
  7252. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7253. },
  7254. projectPoint: function ( point, target ) {
  7255. if ( target === undefined ) {
  7256. console.warn( 'THREE.Plane: .projectPoint() target is now required' );
  7257. target = new Vector3();
  7258. }
  7259. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  7260. },
  7261. intersectLine: function () {
  7262. var v1 = new Vector3();
  7263. return function intersectLine( line, target ) {
  7264. if ( target === undefined ) {
  7265. console.warn( 'THREE.Plane: .intersectLine() target is now required' );
  7266. target = new Vector3();
  7267. }
  7268. var direction = line.delta( v1 );
  7269. var denominator = this.normal.dot( direction );
  7270. if ( denominator === 0 ) {
  7271. // line is coplanar, return origin
  7272. if ( this.distanceToPoint( line.start ) === 0 ) {
  7273. return target.copy( line.start );
  7274. }
  7275. // Unsure if this is the correct method to handle this case.
  7276. return undefined;
  7277. }
  7278. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7279. if ( t < 0 || t > 1 ) {
  7280. return undefined;
  7281. }
  7282. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  7283. };
  7284. }(),
  7285. intersectsLine: function ( line ) {
  7286. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7287. var startSign = this.distanceToPoint( line.start );
  7288. var endSign = this.distanceToPoint( line.end );
  7289. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7290. },
  7291. intersectsBox: function ( box ) {
  7292. return box.intersectsPlane( this );
  7293. },
  7294. intersectsSphere: function ( sphere ) {
  7295. return sphere.intersectsPlane( this );
  7296. },
  7297. coplanarPoint: function ( target ) {
  7298. if ( target === undefined ) {
  7299. console.warn( 'THREE.Plane: .coplanarPoint() target is now required' );
  7300. target = new Vector3();
  7301. }
  7302. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7303. },
  7304. applyMatrix4: function () {
  7305. var v1 = new Vector3();
  7306. var m1 = new Matrix3();
  7307. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  7308. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  7309. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  7310. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7311. this.constant = - referencePoint.dot( normal );
  7312. return this;
  7313. };
  7314. }(),
  7315. translate: function ( offset ) {
  7316. this.constant -= offset.dot( this.normal );
  7317. return this;
  7318. },
  7319. equals: function ( plane ) {
  7320. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7321. }
  7322. } );
  7323. /**
  7324. * @author mrdoob / http://mrdoob.com/
  7325. * @author alteredq / http://alteredqualia.com/
  7326. * @author bhouston / http://clara.io
  7327. */
  7328. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  7329. this.planes = [
  7330. ( p0 !== undefined ) ? p0 : new Plane(),
  7331. ( p1 !== undefined ) ? p1 : new Plane(),
  7332. ( p2 !== undefined ) ? p2 : new Plane(),
  7333. ( p3 !== undefined ) ? p3 : new Plane(),
  7334. ( p4 !== undefined ) ? p4 : new Plane(),
  7335. ( p5 !== undefined ) ? p5 : new Plane()
  7336. ];
  7337. }
  7338. Object.assign( Frustum.prototype, {
  7339. set: function ( p0, p1, p2, p3, p4, p5 ) {
  7340. var planes = this.planes;
  7341. planes[ 0 ].copy( p0 );
  7342. planes[ 1 ].copy( p1 );
  7343. planes[ 2 ].copy( p2 );
  7344. planes[ 3 ].copy( p3 );
  7345. planes[ 4 ].copy( p4 );
  7346. planes[ 5 ].copy( p5 );
  7347. return this;
  7348. },
  7349. clone: function () {
  7350. return new this.constructor().copy( this );
  7351. },
  7352. copy: function ( frustum ) {
  7353. var planes = this.planes;
  7354. for ( var i = 0; i < 6; i ++ ) {
  7355. planes[ i ].copy( frustum.planes[ i ] );
  7356. }
  7357. return this;
  7358. },
  7359. setFromMatrix: function ( m ) {
  7360. var planes = this.planes;
  7361. var me = m.elements;
  7362. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7363. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7364. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7365. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7366. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7367. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7368. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7369. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7370. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7371. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7372. return this;
  7373. },
  7374. intersectsObject: function () {
  7375. var sphere = new Sphere();
  7376. return function intersectsObject( object ) {
  7377. var geometry = object.geometry;
  7378. if ( geometry.boundingSphere === null )
  7379. geometry.computeBoundingSphere();
  7380. sphere.copy( geometry.boundingSphere )
  7381. .applyMatrix4( object.matrixWorld );
  7382. return this.intersectsSphere( sphere );
  7383. };
  7384. }(),
  7385. intersectsSprite: function () {
  7386. var sphere = new Sphere();
  7387. return function intersectsSprite( sprite ) {
  7388. sphere.center.set( 0, 0, 0 );
  7389. sphere.radius = 0.7071067811865476;
  7390. sphere.applyMatrix4( sprite.matrixWorld );
  7391. return this.intersectsSphere( sphere );
  7392. };
  7393. }(),
  7394. intersectsSphere: function ( sphere ) {
  7395. var planes = this.planes;
  7396. var center = sphere.center;
  7397. var negRadius = - sphere.radius;
  7398. for ( var i = 0; i < 6; i ++ ) {
  7399. var distance = planes[ i ].distanceToPoint( center );
  7400. if ( distance < negRadius ) {
  7401. return false;
  7402. }
  7403. }
  7404. return true;
  7405. },
  7406. intersectsBox: function () {
  7407. var p = new Vector3();
  7408. return function intersectsBox( box ) {
  7409. var planes = this.planes;
  7410. for ( var i = 0; i < 6; i ++ ) {
  7411. var plane = planes[ i ];
  7412. // corner at max distance
  7413. p.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7414. p.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7415. p.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7416. if ( plane.distanceToPoint( p ) < 0 ) {
  7417. return false;
  7418. }
  7419. }
  7420. return true;
  7421. };
  7422. }(),
  7423. containsPoint: function ( point ) {
  7424. var planes = this.planes;
  7425. for ( var i = 0; i < 6; i ++ ) {
  7426. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7427. return false;
  7428. }
  7429. }
  7430. return true;
  7431. }
  7432. } );
  7433. var alphamap_fragment = "#ifdef USE_ALPHAMAP\r\n\r\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\r\n\r\n#endif\r\n";
  7434. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\r\n\r\n\tuniform sampler2D alphaMap;\r\n\r\n#endif\r\n";
  7435. var alphatest_fragment = "#ifdef ALPHATEST\r\n\r\n\tif ( diffuseColor.a < ALPHATEST ) discard;\r\n\r\n#endif\r\n";
  7436. var aomap_fragment = "#ifdef USE_AOMAP\r\n\r\n\t// reads channel R, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\r\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\r\n\r\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\r\n\r\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\r\n\r\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\r\n\r\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  7437. var aomap_pars_fragment = "#ifdef USE_AOMAP\r\n\r\n\tuniform sampler2D aoMap;\r\n\tuniform float aoMapIntensity;\r\n\r\n#endif";
  7438. var begin_vertex = "\r\nvec3 transformed = vec3( position );\r\n";
  7439. var beginnormal_vertex = "\r\nvec3 objectNormal = vec3( normal );\r\n";
  7440. var bsdfs = "float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\r\n\r\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\r\n\r\n\t// based upon Frostbite 3 Moving to Physically-based Rendering\r\n\t// page 32, equation 26: E[window1]\r\n\t// https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf\r\n\t// this is intended to be used on spot and point lights who are represented as luminous intensity\r\n\t// but who must be converted to luminous irradiance for surface lighting calculation\r\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\r\n\r\n\tif( cutoffDistance > 0.0 ) {\r\n\r\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\r\n\r\n\t}\r\n\r\n\treturn distanceFalloff;\r\n\r\n#else\r\n\r\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\r\n\r\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\r\n\r\n\t}\r\n\r\n\treturn 1.0;\r\n\r\n#endif\r\n\r\n}\r\n\r\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\r\n\r\n\treturn RECIPROCAL_PI * diffuseColor;\r\n\r\n} // validated\r\n\r\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\r\n\r\n\t// Original approximation by Christophe Schlick '94\r\n\t// float fresnel = pow( 1.0 - dotLH, 5.0 );\r\n\r\n\t// Optimized variant (presented by Epic at SIGGRAPH '13)\r\n\t// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf\r\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\r\n\r\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\r\n\r\n} // validated\r\n\r\n// Microfacet Models for Refraction through Rough Surfaces - equation (34)\r\n// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\r\n// alpha is \"roughness squared\" in Disney’s reparameterization\r\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\r\n\r\n\t// geometry term (normalized) = G(l)⋅G(v) / 4(n⋅l)(n⋅v)\r\n\t// also see #12151\r\n\r\n\tfloat a2 = pow2( alpha );\r\n\r\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\r\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\r\n\r\n\treturn 1.0 / ( gl * gv );\r\n\r\n} // validated\r\n\r\n// Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2\r\n// https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf\r\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\r\n\r\n\tfloat a2 = pow2( alpha );\r\n\r\n\t// dotNL and dotNV are explicitly swapped. This is not a mistake.\r\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\r\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\r\n\r\n\treturn 0.5 / max( gv + gl, EPSILON );\r\n\r\n}\r\n\r\n// Microfacet Models for Refraction through Rough Surfaces - equation (33)\r\n// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\r\n// alpha is \"roughness squared\" in Disney’s reparameterization\r\nfloat D_GGX( const in float alpha, const in float dotNH ) {\r\n\r\n\tfloat a2 = pow2( alpha );\r\n\r\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; // avoid alpha = 0 with dotNH = 1\r\n\r\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\r\n\r\n}\r\n\r\n// GGX Distribution, Schlick Fresnel, GGX-Smith Visibility\r\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\r\n\r\n\tfloat alpha = pow2( roughness ); // UE4's roughness\r\n\r\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\r\n\r\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\r\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\r\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\r\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\r\n\r\n\tvec3 F = F_Schlick( specularColor, dotLH );\r\n\r\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\r\n\r\n\tfloat D = D_GGX( alpha, dotNH );\r\n\r\n\treturn F * ( G * D );\r\n\r\n} // validated\r\n\r\n// Rect Area Light\r\n\r\n// Real-Time Polygonal-Light Shading with Linearly Transformed Cosines\r\n// by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt\r\n// code: https://github.com/selfshadow/ltc_code/\r\n\r\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\r\n\r\n\tconst float LUT_SIZE = 64.0;\r\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\r\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\r\n\r\n\tfloat dotNV = saturate( dot( N, V ) );\r\n\r\n\t// texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )\r\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\r\n\r\n\tuv = uv * LUT_SCALE + LUT_BIAS;\r\n\r\n\treturn uv;\r\n\r\n}\r\n\r\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\r\n\r\n\t// Real-Time Area Lighting: a Journey from Research to Production (p.102)\r\n\t// An approximation of the form factor of a horizon-clipped rectangle.\r\n\r\n\tfloat l = length( f );\r\n\r\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\r\n\r\n}\r\n\r\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\r\n\r\n\tfloat x = dot( v1, v2 );\r\n\r\n\tfloat y = abs( x );\r\n\r\n\t// rational polynomial approximation to theta / sin( theta ) / 2PI\r\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\r\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\r\n\tfloat v = a / b;\r\n\r\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\r\n\r\n\treturn cross( v1, v2 ) * theta_sintheta;\r\n\r\n}\r\n\r\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\r\n\r\n\t// bail if point is on back side of plane of light\r\n\t// assumes ccw winding order of light vertices\r\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\r\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\r\n\tvec3 lightNormal = cross( v1, v2 );\r\n\r\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\r\n\r\n\t// construct orthonormal basis around N\r\n\tvec3 T1, T2;\r\n\tT1 = normalize( V - N * dot( V, N ) );\r\n\tT2 = - cross( N, T1 ); // negated from paper; possibly due to a different handedness of world coordinate system\r\n\r\n\t// compute transform\r\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\r\n\r\n\t// transform rect\r\n\tvec3 coords[ 4 ];\r\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\r\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\r\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\r\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\r\n\r\n\t// project rect onto sphere\r\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\r\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\r\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\r\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\r\n\r\n\t// calculate vector form factor\r\n\tvec3 vectorFormFactor = vec3( 0.0 );\r\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\r\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\r\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\r\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\r\n\r\n\t// adjust for horizon clipping\r\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\r\n\r\n\r\n\r\n\treturn vec3( result );\r\n\r\n}\r\n\r\n// End Rect Area Light\r\n\r\n// ref: https://www.unrealengine.com/blog/physically-based-shading-on-mobile - environmentBRDF for GGX on mobile\r\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\r\n\r\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\r\n\r\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\r\n\r\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\r\n\r\n\tvec4 r = roughness * c0 + c1;\r\n\r\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\r\n\r\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\r\n\r\n\treturn specularColor * AB.x + AB.y;\r\n\r\n} // validated\r\n\r\n\r\nfloat G_BlinnPhong_Implicit( ) {\r\n\r\n\t// geometry term is (n dot l)(n dot v) / 4(n dot l)(n dot v)\r\n\treturn 0.25;\r\n\r\n}\r\n\r\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\r\n\r\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\r\n\r\n}\r\n\r\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\r\n\r\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\r\n\r\n\t//float dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\r\n\t//float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\r\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\r\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\r\n\r\n\tvec3 F = F_Schlick( specularColor, dotLH );\r\n\r\n\tfloat G = G_BlinnPhong_Implicit( );\r\n\r\n\tfloat D = D_BlinnPhong( shininess, dotNH );\r\n\r\n\treturn F * ( G * D );\r\n\r\n} // validated\r\n\r\n// source: http://simonstechblog.blogspot.ca/2011/12/microfacet-brdf.html\r\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\r\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\r\n}\r\n\r\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\r\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\r\n}\r\n";
  7441. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\r\n\r\n\tuniform sampler2D bumpMap;\r\n\tuniform float bumpScale;\r\n\r\n\t// Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen\r\n\t// http://api.unrealengine.com/attachments/Engine/Rendering/LightingAndShadows/BumpMappingWithoutTangentSpace/mm_sfgrad_bump.pdf\r\n\r\n\t// Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)\r\n\r\n\tvec2 dHdxy_fwd() {\r\n\r\n\t\tvec2 dSTdx = dFdx( vUv );\r\n\t\tvec2 dSTdy = dFdy( vUv );\r\n\r\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\r\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\r\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\r\n\r\n\t\treturn vec2( dBx, dBy );\r\n\r\n\t}\r\n\r\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\r\n\r\n\t\t// Workaround for Adreno 3XX dFd*( vec3 ) bug. See #9988\r\n\r\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\r\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\r\n\t\tvec3 vN = surf_norm;\t\t// normalized\r\n\r\n\t\tvec3 R1 = cross( vSigmaY, vN );\r\n\t\tvec3 R2 = cross( vN, vSigmaX );\r\n\r\n\t\tfloat fDet = dot( vSigmaX, R1 );\r\n\r\n\t\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\r\n\r\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\r\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\r\n\r\n\t}\r\n\r\n#endif\r\n";
  7442. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\r\n\r\n\tvec4 plane;\r\n\r\n\t#pragma unroll_loop\r\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\r\n\r\n\t\tplane = clippingPlanes[ i ];\r\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\r\n\r\n\t}\r\n\r\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\r\n\r\n\t\tbool clipped = true;\r\n\r\n\t\t#pragma unroll_loop\r\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\r\n\r\n\t\t\tplane = clippingPlanes[ i ];\r\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\r\n\r\n\t\t}\r\n\r\n\t\tif ( clipped ) discard;\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  7443. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\r\n\r\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG ) && ! defined( MATCAP )\r\n\t\tvarying vec3 vViewPosition;\r\n\t#endif\r\n\r\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\r\n\r\n#endif\r\n";
  7444. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG ) && ! defined( MATCAP )\r\n\tvarying vec3 vViewPosition;\r\n#endif\r\n";
  7445. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG ) && ! defined( MATCAP )\r\n\tvViewPosition = - mvPosition.xyz;\r\n#endif\r\n\r\n";
  7446. var color_fragment = "#ifdef USE_COLOR\r\n\r\n\tdiffuseColor.rgb *= vColor;\r\n\r\n#endif";
  7447. var color_pars_fragment = "#ifdef USE_COLOR\r\n\r\n\tvarying vec3 vColor;\r\n\r\n#endif\r\n";
  7448. var color_pars_vertex = "#ifdef USE_COLOR\r\n\r\n\tvarying vec3 vColor;\r\n\r\n#endif";
  7449. var color_vertex = "#ifdef USE_COLOR\r\n\r\n\tvColor.xyz = color.xyz;\r\n\r\n#endif";
  7450. var common = "#define PI 3.14159265359\r\n#define PI2 6.28318530718\r\n#define PI_HALF 1.5707963267949\r\n#define RECIPROCAL_PI 0.31830988618\r\n#define RECIPROCAL_PI2 0.15915494\r\n#define LOG2 1.442695\r\n#define EPSILON 1e-6\r\n\r\n#define saturate(a) clamp( a, 0.0, 1.0 )\r\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\r\n\r\nfloat pow2( const in float x ) { return x*x; }\r\nfloat pow3( const in float x ) { return x*x*x; }\r\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\r\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\r\n// expects values in the range of [0,1]x[0,1], returns values in the [0,1] range.\r\n// do not collapse into a single function per: http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0/\r\nhighp float rand( const in vec2 uv ) {\r\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\r\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\r\n\treturn fract(sin(sn) * c);\r\n}\r\n\r\nstruct IncidentLight {\r\n\tvec3 color;\r\n\tvec3 direction;\r\n\tbool visible;\r\n};\r\n\r\nstruct ReflectedLight {\r\n\tvec3 directDiffuse;\r\n\tvec3 directSpecular;\r\n\tvec3 indirectDiffuse;\r\n\tvec3 indirectSpecular;\r\n};\r\n\r\nstruct GeometricContext {\r\n\tvec3 position;\r\n\tvec3 normal;\r\n\tvec3 viewDir;\r\n};\r\n\r\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\r\n\r\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\r\n\r\n}\r\n\r\n// http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations\r\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\r\n\r\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\r\n\r\n}\r\n\r\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\r\n\r\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\r\n\r\n\treturn - distance * planeNormal + point;\r\n\r\n}\r\n\r\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\r\n\r\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\r\n\r\n}\r\n\r\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\r\n\r\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\r\n\r\n}\r\n\r\nmat3 transposeMat3( const in mat3 m ) {\r\n\r\n\tmat3 tmp;\r\n\r\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\r\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\r\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\r\n\r\n\treturn tmp;\r\n\r\n}\r\n\r\n// https://en.wikipedia.org/wiki/Relative_luminance\r\nfloat linearToRelativeLuminance( const in vec3 color ) {\r\n\r\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\r\n\r\n\treturn dot( weights, color.rgb );\r\n\r\n}\r\n";
  7451. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\r\n\r\n#define cubeUV_textureSize (1024.0)\r\n\r\nint getFaceFromDirection(vec3 direction) {\r\n\tvec3 absDirection = abs(direction);\r\n\tint face = -1;\r\n\tif( absDirection.x > absDirection.z ) {\r\n\t\tif(absDirection.x > absDirection.y )\r\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\r\n\t\telse\r\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\r\n\t}\r\n\telse {\r\n\t\tif(absDirection.z > absDirection.y )\r\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\r\n\t\telse\r\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\r\n\t}\r\n\treturn face;\r\n}\r\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\r\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\r\n\r\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\r\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\r\n\tfloat dxRoughness = dFdx(roughness);\r\n\tfloat dyRoughness = dFdy(roughness);\r\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\r\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\r\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\r\n\t// Clamp the value to the max mip level counts. hard coded to 6 mips\r\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\r\n\tfloat mipLevel = 0.5 * log2(d);\r\n\treturn vec2(floor(mipLevel), fract(mipLevel));\r\n}\r\n\r\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\r\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\r\n\r\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\r\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\r\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\r\n\r\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\r\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\r\n\t// float powScale = exp2(roughnessLevel + mipLevel);\r\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\r\n\t// float scale = 1.0 / exp2(roughnessLevel + 2.0 + mipLevel);\r\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\r\n\t// float mipOffset = 0.75*(1.0 - 1.0/exp2(mipLevel))/exp2(roughnessLevel);\r\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\r\n\r\n\tbool bRes = mipLevel == 0.0;\r\n\tscale = bRes && (scale < a) ? a : scale;\r\n\r\n\tvec3 r;\r\n\tvec2 offset;\r\n\tint face = getFaceFromDirection(direction);\r\n\r\n\tfloat rcpPowScale = 1.0 / powScale;\r\n\r\n\tif( face == 0) {\r\n\t\tr = vec3(direction.x, -direction.z, direction.y);\r\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\r\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\r\n\t}\r\n\telse if( face == 1) {\r\n\t\tr = vec3(direction.y, direction.x, direction.z);\r\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\r\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\r\n\t}\r\n\telse if( face == 2) {\r\n\t\tr = vec3(direction.z, direction.x, direction.y);\r\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\r\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\r\n\t}\r\n\telse if( face == 3) {\r\n\t\tr = vec3(direction.x, direction.z, direction.y);\r\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\r\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\r\n\t}\r\n\telse if( face == 4) {\r\n\t\tr = vec3(direction.y, direction.x, -direction.z);\r\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\r\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\r\n\t}\r\n\telse {\r\n\t\tr = vec3(direction.z, -direction.x, direction.y);\r\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\r\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\r\n\t}\r\n\tr = normalize(r);\r\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\r\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\r\n\tvec2 base = offset + vec2( texelOffset );\r\n\treturn base + s * ( scale - 2.0 * texelOffset );\r\n}\r\n\r\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\r\n\r\nvec4 textureCubeUV( sampler2D envMap, vec3 reflectedDirection, float roughness ) {\r\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\r\n\tfloat r1 = floor(roughnessVal);\r\n\tfloat r2 = r1 + 1.0;\r\n\tfloat t = fract(roughnessVal);\r\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\r\n\tfloat s = mipInfo.y;\r\n\tfloat level0 = mipInfo.x;\r\n\tfloat level1 = level0 + 1.0;\r\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\r\n\r\n\t// round to nearest mipmap if we are not interpolating.\r\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\r\n\r\n\t// Tri linear interpolation.\r\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\r\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\r\n\r\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\r\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\r\n\r\n\tvec4 result = mix(color10, color20, t);\r\n\r\n\treturn vec4(result.rgb, 1.0);\r\n}\r\n\r\n#endif\r\n";
  7452. var defaultnormal_vertex = "vec3 transformedNormal = normalMatrix * objectNormal;\r\n\r\n#ifdef FLIP_SIDED\r\n\r\n\ttransformedNormal = - transformedNormal;\r\n\r\n#endif\r\n";
  7453. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\r\n\r\n\tuniform sampler2D displacementMap;\r\n\tuniform float displacementScale;\r\n\tuniform float displacementBias;\r\n\r\n#endif\r\n";
  7454. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\r\n\r\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\r\n\r\n#endif\r\n";
  7455. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\r\n\r\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\r\n\r\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\r\n\r\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\r\n\r\n#endif\r\n";
  7456. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\r\n\r\n\tuniform sampler2D emissiveMap;\r\n\r\n#endif\r\n";
  7457. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\r\n";
  7458. var encodings_pars_fragment = "// For a discussion of what this is, please read this: http://lousodrome.net/blog/light/2013/05/26/gamma-correct-and-hdr-rendering-in-a-32-bits-buffer/\r\n\r\nvec4 LinearToLinear( in vec4 value ) {\r\n\treturn value;\r\n}\r\n\r\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\r\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\r\n}\r\n\r\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\r\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\r\n}\r\n\r\nvec4 sRGBToLinear( in vec4 value ) {\r\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\r\n}\r\n\r\nvec4 LinearTosRGB( in vec4 value ) {\r\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\r\n}\r\n\r\nvec4 RGBEToLinear( in vec4 value ) {\r\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\r\n}\r\n\r\nvec4 LinearToRGBE( in vec4 value ) {\r\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\r\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\r\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\r\n// return vec4( value.brg, ( 3.0 + 128.0 ) / 256.0 );\r\n}\r\n\r\n// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html\r\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\r\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\r\n}\r\n\r\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\r\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\r\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\r\n\tM = ceil( M * 255.0 ) / 255.0;\r\n\treturn vec4( value.rgb / ( M * maxRange ), M );\r\n}\r\n\r\n// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html\r\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\r\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\r\n}\r\n\r\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\r\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\r\n\tfloat D = max( maxRange / maxRGB, 1.0 );\r\n\tD = min( floor( D ) / 255.0, 1.0 );\r\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\r\n}\r\n\r\n// LogLuv reference: http://graphicrants.blogspot.ca/2009/04/rgbm-color-encoding.html\r\n\r\n// M matrix, for encoding\r\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\r\nvec4 LinearToLogLuv( in vec4 value ) {\r\n\tvec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\r\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\r\n\tvec4 vResult;\r\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\r\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\r\n\tvResult.w = fract( Le );\r\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\r\n\treturn vResult;\r\n}\r\n\r\n// Inverse M matrix, for decoding\r\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\r\nvec4 LogLuvToLinear( in vec4 value ) {\r\n\tfloat Le = value.z * 255.0 + value.w;\r\n\tvec3 Xp_Y_XYZp;\r\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\r\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\r\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\r\n\tvec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\r\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\r\n}\r\n";
  7459. var envmap_fragment = "#ifdef USE_ENVMAP\r\n\r\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\r\n\r\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\r\n\r\n\t\t// Transforming Normal Vectors with the Inverse Transformation\r\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\r\n\r\n\t\t#ifdef ENVMAP_MODE_REFLECTION\r\n\r\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\r\n\r\n\t\t#else\r\n\r\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\r\n\r\n\t\t#endif\r\n\r\n\t#else\r\n\r\n\t\tvec3 reflectVec = vReflect;\r\n\r\n\t#endif\r\n\r\n\t#ifdef ENVMAP_TYPE_CUBE\r\n\r\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\r\n\r\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\r\n\r\n\t\tvec2 sampleUV;\r\n\r\n\t\treflectVec = normalize( reflectVec );\r\n\r\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\r\n\r\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\r\n\r\n\t#elif defined( ENVMAP_TYPE_SPHERE )\r\n\r\n\t\treflectVec = normalize( reflectVec );\r\n\r\n\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\r\n\r\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\r\n\r\n\t#else\r\n\r\n\t\tvec4 envColor = vec4( 0.0 );\r\n\r\n\t#endif\r\n\r\n\tenvColor = envMapTexelToLinear( envColor );\r\n\r\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\r\n\r\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\r\n\r\n\t#elif defined( ENVMAP_BLENDING_MIX )\r\n\r\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\r\n\r\n\t#elif defined( ENVMAP_BLENDING_ADD )\r\n\r\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  7460. var envmap_pars_fragment = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\r\n\tuniform float reflectivity;\r\n\tuniform float envMapIntensity;\r\n#endif\r\n\r\n#ifdef USE_ENVMAP\r\n\r\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\r\n\t\tvarying vec3 vWorldPosition;\r\n\t#endif\r\n\r\n\t#ifdef ENVMAP_TYPE_CUBE\r\n\t\tuniform samplerCube envMap;\r\n\t#else\r\n\t\tuniform sampler2D envMap;\r\n\t#endif\r\n\tuniform float flipEnvMap;\r\n\tuniform int maxMipLevel;\r\n\r\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\r\n\t\tuniform float refractionRatio;\r\n\t#else\r\n\t\tvarying vec3 vReflect;\r\n\t#endif\r\n\r\n#endif\r\n";
  7461. var envmap_pars_vertex = "#ifdef USE_ENVMAP\r\n\r\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\r\n\t\tvarying vec3 vWorldPosition;\r\n\r\n\t#else\r\n\r\n\t\tvarying vec3 vReflect;\r\n\t\tuniform float refractionRatio;\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  7462. var envmap_vertex = "#ifdef USE_ENVMAP\r\n\r\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\r\n\r\n\t\tvWorldPosition = worldPosition.xyz;\r\n\r\n\t#else\r\n\r\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\r\n\r\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\r\n\r\n\t\t#ifdef ENVMAP_MODE_REFLECTION\r\n\r\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\r\n\r\n\t\t#else\r\n\r\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\r\n\r\n\t\t#endif\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  7463. var fog_vertex = "#ifdef USE_FOG\r\n\r\n\tfogDepth = -mvPosition.z;\r\n\r\n#endif\r\n";
  7464. var fog_pars_vertex = "#ifdef USE_FOG\r\n\r\n\tvarying float fogDepth;\r\n\r\n#endif\r\n";
  7465. var fog_fragment = "#ifdef USE_FOG\r\n\r\n\t#ifdef FOG_EXP2\r\n\r\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 ) );\r\n\r\n\t#else\r\n\r\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\r\n\r\n\t#endif\r\n\r\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\r\n\r\n#endif\r\n";
  7466. var fog_pars_fragment = "#ifdef USE_FOG\r\n\r\n\tuniform vec3 fogColor;\r\n\tvarying float fogDepth;\r\n\r\n\t#ifdef FOG_EXP2\r\n\r\n\t\tuniform float fogDensity;\r\n\r\n\t#else\r\n\r\n\t\tuniform float fogNear;\r\n\t\tuniform float fogFar;\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  7467. var gradientmap_pars_fragment = "#ifdef TOON\r\n\r\n\tuniform sampler2D gradientMap;\r\n\r\n\tvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\r\n\r\n\t\t// dotNL will be from -1.0 to 1.0\r\n\t\tfloat dotNL = dot( normal, lightDirection );\r\n\t\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\r\n\r\n\t\t#ifdef USE_GRADIENTMAP\r\n\r\n\t\t\treturn texture2D( gradientMap, coord ).rgb;\r\n\r\n\t\t#else\r\n\r\n\t\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\r\n\r\n\t\t#endif\r\n\r\n\r\n\t}\r\n\r\n#endif\r\n";
  7468. var lightmap_fragment = "#ifdef USE_LIGHTMAP\r\n\r\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity; // factor of PI should not be present; included here to prevent breakage\r\n\r\n#endif\r\n";
  7469. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\r\n\r\n\tuniform sampler2D lightMap;\r\n\tuniform float lightMapIntensity;\r\n\r\n#endif";
  7470. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\r\n\r\nGeometricContext geometry;\r\ngeometry.position = mvPosition.xyz;\r\ngeometry.normal = normalize( transformedNormal );\r\ngeometry.viewDir = normalize( -mvPosition.xyz );\r\n\r\nGeometricContext backGeometry;\r\nbackGeometry.position = geometry.position;\r\nbackGeometry.normal = -geometry.normal;\r\nbackGeometry.viewDir = geometry.viewDir;\r\n\r\nvLightFront = vec3( 0.0 );\r\n\r\n#ifdef DOUBLE_SIDED\r\n\tvLightBack = vec3( 0.0 );\r\n#endif\r\n\r\nIncidentLight directLight;\r\nfloat dotNL;\r\nvec3 directLightColor_Diffuse;\r\n\r\n#if NUM_POINT_LIGHTS > 0\r\n\r\n\t#pragma unroll_loop\r\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\r\n\r\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\r\n\r\n\t\tdotNL = dot( geometry.normal, directLight.direction );\r\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\r\n\r\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\r\n\r\n\t\t#ifdef DOUBLE_SIDED\r\n\r\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\r\n\r\n\t\t#endif\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n#if NUM_SPOT_LIGHTS > 0\r\n\r\n\t#pragma unroll_loop\r\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\r\n\r\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\r\n\r\n\t\tdotNL = dot( geometry.normal, directLight.direction );\r\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\r\n\r\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\r\n\r\n\t\t#ifdef DOUBLE_SIDED\r\n\r\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\r\n\r\n\t\t#endif\r\n\t}\r\n\r\n#endif\r\n\r\n\r\n\r\n#if NUM_DIR_LIGHTS > 0\r\n\r\n\t#pragma unroll_loop\r\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\r\n\r\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\r\n\r\n\t\tdotNL = dot( geometry.normal, directLight.direction );\r\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\r\n\r\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\r\n\r\n\t\t#ifdef DOUBLE_SIDED\r\n\r\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\r\n\r\n\t\t#endif\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n#if NUM_HEMI_LIGHTS > 0\r\n\r\n\t#pragma unroll_loop\r\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\r\n\r\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\r\n\r\n\t\t#ifdef DOUBLE_SIDED\r\n\r\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\r\n\r\n\t\t#endif\r\n\r\n\t}\r\n\r\n#endif\r\n";
  7471. var lights_pars_begin = "uniform vec3 ambientLightColor;\r\n\r\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\r\n\r\n\tvec3 irradiance = ambientLightColor;\r\n\r\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\r\n\r\n\t\tirradiance *= PI;\r\n\r\n\t#endif\r\n\r\n\treturn irradiance;\r\n\r\n}\r\n\r\n#if NUM_DIR_LIGHTS > 0\r\n\r\n\tstruct DirectionalLight {\r\n\t\tvec3 direction;\r\n\t\tvec3 color;\r\n\r\n\t\tint shadow;\r\n\t\tfloat shadowBias;\r\n\t\tfloat shadowRadius;\r\n\t\tvec2 shadowMapSize;\r\n\t};\r\n\r\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\r\n\r\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\r\n\r\n\t\tdirectLight.color = directionalLight.color;\r\n\t\tdirectLight.direction = directionalLight.direction;\r\n\t\tdirectLight.visible = true;\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n\r\n#if NUM_POINT_LIGHTS > 0\r\n\r\n\tstruct PointLight {\r\n\t\tvec3 position;\r\n\t\tvec3 color;\r\n\t\tfloat distance;\r\n\t\tfloat decay;\r\n\r\n\t\tint shadow;\r\n\t\tfloat shadowBias;\r\n\t\tfloat shadowRadius;\r\n\t\tvec2 shadowMapSize;\r\n\t\tfloat shadowCameraNear;\r\n\t\tfloat shadowCameraFar;\r\n\t};\r\n\r\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\r\n\r\n\t// directLight is an out parameter as having it as a return value caused compiler errors on some devices\r\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\r\n\r\n\t\tvec3 lVector = pointLight.position - geometry.position;\r\n\t\tdirectLight.direction = normalize( lVector );\r\n\r\n\t\tfloat lightDistance = length( lVector );\r\n\r\n\t\tdirectLight.color = pointLight.color;\r\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\r\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n\r\n#if NUM_SPOT_LIGHTS > 0\r\n\r\n\tstruct SpotLight {\r\n\t\tvec3 position;\r\n\t\tvec3 direction;\r\n\t\tvec3 color;\r\n\t\tfloat distance;\r\n\t\tfloat decay;\r\n\t\tfloat coneCos;\r\n\t\tfloat penumbraCos;\r\n\r\n\t\tint shadow;\r\n\t\tfloat shadowBias;\r\n\t\tfloat shadowRadius;\r\n\t\tvec2 shadowMapSize;\r\n\t};\r\n\r\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\r\n\r\n\t// directLight is an out parameter as having it as a return value caused compiler errors on some devices\r\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\r\n\r\n\t\tvec3 lVector = spotLight.position - geometry.position;\r\n\t\tdirectLight.direction = normalize( lVector );\r\n\r\n\t\tfloat lightDistance = length( lVector );\r\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\r\n\r\n\t\tif ( angleCos > spotLight.coneCos ) {\r\n\r\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\r\n\r\n\t\t\tdirectLight.color = spotLight.color;\r\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\r\n\t\t\tdirectLight.visible = true;\r\n\r\n\t\t} else {\r\n\r\n\t\t\tdirectLight.color = vec3( 0.0 );\r\n\t\t\tdirectLight.visible = false;\r\n\r\n\t\t}\r\n\t}\r\n\r\n#endif\r\n\r\n\r\n#if NUM_RECT_AREA_LIGHTS > 0\r\n\r\n\tstruct RectAreaLight {\r\n\t\tvec3 color;\r\n\t\tvec3 position;\r\n\t\tvec3 halfWidth;\r\n\t\tvec3 halfHeight;\r\n\t};\r\n\r\n\t// Pre-computed values of LinearTransformedCosine approximation of BRDF\r\n\t// BRDF approximation Texture is 64x64\r\n\tuniform sampler2D ltc_1; // RGBA Float\r\n\tuniform sampler2D ltc_2; // RGBA Float\r\n\r\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\r\n\r\n#endif\r\n\r\n\r\n#if NUM_HEMI_LIGHTS > 0\r\n\r\n\tstruct HemisphereLight {\r\n\t\tvec3 direction;\r\n\t\tvec3 skyColor;\r\n\t\tvec3 groundColor;\r\n\t};\r\n\r\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\r\n\r\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\r\n\r\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\r\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\r\n\r\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\r\n\r\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\r\n\r\n\t\t\tirradiance *= PI;\r\n\r\n\t\t#endif\r\n\r\n\t\treturn irradiance;\r\n\r\n\t}\r\n\r\n#endif\r\n";
  7472. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP ) && defined( PHYSICAL )\r\n\r\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\r\n\r\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\r\n\r\n\t\t#ifdef ENVMAP_TYPE_CUBE\r\n\r\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\r\n\r\n\t\t\t// TODO: replace with properly filtered cubemaps and access the irradiance LOD level, be it the last LOD level\r\n\t\t\t// of a specular cubemap, or just the default level of a specially created irradiance cubemap.\r\n\r\n\t\t\t#ifdef TEXTURE_LOD_EXT\r\n\r\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\r\n\r\n\t\t\t#else\r\n\r\n\t\t\t\t// force the bias high to get the last LOD level as it is the most blurred.\r\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\r\n\r\n\t\t\t#endif\r\n\r\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\r\n\r\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\r\n\r\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\r\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, queryVec, 1.0 );\r\n\r\n\t\t#else\r\n\r\n\t\t\tvec4 envMapColor = vec4( 0.0 );\r\n\r\n\t\t#endif\r\n\r\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\r\n\r\n\t}\r\n\r\n\t// taken from here: http://casual-effects.blogspot.ca/2011/08/plausible-environment-lighting-in-two.html\r\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\r\n\r\n\t\t//float envMapWidth = pow( 2.0, maxMIPLevelScalar );\r\n\t\t//float desiredMIPLevel = log2( envMapWidth * sqrt( 3.0 ) ) - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\r\n\r\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\r\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\r\n\r\n\t\t// clamp to allowable LOD ranges.\r\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\r\n\r\n\t}\r\n\r\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\r\n\r\n\t\t#ifdef ENVMAP_MODE_REFLECTION\r\n\r\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\r\n\r\n\t\t#else\r\n\r\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\r\n\r\n\t\t#endif\r\n\r\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\r\n\r\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\r\n\r\n\t\t#ifdef ENVMAP_TYPE_CUBE\r\n\r\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\r\n\r\n\t\t\t#ifdef TEXTURE_LOD_EXT\r\n\r\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\r\n\r\n\t\t\t#else\r\n\r\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\r\n\r\n\t\t\t#endif\r\n\r\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\r\n\r\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\r\n\r\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\r\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent ));\r\n\r\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\r\n\r\n\t\t\tvec2 sampleUV;\r\n\t\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\r\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\t\t\t#ifdef TEXTURE_LOD_EXT\r\n\r\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\r\n\r\n\t\t\t#else\r\n\r\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\r\n\r\n\t\t\t#endif\r\n\r\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\r\n\r\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\r\n\r\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\r\n\r\n\t\t\t#ifdef TEXTURE_LOD_EXT\r\n\r\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\r\n\r\n\t\t\t#else\r\n\r\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\r\n\r\n\t\t\t#endif\r\n\r\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\r\n\r\n\t\t#endif\r\n\r\n\t\treturn envMapColor.rgb * envMapIntensity;\r\n\r\n\t}\r\n\r\n#endif\r\n";
  7473. var lights_phong_fragment = "BlinnPhongMaterial material;\r\nmaterial.diffuseColor = diffuseColor.rgb;\r\nmaterial.specularColor = specular;\r\nmaterial.specularShininess = shininess;\r\nmaterial.specularStrength = specularStrength;\r\n";
  7474. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\r\n\r\n#ifndef FLAT_SHADED\r\n\r\n\tvarying vec3 vNormal;\r\n\r\n#endif\r\n\r\n\r\nstruct BlinnPhongMaterial {\r\n\r\n\tvec3\tdiffuseColor;\r\n\tvec3\tspecularColor;\r\n\tfloat\tspecularShininess;\r\n\tfloat\tspecularStrength;\r\n\r\n};\r\n\r\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\r\n\r\n\t#ifdef TOON\r\n\r\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\r\n\r\n\t#else\r\n\r\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\r\n\t\tvec3 irradiance = dotNL * directLight.color;\r\n\r\n\t#endif\r\n\r\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\r\n\r\n\t\tirradiance *= PI; // punctual light\r\n\r\n\t#endif\r\n\r\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\r\n\r\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\r\n\r\n}\r\n\r\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\r\n\r\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\r\n\r\n}\r\n\r\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\r\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\r\n\r\n#define Material_LightProbeLOD( material )\t(0)\r\n";
  7475. var lights_physical_fragment = "PhysicalMaterial material;\r\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\r\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\r\n#ifdef STANDARD\r\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\r\n#else\r\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\r\n\tmaterial.clearCoat = saturate( clearCoat ); // Burley clearcoat model\r\n\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\r\n#endif\r\n";
  7476. var lights_physical_pars_fragment = "struct PhysicalMaterial {\r\n\r\n\tvec3\tdiffuseColor;\r\n\tfloat\tspecularRoughness;\r\n\tvec3\tspecularColor;\r\n\r\n\t#ifndef STANDARD\r\n\t\tfloat clearCoat;\r\n\t\tfloat clearCoatRoughness;\r\n\t#endif\r\n\r\n};\r\n\r\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\r\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\r\n\r\n// Clear coat directional hemishperical reflectance (this approximation should be improved)\r\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\r\n\r\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\r\n\r\n}\r\n\r\n#if NUM_RECT_AREA_LIGHTS > 0\r\n\r\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\r\n\r\n\t\tvec3 normal = geometry.normal;\r\n\t\tvec3 viewDir = geometry.viewDir;\r\n\t\tvec3 position = geometry.position;\r\n\t\tvec3 lightPos = rectAreaLight.position;\r\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\r\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\r\n\t\tvec3 lightColor = rectAreaLight.color;\r\n\t\tfloat roughness = material.specularRoughness;\r\n\r\n\t\tvec3 rectCoords[ 4 ];\r\n\t\trectCoords[ 0 ] = lightPos - halfWidth - halfHeight; // counterclockwise\r\n\t\trectCoords[ 1 ] = lightPos + halfWidth - halfHeight;\r\n\t\trectCoords[ 2 ] = lightPos + halfWidth + halfHeight;\r\n\t\trectCoords[ 3 ] = lightPos - halfWidth + halfHeight;\r\n\r\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\r\n\r\n\t\tvec4 t1 = texture2D( ltc_1, uv );\r\n\t\tvec4 t2 = texture2D( ltc_2, uv );\r\n\r\n\t\tmat3 mInv = mat3(\r\n\t\t\tvec3( t1.x, 0, t1.y ),\r\n\t\t\tvec3( 0, 1, 0 ),\r\n\t\t\tvec3( t1.z, 0, t1.w )\r\n\t\t);\r\n\r\n\t\t// LTC Fresnel Approximation by Stephen Hill\r\n\t\t// http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf\r\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\r\n\r\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\r\n\r\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\r\n\r\n\t}\r\n\r\n#endif\r\n\r\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\r\n\r\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\r\n\r\n\tvec3 irradiance = dotNL * directLight.color;\r\n\r\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\r\n\r\n\t\tirradiance *= PI; // punctual light\r\n\r\n\t#endif\r\n\r\n\t#ifndef STANDARD\r\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\r\n\t#else\r\n\t\tfloat clearCoatDHR = 0.0;\r\n\t#endif\r\n\r\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\r\n\r\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\r\n\r\n\t#ifndef STANDARD\r\n\r\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\r\n\r\n\t#endif\r\n\r\n}\r\n\r\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\r\n\r\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\r\n\r\n}\r\n\r\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\r\n\r\n\t#ifndef STANDARD\r\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\r\n\t\tfloat dotNL = dotNV;\r\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\r\n\t#else\r\n\t\tfloat clearCoatDHR = 0.0;\r\n\t#endif\r\n\r\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\r\n\r\n\t#ifndef STANDARD\r\n\r\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\r\n\r\n\t#endif\r\n\r\n}\r\n\r\n#define RE_Direct\t\t\t\tRE_Direct_Physical\r\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\r\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\r\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\r\n\r\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\r\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\r\n\r\n// ref: https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf\r\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\r\n\r\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\r\n\r\n}\r\n";
  7477. var lights_fragment_begin = "\r\n\r\nGeometricContext geometry;\r\n\r\ngeometry.position = - vViewPosition;\r\ngeometry.normal = normal;\r\ngeometry.viewDir = normalize( vViewPosition );\r\n\r\nIncidentLight directLight;\r\n\r\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\r\n\r\n\tPointLight pointLight;\r\n\r\n\t#pragma unroll_loop\r\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\r\n\r\n\t\tpointLight = pointLights[ i ];\r\n\r\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\r\n\r\n\t\t#ifdef USE_SHADOWMAP\r\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\r\n\t\t#endif\r\n\r\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\r\n\r\n\tSpotLight spotLight;\r\n\r\n\t#pragma unroll_loop\r\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\r\n\r\n\t\tspotLight = spotLights[ i ];\r\n\r\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\r\n\r\n\t\t#ifdef USE_SHADOWMAP\r\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\r\n\t\t#endif\r\n\r\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\r\n\r\n\tDirectionalLight directionalLight;\r\n\r\n\t#pragma unroll_loop\r\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\r\n\r\n\t\tdirectionalLight = directionalLights[ i ];\r\n\r\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\r\n\r\n\t\t#ifdef USE_SHADOWMAP\r\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\r\n\t\t#endif\r\n\r\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\r\n\r\n\tRectAreaLight rectAreaLight;\r\n\r\n\t#pragma unroll_loop\r\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\r\n\r\n\t\trectAreaLight = rectAreaLights[ i ];\r\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n#if defined( RE_IndirectDiffuse )\r\n\r\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\r\n\r\n\t#if ( NUM_HEMI_LIGHTS > 0 )\r\n\r\n\t\t#pragma unroll_loop\r\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\r\n\r\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\r\n\r\n\t\t}\r\n\r\n\t#endif\r\n\r\n#endif\r\n\r\n#if defined( RE_IndirectSpecular )\r\n\r\n\tvec3 radiance = vec3( 0.0 );\r\n\tvec3 clearCoatRadiance = vec3( 0.0 );\r\n\r\n#endif\r\n";
  7478. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\r\n\r\n\t#ifdef USE_LIGHTMAP\r\n\r\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\r\n\r\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\r\n\r\n\t\t\tlightMapIrradiance *= PI; // factor of PI should not be present; included here to prevent breakage\r\n\r\n\t\t#endif\r\n\r\n\t\tirradiance += lightMapIrradiance;\r\n\r\n\t#endif\r\n\r\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\r\n\r\n\t\tirradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\r\n\r\n\t#endif\r\n\r\n#endif\r\n\r\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\r\n\r\n\tradiance += getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), maxMipLevel );\r\n\r\n\t#ifndef STANDARD\r\n\t\tclearCoatRadiance += getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), maxMipLevel );\r\n\t#endif\r\n\r\n#endif\r\n";
  7479. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\r\n\r\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\r\n\r\n#endif\r\n\r\n#if defined( RE_IndirectSpecular )\r\n\r\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\r\n\r\n#endif\r\n";
  7480. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\r\n\r\n\tgl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;\r\n\r\n#endif";
  7481. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\r\n\r\n\tuniform float logDepthBufFC;\r\n\tvarying float vFragDepth;\r\n\r\n#endif\r\n";
  7482. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\r\n\r\n\t#ifdef USE_LOGDEPTHBUF_EXT\r\n\r\n\t\tvarying float vFragDepth;\r\n\r\n\t#else\r\n\r\n\t\tuniform float logDepthBufFC;\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  7483. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\r\n\r\n\t#ifdef USE_LOGDEPTHBUF_EXT\r\n\r\n\t\tvFragDepth = 1.0 + gl_Position.w;\r\n\r\n\t#else\r\n\r\n\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\r\n\r\n\t\tgl_Position.z *= gl_Position.w;\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  7484. var map_fragment = "#ifdef USE_MAP\r\n\r\n\tvec4 texelColor = texture2D( map, vUv );\r\n\r\n\ttexelColor = mapTexelToLinear( texelColor );\r\n\tdiffuseColor *= texelColor;\r\n\r\n#endif\r\n";
  7485. var map_pars_fragment = "#ifdef USE_MAP\r\n\r\n\tuniform sampler2D map;\r\n\r\n#endif\r\n";
  7486. var map_particle_fragment = "#ifdef USE_MAP\r\n\r\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\r\n\tvec4 mapTexel = texture2D( map, uv );\r\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\r\n\r\n#endif\r\n";
  7487. var map_particle_pars_fragment = "#ifdef USE_MAP\r\n\r\n\tuniform mat3 uvTransform;\r\n\tuniform sampler2D map;\r\n\r\n#endif\r\n";
  7488. var metalnessmap_fragment = "float metalnessFactor = metalness;\r\n\r\n#ifdef USE_METALNESSMAP\r\n\r\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\r\n\r\n\t// reads channel B, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\r\n\tmetalnessFactor *= texelMetalness.b;\r\n\r\n#endif\r\n";
  7489. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\r\n\r\n\tuniform sampler2D metalnessMap;\r\n\r\n#endif";
  7490. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\r\n\r\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\r\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\r\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\r\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\r\n\r\n#endif\r\n";
  7491. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\r\n\r\n\t#ifndef USE_MORPHNORMALS\r\n\r\n\tuniform float morphTargetInfluences[ 8 ];\r\n\r\n\t#else\r\n\r\n\tuniform float morphTargetInfluences[ 4 ];\r\n\r\n\t#endif\r\n\r\n#endif";
  7492. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\r\n\r\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\r\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\r\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\r\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\r\n\r\n\t#ifndef USE_MORPHNORMALS\r\n\r\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\r\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\r\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\r\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  7493. var normal_fragment_begin = "#ifdef FLAT_SHADED\r\n\r\n\t// Workaround for Adreno/Nexus5 not able able to do dFdx( vViewPosition ) ...\r\n\r\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\r\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\r\n\tvec3 normal = normalize( cross( fdx, fdy ) );\r\n\r\n#else\r\n\r\n\tvec3 normal = normalize( vNormal );\r\n\r\n\t#ifdef DOUBLE_SIDED\r\n\r\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  7494. var normal_fragment_maps = "#ifdef USE_NORMALMAP\r\n\r\n\t#ifdef OBJECTSPACE_NORMALMAP\r\n\r\n\t\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0; // overrides both flatShading and attribute normals\r\n\r\n\t\t#ifdef FLIP_SIDED\r\n\r\n\t\t\tnormal = - normal;\r\n\r\n\t\t#endif\r\n\r\n\t\t#ifdef DOUBLE_SIDED\r\n\r\n\t\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\r\n\r\n\t\t#endif\r\n\r\n\t\tnormal = normalize( normalMatrix * normal );\r\n\r\n\t#else // tangent-space normal map\r\n\r\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal );\r\n\r\n\t#endif\r\n\r\n#elif defined( USE_BUMPMAP )\r\n\r\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\r\n\r\n#endif\r\n";
  7495. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\r\n\r\n\tuniform sampler2D normalMap;\r\n\tuniform vec2 normalScale;\r\n\r\n\t#ifdef OBJECTSPACE_NORMALMAP\r\n\r\n\t\tuniform mat3 normalMatrix;\r\n\r\n\t#else\r\n\r\n\t\t// Per-Pixel Tangent Space Normal Mapping\r\n\t\t// http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\r\n\r\n\t\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\r\n\r\n\t\t\t// Workaround for Adreno 3XX dFd*( vec3 ) bug. See #9988\r\n\r\n\t\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\r\n\t\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\r\n\t\t\tvec2 st0 = dFdx( vUv.st );\r\n\t\t\tvec2 st1 = dFdy( vUv.st );\r\n\r\n\t\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s ); // we do not care about the magnitude\r\n\r\n\t\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\r\n\t\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\r\n\t\t\tvec3 N = normalize( surf_norm );\r\n\t\t\tmat3 tsn = mat3( S, T, N );\r\n\r\n\t\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\r\n\r\n\t\t\tmapN.xy *= normalScale;\r\n\t\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\r\n\r\n\t\t\treturn normalize( tsn * mapN );\r\n\r\n\t\t}\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  7496. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\r\n\treturn normalize( normal ) * 0.5 + 0.5;\r\n}\r\n\r\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\r\n\treturn 2.0 * rgb.xyz - 1.0;\r\n}\r\n\r\nconst float PackUpscale = 256. / 255.; // fraction -> 0..1 (including 1)\r\nconst float UnpackDownscale = 255. / 256.; // 0..1 -> fraction (excluding 1)\r\n\r\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\r\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\r\n\r\nconst float ShiftRight8 = 1. / 256.;\r\n\r\nvec4 packDepthToRGBA( const in float v ) {\r\n\tvec4 r = vec4( fract( v * PackFactors ), v );\r\n\tr.yzw -= r.xyz * ShiftRight8; // tidy overflow\r\n\treturn r * PackUpscale;\r\n}\r\n\r\nfloat unpackRGBAToDepth( const in vec4 v ) {\r\n\treturn dot( v, UnpackFactors );\r\n}\r\n\r\n// NOTE: viewZ/eyeZ is < 0 when in front of the camera per OpenGL conventions\r\n\r\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\r\n\treturn ( viewZ + near ) / ( near - far );\r\n}\r\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\r\n\treturn linearClipZ * ( near - far ) - near;\r\n}\r\n\r\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\r\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\r\n}\r\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\r\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\r\n}\r\n";
  7497. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\r\n\r\n\t// Get get normal blending with premultipled, use with CustomBlending, OneFactor, OneMinusSrcAlphaFactor, AddEquation.\r\n\tgl_FragColor.rgb *= gl_FragColor.a;\r\n\r\n#endif\r\n";
  7498. var project_vertex = "vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\r\n\r\ngl_Position = projectionMatrix * mvPosition;\r\n";
  7499. var dithering_fragment = "#if defined( DITHERING )\r\n\r\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\r\n\r\n#endif\r\n";
  7500. var dithering_pars_fragment = "#if defined( DITHERING )\r\n\r\n\t// based on https://www.shadertoy.com/view/MslGR8\r\n\tvec3 dithering( vec3 color ) {\r\n\t\t//Calculate grid position\r\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\r\n\r\n\t\t//Shift the individual colors differently, thus making it even harder to see the dithering pattern\r\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\r\n\r\n\t\t//modify shift acording to grid position.\r\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\r\n\r\n\t\t//shift the color by dither_shift\r\n\t\treturn color + dither_shift_RGB;\r\n\t}\r\n\r\n#endif\r\n";
  7501. var roughnessmap_fragment = "float roughnessFactor = roughness;\r\n\r\n#ifdef USE_ROUGHNESSMAP\r\n\r\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\r\n\r\n\t// reads channel G, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\r\n\troughnessFactor *= texelRoughness.g;\r\n\r\n#endif\r\n";
  7502. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\r\n\r\n\tuniform sampler2D roughnessMap;\r\n\r\n#endif";
  7503. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\r\n\r\n\t#if NUM_DIR_LIGHTS > 0\r\n\r\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\r\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\r\n\r\n\t#endif\r\n\r\n\t#if NUM_SPOT_LIGHTS > 0\r\n\r\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\r\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\r\n\r\n\t#endif\r\n\r\n\t#if NUM_POINT_LIGHTS > 0\r\n\r\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\r\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\r\n\r\n\t#endif\r\n\r\n\r\n\r\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\r\n\r\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\r\n\r\n\t}\r\n\r\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\r\n\r\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\r\n\r\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\r\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\r\n\r\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\r\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\r\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\r\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\r\n\r\n\t\tvec2 f = fract( uv * size + 0.5 );\r\n\r\n\t\tfloat a = mix( lb, lt, f.y );\r\n\t\tfloat b = mix( rb, rt, f.y );\r\n\t\tfloat c = mix( a, b, f.x );\r\n\r\n\t\treturn c;\r\n\r\n\t}\r\n\r\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\r\n\r\n\t\tfloat shadow = 1.0;\r\n\r\n\t\tshadowCoord.xyz /= shadowCoord.w;\r\n\t\tshadowCoord.z += shadowBias;\r\n\r\n\t\t// if ( something && something ) breaks ATI OpenGL shader compiler\r\n\t\t// if ( all( something, something ) ) using this instead\r\n\r\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\r\n\t\tbool inFrustum = all( inFrustumVec );\r\n\r\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\r\n\r\n\t\tbool frustumTest = all( frustumTestVec );\r\n\r\n\t\tif ( frustumTest ) {\r\n\r\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\r\n\r\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\r\n\r\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\r\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\r\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\r\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\r\n\r\n\t\t\tshadow = (\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\r\n\t\t\t) * ( 1.0 / 9.0 );\r\n\r\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\r\n\r\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\r\n\r\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\r\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\r\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\r\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\r\n\r\n\t\t\tshadow = (\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\r\n\t\t\t) * ( 1.0 / 9.0 );\r\n\r\n\t\t#else // no percentage-closer filtering:\r\n\r\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\r\n\r\n\t\t#endif\r\n\r\n\t\t}\r\n\r\n\t\treturn shadow;\r\n\r\n\t}\r\n\r\n\t// cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D\r\n\t// vector suitable for 2D texture mapping. This code uses the following layout for the\r\n\t// 2D texture:\r\n\t//\r\n\t// xzXZ\r\n\t// y Y\r\n\t//\r\n\t// Y - Positive y direction\r\n\t// y - Negative y direction\r\n\t// X - Positive x direction\r\n\t// x - Negative x direction\r\n\t// Z - Positive z direction\r\n\t// z - Negative z direction\r\n\t//\r\n\t// Source and test bed:\r\n\t// https://gist.github.com/tschw/da10c43c467ce8afd0c4\r\n\r\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\r\n\r\n\t\t// Number of texels to avoid at the edge of each square\r\n\r\n\t\tvec3 absV = abs( v );\r\n\r\n\t\t// Intersect unit cube\r\n\r\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\r\n\t\tabsV *= scaleToCube;\r\n\r\n\t\t// Apply scale to avoid seams\r\n\r\n\t\t// two texels less per square (one texel will do for NEAREST)\r\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\r\n\r\n\t\t// Unwrap\r\n\r\n\t\t// space: -1 ... 1 range for each square\r\n\t\t//\r\n\t\t// #X##\t\tdim := ( 4 , 2 )\r\n\t\t// # #\t\tcenter := ( 1 , 1 )\r\n\r\n\t\tvec2 planar = v.xy;\r\n\r\n\t\tfloat almostATexel = 1.5 * texelSizeY;\r\n\t\tfloat almostOne = 1.0 - almostATexel;\r\n\r\n\t\tif ( absV.z >= almostOne ) {\r\n\r\n\t\t\tif ( v.z > 0.0 )\r\n\t\t\t\tplanar.x = 4.0 - v.x;\r\n\r\n\t\t} else if ( absV.x >= almostOne ) {\r\n\r\n\t\t\tfloat signX = sign( v.x );\r\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\r\n\r\n\t\t} else if ( absV.y >= almostOne ) {\r\n\r\n\t\t\tfloat signY = sign( v.y );\r\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\r\n\t\t\tplanar.y = v.z * signY - 2.0;\r\n\r\n\t\t}\r\n\r\n\t\t// Transform to UV space\r\n\r\n\t\t// scale := 0.5 / dim\r\n\t\t// translate := ( center + 0.5 ) / dim\r\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\r\n\r\n\t}\r\n\r\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\r\n\r\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\r\n\r\n\t\t// for point lights, the uniform @vShadowCoord is re-purposed to hold\r\n\t\t// the vector from the light to the world-space position of the fragment.\r\n\t\tvec3 lightToPosition = shadowCoord.xyz;\r\n\r\n\t\t// dp = normalized distance from light to fragment position\r\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); // need to clamp?\r\n\t\tdp += shadowBias;\r\n\r\n\t\t// bd3D = base direction 3D\r\n\t\tvec3 bd3D = normalize( lightToPosition );\r\n\r\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\r\n\r\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\r\n\r\n\t\t\treturn (\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\r\n\t\t\t) * ( 1.0 / 9.0 );\r\n\r\n\t\t#else // no percentage-closer filtering\r\n\r\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\r\n\r\n\t\t#endif\r\n\r\n\t}\r\n\r\n#endif\r\n";
  7504. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\r\n\r\n\t#if NUM_DIR_LIGHTS > 0\r\n\r\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\r\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\r\n\r\n\t#endif\r\n\r\n\t#if NUM_SPOT_LIGHTS > 0\r\n\r\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\r\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\r\n\r\n\t#endif\r\n\r\n\t#if NUM_POINT_LIGHTS > 0\r\n\r\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\r\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\r\n\r\n\t#endif\r\n\r\n\r\n\r\n#endif\r\n";
  7505. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\r\n\r\n\t#if NUM_DIR_LIGHTS > 0\r\n\r\n\t#pragma unroll_loop\r\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\r\n\r\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\r\n\r\n\t}\r\n\r\n\t#endif\r\n\r\n\t#if NUM_SPOT_LIGHTS > 0\r\n\r\n\t#pragma unroll_loop\r\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\r\n\r\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\r\n\r\n\t}\r\n\r\n\t#endif\r\n\r\n\t#if NUM_POINT_LIGHTS > 0\r\n\r\n\t#pragma unroll_loop\r\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\r\n\r\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\r\n\r\n\t}\r\n\r\n\t#endif\r\n\r\n\r\n\r\n#endif\r\n";
  7506. var shadowmask_pars_fragment = "float getShadowMask() {\r\n\r\n\tfloat shadow = 1.0;\r\n\r\n\t#ifdef USE_SHADOWMAP\r\n\r\n\t#if NUM_DIR_LIGHTS > 0\r\n\r\n\tDirectionalLight directionalLight;\r\n\r\n\t#pragma unroll_loop\r\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\r\n\r\n\t\tdirectionalLight = directionalLights[ i ];\r\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\r\n\r\n\t}\r\n\r\n\t#endif\r\n\r\n\t#if NUM_SPOT_LIGHTS > 0\r\n\r\n\tSpotLight spotLight;\r\n\r\n\t#pragma unroll_loop\r\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\r\n\r\n\t\tspotLight = spotLights[ i ];\r\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\r\n\r\n\t}\r\n\r\n\t#endif\r\n\r\n\t#if NUM_POINT_LIGHTS > 0\r\n\r\n\tPointLight pointLight;\r\n\r\n\t#pragma unroll_loop\r\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\r\n\r\n\t\tpointLight = pointLights[ i ];\r\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\r\n\r\n\t}\r\n\r\n\t#endif\r\n\r\n\r\n\r\n\t#endif\r\n\r\n\treturn shadow;\r\n\r\n}\r\n";
  7507. var skinbase_vertex = "#ifdef USE_SKINNING\r\n\r\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\r\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\r\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\r\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\r\n\r\n#endif";
  7508. var skinning_pars_vertex = "#ifdef USE_SKINNING\r\n\r\n\tuniform mat4 bindMatrix;\r\n\tuniform mat4 bindMatrixInverse;\r\n\r\n\t#ifdef BONE_TEXTURE\r\n\r\n\t\tuniform sampler2D boneTexture;\r\n\t\tuniform int boneTextureSize;\r\n\r\n\t\tmat4 getBoneMatrix( const in float i ) {\r\n\r\n\t\t\tfloat j = i * 4.0;\r\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\r\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\r\n\r\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\r\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\r\n\r\n\t\t\ty = dy * ( y + 0.5 );\r\n\r\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\r\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\r\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\r\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\r\n\r\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\r\n\r\n\t\t\treturn bone;\r\n\r\n\t\t}\r\n\r\n\t#else\r\n\r\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\r\n\r\n\t\tmat4 getBoneMatrix( const in float i ) {\r\n\r\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\r\n\t\t\treturn bone;\r\n\r\n\t\t}\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  7509. var skinning_vertex = "#ifdef USE_SKINNING\r\n\r\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\r\n\r\n\tvec4 skinned = vec4( 0.0 );\r\n\tskinned += boneMatX * skinVertex * skinWeight.x;\r\n\tskinned += boneMatY * skinVertex * skinWeight.y;\r\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\r\n\tskinned += boneMatW * skinVertex * skinWeight.w;\r\n\r\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\r\n\r\n#endif\r\n";
  7510. var skinnormal_vertex = "#ifdef USE_SKINNING\r\n\r\n\tmat4 skinMatrix = mat4( 0.0 );\r\n\tskinMatrix += skinWeight.x * boneMatX;\r\n\tskinMatrix += skinWeight.y * boneMatY;\r\n\tskinMatrix += skinWeight.z * boneMatZ;\r\n\tskinMatrix += skinWeight.w * boneMatW;\r\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\r\n\r\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\r\n\r\n#endif\r\n";
  7511. var specularmap_fragment = "float specularStrength;\r\n\r\n#ifdef USE_SPECULARMAP\r\n\r\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\r\n\tspecularStrength = texelSpecular.r;\r\n\r\n#else\r\n\r\n\tspecularStrength = 1.0;\r\n\r\n#endif";
  7512. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\r\n\r\n\tuniform sampler2D specularMap;\r\n\r\n#endif";
  7513. var tonemapping_fragment = "#if defined( TONE_MAPPING )\r\n\r\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\r\n\r\n#endif\r\n";
  7514. var tonemapping_pars_fragment = "#ifndef saturate\r\n\t#define saturate(a) clamp( a, 0.0, 1.0 )\r\n#endif\r\n\r\nuniform float toneMappingExposure;\r\nuniform float toneMappingWhitePoint;\r\n\r\n// exposure only\r\nvec3 LinearToneMapping( vec3 color ) {\r\n\r\n\treturn toneMappingExposure * color;\r\n\r\n}\r\n\r\n// source: https://www.cs.utah.edu/~reinhard/cdrom/\r\nvec3 ReinhardToneMapping( vec3 color ) {\r\n\r\n\tcolor *= toneMappingExposure;\r\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\r\n\r\n}\r\n\r\n// source: http://filmicgames.com/archives/75\r\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\r\nvec3 Uncharted2ToneMapping( vec3 color ) {\r\n\r\n\t// John Hable's filmic operator from Uncharted 2 video game\r\n\tcolor *= toneMappingExposure;\r\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\r\n\r\n}\r\n\r\n// source: http://filmicgames.com/archives/75\r\nvec3 OptimizedCineonToneMapping( vec3 color ) {\r\n\r\n\t// optimized filmic operator by Jim Hejl and Richard Burgess-Dawson\r\n\tcolor *= toneMappingExposure;\r\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\r\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\r\n\r\n}\r\n";
  7515. var uv_pars_fragment = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\r\n\r\n\tvarying vec2 vUv;\r\n\r\n#endif";
  7516. var uv_pars_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\r\n\r\n\tvarying vec2 vUv;\r\n\tuniform mat3 uvTransform;\r\n\r\n#endif\r\n";
  7517. var uv_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\r\n\r\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\r\n\r\n#endif";
  7518. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\r\n\r\n\tvarying vec2 vUv2;\r\n\r\n#endif";
  7519. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\r\n\r\n\tattribute vec2 uv2;\r\n\tvarying vec2 vUv2;\r\n\r\n#endif";
  7520. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\r\n\r\n\tvUv2 = uv2;\r\n\r\n#endif";
  7521. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\r\n\r\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\r\n\r\n#endif\r\n";
  7522. var background_frag = "uniform sampler2D t2D;\r\n\r\nvarying vec2 vUv;\r\n\r\nvoid main() {\r\n\r\n\tvec4 texColor = texture2D( t2D, vUv );\r\n\r\n\tgl_FragColor = mapTexelToLinear( texColor );\r\n\r\n\t#include <tonemapping_fragment>\r\n\t#include <encodings_fragment>\r\n\r\n}\r\n";
  7523. var background_vert = "varying vec2 vUv;\r\nuniform mat3 uvTransform;\r\n\r\nvoid main() {\r\n\r\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\r\n\r\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\r\n\r\n}\r\n";
  7524. var cube_frag = "uniform samplerCube tCube;\r\nuniform float tFlip;\r\nuniform float opacity;\r\n\r\nvarying vec3 vWorldDirection;\r\n\r\nvoid main() {\r\n\r\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\r\n\r\n\tgl_FragColor = mapTexelToLinear( texColor );\r\n\tgl_FragColor.a *= opacity;\r\n\r\n\t#include <tonemapping_fragment>\r\n\t#include <encodings_fragment>\r\n\r\n}\r\n";
  7525. var cube_vert = "varying vec3 vWorldDirection;\r\n\r\n#include <common>\r\n\r\nvoid main() {\r\n\r\n\tvWorldDirection = transformDirection( position, modelMatrix );\r\n\r\n\t#include <begin_vertex>\r\n\t#include <project_vertex>\r\n\r\n\tgl_Position.z = gl_Position.w; // set z to camera.far\r\n\r\n}\r\n";
  7526. var depth_frag = "#if DEPTH_PACKING == 3200\r\n\r\n\tuniform float opacity;\r\n\r\n#endif\r\n\r\n#include <common>\r\n#include <packing>\r\n#include <uv_pars_fragment>\r\n#include <map_pars_fragment>\r\n#include <alphamap_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tvec4 diffuseColor = vec4( 1.0 );\r\n\r\n\t#if DEPTH_PACKING == 3200\r\n\r\n\t\tdiffuseColor.a = opacity;\r\n\r\n\t#endif\r\n\r\n\t#include <map_fragment>\r\n\t#include <alphamap_fragment>\r\n\t#include <alphatest_fragment>\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\r\n\t#if DEPTH_PACKING == 3200\r\n\r\n\t\tgl_FragColor = vec4( vec3( 1.0 - gl_FragCoord.z ), opacity );\r\n\r\n\t#elif DEPTH_PACKING == 3201\r\n\r\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\r\n\r\n\t#endif\r\n\r\n}\r\n";
  7527. var depth_vert = "#include <common>\r\n#include <uv_pars_vertex>\r\n#include <displacementmap_pars_vertex>\r\n#include <morphtarget_pars_vertex>\r\n#include <skinning_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <uv_vertex>\r\n\r\n\t#include <skinbase_vertex>\r\n\r\n\t#ifdef USE_DISPLACEMENTMAP\r\n\r\n\t\t#include <beginnormal_vertex>\r\n\t\t#include <morphnormal_vertex>\r\n\t\t#include <skinnormal_vertex>\r\n\r\n\t#endif\r\n\r\n\t#include <begin_vertex>\r\n\t#include <morphtarget_vertex>\r\n\t#include <skinning_vertex>\r\n\t#include <displacementmap_vertex>\r\n\t#include <project_vertex>\r\n\t#include <logdepthbuf_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\r\n}\r\n";
  7528. var distanceRGBA_frag = "#define DISTANCE\r\n\r\nuniform vec3 referencePosition;\r\nuniform float nearDistance;\r\nuniform float farDistance;\r\nvarying vec3 vWorldPosition;\r\n\r\n#include <common>\r\n#include <packing>\r\n#include <uv_pars_fragment>\r\n#include <map_pars_fragment>\r\n#include <alphamap_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main () {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tvec4 diffuseColor = vec4( 1.0 );\r\n\r\n\t#include <map_fragment>\r\n\t#include <alphamap_fragment>\r\n\t#include <alphatest_fragment>\r\n\r\n\tfloat dist = length( vWorldPosition - referencePosition );\r\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\r\n\tdist = saturate( dist ); // clamp to [ 0, 1 ]\r\n\r\n\tgl_FragColor = packDepthToRGBA( dist );\r\n\r\n}\r\n";
  7529. var distanceRGBA_vert = "#define DISTANCE\r\n\r\nvarying vec3 vWorldPosition;\r\n\r\n#include <common>\r\n#include <uv_pars_vertex>\r\n#include <displacementmap_pars_vertex>\r\n#include <morphtarget_pars_vertex>\r\n#include <skinning_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <uv_vertex>\r\n\r\n\t#include <skinbase_vertex>\r\n\r\n\t#ifdef USE_DISPLACEMENTMAP\r\n\r\n\t\t#include <beginnormal_vertex>\r\n\t\t#include <morphnormal_vertex>\r\n\t\t#include <skinnormal_vertex>\r\n\r\n\t#endif\r\n\r\n\t#include <begin_vertex>\r\n\t#include <morphtarget_vertex>\r\n\t#include <skinning_vertex>\r\n\t#include <displacementmap_vertex>\r\n\t#include <project_vertex>\r\n\t#include <worldpos_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\r\n\tvWorldPosition = worldPosition.xyz;\r\n\r\n}\r\n";
  7530. var equirect_frag = "uniform sampler2D tEquirect;\r\n\r\nvarying vec3 vWorldDirection;\r\n\r\n#include <common>\r\n\r\nvoid main() {\r\n\r\n\tvec3 direction = normalize( vWorldDirection );\r\n\r\n\tvec2 sampleUV;\r\n\r\n\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\r\n\r\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\r\n\r\n}\r\n";
  7531. var equirect_vert = "varying vec3 vWorldDirection;\r\n\r\n#include <common>\r\n\r\nvoid main() {\r\n\r\n\tvWorldDirection = transformDirection( position, modelMatrix );\r\n\r\n\t#include <begin_vertex>\r\n\t#include <project_vertex>\r\n\r\n}\r\n";
  7532. var linedashed_frag = "uniform vec3 diffuse;\r\nuniform float opacity;\r\n\r\nuniform float dashSize;\r\nuniform float totalSize;\r\n\r\nvarying float vLineDistance;\r\n\r\n#include <common>\r\n#include <color_pars_fragment>\r\n#include <fog_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\r\n\r\n\t\tdiscard;\r\n\r\n\t}\r\n\r\n\tvec3 outgoingLight = vec3( 0.0 );\r\n\tvec4 diffuseColor = vec4( diffuse, opacity );\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\t#include <color_fragment>\r\n\r\n\toutgoingLight = diffuseColor.rgb; // simple shader\r\n\r\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\r\n\r\n\t#include <premultiplied_alpha_fragment>\r\n\t#include <tonemapping_fragment>\r\n\t#include <encodings_fragment>\r\n\t#include <fog_fragment>\r\n\r\n}\r\n";
  7533. var linedashed_vert = "uniform float scale;\r\nattribute float lineDistance;\r\n\r\nvarying float vLineDistance;\r\n\r\n#include <common>\r\n#include <color_pars_vertex>\r\n#include <fog_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <color_vertex>\r\n\r\n\tvLineDistance = scale * lineDistance;\r\n\r\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\r\n\tgl_Position = projectionMatrix * mvPosition;\r\n\r\n\t#include <logdepthbuf_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\t#include <fog_vertex>\r\n\r\n}\r\n";
  7534. var meshbasic_frag = "uniform vec3 diffuse;\r\nuniform float opacity;\r\n\r\n#ifndef FLAT_SHADED\r\n\r\n\tvarying vec3 vNormal;\r\n\r\n#endif\r\n\r\n#include <common>\r\n#include <color_pars_fragment>\r\n#include <uv_pars_fragment>\r\n#include <uv2_pars_fragment>\r\n#include <map_pars_fragment>\r\n#include <alphamap_pars_fragment>\r\n#include <aomap_pars_fragment>\r\n#include <lightmap_pars_fragment>\r\n#include <envmap_pars_fragment>\r\n#include <fog_pars_fragment>\r\n#include <specularmap_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tvec4 diffuseColor = vec4( diffuse, opacity );\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\t#include <map_fragment>\r\n\t#include <color_fragment>\r\n\t#include <alphamap_fragment>\r\n\t#include <alphatest_fragment>\r\n\t#include <specularmap_fragment>\r\n\r\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\r\n\r\n\t// accumulation (baked indirect lighting only)\r\n\t#ifdef USE_LIGHTMAP\r\n\r\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\r\n\r\n\t#else\r\n\r\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\r\n\r\n\t#endif\r\n\r\n\t// modulation\r\n\t#include <aomap_fragment>\r\n\r\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\r\n\r\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\r\n\r\n\t#include <envmap_fragment>\r\n\r\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\r\n\r\n\t#include <premultiplied_alpha_fragment>\r\n\t#include <tonemapping_fragment>\r\n\t#include <encodings_fragment>\r\n\t#include <fog_fragment>\r\n\r\n}\r\n";
  7535. var meshbasic_vert = "#include <common>\r\n#include <uv_pars_vertex>\r\n#include <uv2_pars_vertex>\r\n#include <envmap_pars_vertex>\r\n#include <color_pars_vertex>\r\n#include <fog_pars_vertex>\r\n#include <morphtarget_pars_vertex>\r\n#include <skinning_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <uv_vertex>\r\n\t#include <uv2_vertex>\r\n\t#include <color_vertex>\r\n\t#include <skinbase_vertex>\r\n\r\n\t#ifdef USE_ENVMAP\r\n\r\n\t#include <beginnormal_vertex>\r\n\t#include <morphnormal_vertex>\r\n\t#include <skinnormal_vertex>\r\n\t#include <defaultnormal_vertex>\r\n\r\n\t#endif\r\n\r\n\t#include <begin_vertex>\r\n\t#include <morphtarget_vertex>\r\n\t#include <skinning_vertex>\r\n\t#include <project_vertex>\r\n\t#include <logdepthbuf_vertex>\r\n\r\n\t#include <worldpos_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\t#include <envmap_vertex>\r\n\t#include <fog_vertex>\r\n\r\n}\r\n";
  7536. var meshlambert_frag = "uniform vec3 diffuse;\r\nuniform vec3 emissive;\r\nuniform float opacity;\r\n\r\nvarying vec3 vLightFront;\r\n\r\n#ifdef DOUBLE_SIDED\r\n\r\n\tvarying vec3 vLightBack;\r\n\r\n#endif\r\n\r\n#include <common>\r\n#include <packing>\r\n#include <dithering_pars_fragment>\r\n#include <color_pars_fragment>\r\n#include <uv_pars_fragment>\r\n#include <uv2_pars_fragment>\r\n#include <map_pars_fragment>\r\n#include <alphamap_pars_fragment>\r\n#include <aomap_pars_fragment>\r\n#include <lightmap_pars_fragment>\r\n#include <emissivemap_pars_fragment>\r\n#include <envmap_pars_fragment>\r\n#include <bsdfs>\r\n#include <lights_pars_begin>\r\n#include <fog_pars_fragment>\r\n#include <shadowmap_pars_fragment>\r\n#include <shadowmask_pars_fragment>\r\n#include <specularmap_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tvec4 diffuseColor = vec4( diffuse, opacity );\r\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\r\n\tvec3 totalEmissiveRadiance = emissive;\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\t#include <map_fragment>\r\n\t#include <color_fragment>\r\n\t#include <alphamap_fragment>\r\n\t#include <alphatest_fragment>\r\n\t#include <specularmap_fragment>\r\n\t#include <emissivemap_fragment>\r\n\r\n\t// accumulation\r\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\r\n\r\n\t#include <lightmap_fragment>\r\n\r\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\r\n\r\n\t#ifdef DOUBLE_SIDED\r\n\r\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\r\n\r\n\t#else\r\n\r\n\t\treflectedLight.directDiffuse = vLightFront;\r\n\r\n\t#endif\r\n\r\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\r\n\r\n\t// modulation\r\n\t#include <aomap_fragment>\r\n\r\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\r\n\r\n\t#include <envmap_fragment>\r\n\r\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\r\n\r\n\t#include <tonemapping_fragment>\r\n\t#include <encodings_fragment>\r\n\t#include <fog_fragment>\r\n\t#include <premultiplied_alpha_fragment>\r\n\t#include <dithering_fragment>\r\n\r\n}\r\n";
  7537. var meshlambert_vert = "#define LAMBERT\r\n\r\nvarying vec3 vLightFront;\r\n\r\n#ifdef DOUBLE_SIDED\r\n\r\n\tvarying vec3 vLightBack;\r\n\r\n#endif\r\n\r\n#include <common>\r\n#include <uv_pars_vertex>\r\n#include <uv2_pars_vertex>\r\n#include <envmap_pars_vertex>\r\n#include <bsdfs>\r\n#include <lights_pars_begin>\r\n#include <color_pars_vertex>\r\n#include <fog_pars_vertex>\r\n#include <morphtarget_pars_vertex>\r\n#include <skinning_pars_vertex>\r\n#include <shadowmap_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <uv_vertex>\r\n\t#include <uv2_vertex>\r\n\t#include <color_vertex>\r\n\r\n\t#include <beginnormal_vertex>\r\n\t#include <morphnormal_vertex>\r\n\t#include <skinbase_vertex>\r\n\t#include <skinnormal_vertex>\r\n\t#include <defaultnormal_vertex>\r\n\r\n\t#include <begin_vertex>\r\n\t#include <morphtarget_vertex>\r\n\t#include <skinning_vertex>\r\n\t#include <project_vertex>\r\n\t#include <logdepthbuf_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\r\n\t#include <worldpos_vertex>\r\n\t#include <envmap_vertex>\r\n\t#include <lights_lambert_vertex>\r\n\t#include <shadowmap_vertex>\r\n\t#include <fog_vertex>\r\n\r\n}\r\n";
  7538. var meshmatcap_frag = "#define MATCAP\r\n\r\nuniform vec3 diffuse;\r\nuniform float opacity;\r\nuniform sampler2D matcap;\r\n\r\nvarying vec3 vViewPosition;\r\n\r\n#ifndef FLAT_SHADED\r\n\r\n\tvarying vec3 vNormal;\r\n\r\n#endif\r\n\r\n#include <common>\r\n#include <uv_pars_fragment>\r\n#include <map_pars_fragment>\r\n#include <alphamap_pars_fragment>\r\n\r\n#include <fog_pars_fragment>\r\n#include <bumpmap_pars_fragment>\r\n#include <normalmap_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tvec4 diffuseColor = vec4( diffuse, opacity );\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\t#include <map_fragment>\r\n\t#include <alphamap_fragment>\r\n\t#include <alphatest_fragment>\r\n\t#include <normal_fragment_begin>\r\n\t#include <normal_fragment_maps>\r\n\r\n\tvec3 viewDir = normalize( vViewPosition );\r\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\r\n\tvec3 y = cross( viewDir, x );\r\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; // 0.495 to remove artifacts caused by undersized matcap disks\r\n\r\n\tvec4 matcapColor = texture2D( matcap, uv );\r\n\r\n\tmatcapColor = matcapTexelToLinear( matcapColor );\r\n\r\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\r\n\r\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\r\n\r\n\t#include <premultiplied_alpha_fragment>\r\n\t#include <tonemapping_fragment>\r\n\t#include <encodings_fragment>\r\n\t#include <fog_fragment>\r\n\r\n}\r\n";
  7539. var meshmatcap_vert = "#define MATCAP\r\n\r\nvarying vec3 vViewPosition;\r\n\r\n#ifndef FLAT_SHADED\r\n\r\n\tvarying vec3 vNormal;\r\n\r\n#endif\r\n\r\n#include <common>\r\n#include <uv_pars_vertex>\r\n#include <displacementmap_pars_vertex>\r\n#include <fog_pars_vertex>\r\n#include <morphtarget_pars_vertex>\r\n#include <skinning_pars_vertex>\r\n\r\n#include <logdepthbuf_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <uv_vertex>\r\n\r\n\t#include <beginnormal_vertex>\r\n\t#include <morphnormal_vertex>\r\n\t#include <skinbase_vertex>\r\n\t#include <skinnormal_vertex>\r\n\t#include <defaultnormal_vertex>\r\n\r\n\t#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\r\n\r\n\t\tvNormal = normalize( transformedNormal );\r\n\r\n\t#endif\r\n\r\n\t#include <begin_vertex>\r\n\t#include <morphtarget_vertex>\r\n\t#include <skinning_vertex>\r\n\t#include <displacementmap_vertex>\r\n\t#include <project_vertex>\r\n\r\n\t#include <logdepthbuf_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\t#include <fog_vertex>\r\n\r\n\tvViewPosition = - mvPosition.xyz;\r\n\r\n}\r\n";
  7540. var meshphong_frag = "#define PHONG\r\n\r\nuniform vec3 diffuse;\r\nuniform vec3 emissive;\r\nuniform vec3 specular;\r\nuniform float shininess;\r\nuniform float opacity;\r\n\r\n#include <common>\r\n#include <packing>\r\n#include <dithering_pars_fragment>\r\n#include <color_pars_fragment>\r\n#include <uv_pars_fragment>\r\n#include <uv2_pars_fragment>\r\n#include <map_pars_fragment>\r\n#include <alphamap_pars_fragment>\r\n#include <aomap_pars_fragment>\r\n#include <lightmap_pars_fragment>\r\n#include <emissivemap_pars_fragment>\r\n#include <envmap_pars_fragment>\r\n#include <gradientmap_pars_fragment>\r\n#include <fog_pars_fragment>\r\n#include <bsdfs>\r\n#include <lights_pars_begin>\r\n#include <lights_phong_pars_fragment>\r\n#include <shadowmap_pars_fragment>\r\n#include <bumpmap_pars_fragment>\r\n#include <normalmap_pars_fragment>\r\n#include <specularmap_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tvec4 diffuseColor = vec4( diffuse, opacity );\r\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\r\n\tvec3 totalEmissiveRadiance = emissive;\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\t#include <map_fragment>\r\n\t#include <color_fragment>\r\n\t#include <alphamap_fragment>\r\n\t#include <alphatest_fragment>\r\n\t#include <specularmap_fragment>\r\n\t#include <normal_fragment_begin>\r\n\t#include <normal_fragment_maps>\r\n\t#include <emissivemap_fragment>\r\n\r\n\t// accumulation\r\n\t#include <lights_phong_fragment>\r\n\t#include <lights_fragment_begin>\r\n\t#include <lights_fragment_maps>\r\n\t#include <lights_fragment_end>\r\n\r\n\t// modulation\r\n\t#include <aomap_fragment>\r\n\r\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\r\n\r\n\t#include <envmap_fragment>\r\n\r\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\r\n\r\n\t#include <tonemapping_fragment>\r\n\t#include <encodings_fragment>\r\n\t#include <fog_fragment>\r\n\t#include <premultiplied_alpha_fragment>\r\n\t#include <dithering_fragment>\r\n\r\n}\r\n";
  7541. var meshphong_vert = "#define PHONG\r\n\r\nvarying vec3 vViewPosition;\r\n\r\n#ifndef FLAT_SHADED\r\n\r\n\tvarying vec3 vNormal;\r\n\r\n#endif\r\n\r\n#include <common>\r\n#include <uv_pars_vertex>\r\n#include <uv2_pars_vertex>\r\n#include <displacementmap_pars_vertex>\r\n#include <envmap_pars_vertex>\r\n#include <color_pars_vertex>\r\n#include <fog_pars_vertex>\r\n#include <morphtarget_pars_vertex>\r\n#include <skinning_pars_vertex>\r\n#include <shadowmap_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <uv_vertex>\r\n\t#include <uv2_vertex>\r\n\t#include <color_vertex>\r\n\r\n\t#include <beginnormal_vertex>\r\n\t#include <morphnormal_vertex>\r\n\t#include <skinbase_vertex>\r\n\t#include <skinnormal_vertex>\r\n\t#include <defaultnormal_vertex>\r\n\r\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\r\n\r\n\tvNormal = normalize( transformedNormal );\r\n\r\n#endif\r\n\r\n\t#include <begin_vertex>\r\n\t#include <morphtarget_vertex>\r\n\t#include <skinning_vertex>\r\n\t#include <displacementmap_vertex>\r\n\t#include <project_vertex>\r\n\t#include <logdepthbuf_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\r\n\tvViewPosition = - mvPosition.xyz;\r\n\r\n\t#include <worldpos_vertex>\r\n\t#include <envmap_vertex>\r\n\t#include <shadowmap_vertex>\r\n\t#include <fog_vertex>\r\n\r\n}\r\n";
  7542. var meshphysical_frag = "#define PHYSICAL\r\n\r\nuniform vec3 diffuse;\r\nuniform vec3 emissive;\r\nuniform float roughness;\r\nuniform float metalness;\r\nuniform float opacity;\r\n\r\n#ifndef STANDARD\r\n\tuniform float clearCoat;\r\n\tuniform float clearCoatRoughness;\r\n#endif\r\n\r\nvarying vec3 vViewPosition;\r\n\r\n#ifndef FLAT_SHADED\r\n\r\n\tvarying vec3 vNormal;\r\n\r\n#endif\r\n\r\n#include <common>\r\n#include <packing>\r\n#include <dithering_pars_fragment>\r\n#include <color_pars_fragment>\r\n#include <uv_pars_fragment>\r\n#include <uv2_pars_fragment>\r\n#include <map_pars_fragment>\r\n#include <alphamap_pars_fragment>\r\n#include <aomap_pars_fragment>\r\n#include <lightmap_pars_fragment>\r\n#include <emissivemap_pars_fragment>\r\n#include <bsdfs>\r\n#include <cube_uv_reflection_fragment>\r\n#include <envmap_pars_fragment>\r\n#include <envmap_physical_pars_fragment>\r\n#include <fog_pars_fragment>\r\n#include <lights_pars_begin>\r\n#include <lights_physical_pars_fragment>\r\n#include <shadowmap_pars_fragment>\r\n#include <bumpmap_pars_fragment>\r\n#include <normalmap_pars_fragment>\r\n#include <roughnessmap_pars_fragment>\r\n#include <metalnessmap_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tvec4 diffuseColor = vec4( diffuse, opacity );\r\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\r\n\tvec3 totalEmissiveRadiance = emissive;\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\t#include <map_fragment>\r\n\t#include <color_fragment>\r\n\t#include <alphamap_fragment>\r\n\t#include <alphatest_fragment>\r\n\t#include <roughnessmap_fragment>\r\n\t#include <metalnessmap_fragment>\r\n\t#include <normal_fragment_begin>\r\n\t#include <normal_fragment_maps>\r\n\t#include <emissivemap_fragment>\r\n\r\n\t// accumulation\r\n\t#include <lights_physical_fragment>\r\n\t#include <lights_fragment_begin>\r\n\t#include <lights_fragment_maps>\r\n\t#include <lights_fragment_end>\r\n\r\n\t// modulation\r\n\t#include <aomap_fragment>\r\n\r\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\r\n\r\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\r\n\r\n\t#include <tonemapping_fragment>\r\n\t#include <encodings_fragment>\r\n\t#include <fog_fragment>\r\n\t#include <premultiplied_alpha_fragment>\r\n\t#include <dithering_fragment>\r\n\r\n}\r\n";
  7543. var meshphysical_vert = "#define PHYSICAL\r\n\r\nvarying vec3 vViewPosition;\r\n\r\n#ifndef FLAT_SHADED\r\n\r\n\tvarying vec3 vNormal;\r\n\r\n#endif\r\n\r\n#include <common>\r\n#include <uv_pars_vertex>\r\n#include <uv2_pars_vertex>\r\n#include <displacementmap_pars_vertex>\r\n#include <color_pars_vertex>\r\n#include <fog_pars_vertex>\r\n#include <morphtarget_pars_vertex>\r\n#include <skinning_pars_vertex>\r\n#include <shadowmap_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <uv_vertex>\r\n\t#include <uv2_vertex>\r\n\t#include <color_vertex>\r\n\r\n\t#include <beginnormal_vertex>\r\n\t#include <morphnormal_vertex>\r\n\t#include <skinbase_vertex>\r\n\t#include <skinnormal_vertex>\r\n\t#include <defaultnormal_vertex>\r\n\r\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\r\n\r\n\tvNormal = normalize( transformedNormal );\r\n\r\n#endif\r\n\r\n\t#include <begin_vertex>\r\n\t#include <morphtarget_vertex>\r\n\t#include <skinning_vertex>\r\n\t#include <displacementmap_vertex>\r\n\t#include <project_vertex>\r\n\t#include <logdepthbuf_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\r\n\tvViewPosition = - mvPosition.xyz;\r\n\r\n\t#include <worldpos_vertex>\r\n\t#include <shadowmap_vertex>\r\n\t#include <fog_vertex>\r\n\r\n}\r\n";
  7544. var normal_frag = "#define NORMAL\r\n\r\nuniform float opacity;\r\n\r\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || ( defined( USE_NORMALMAP ) && ! defined( OBJECTSPACE_NORMALMAP ) )\r\n\r\n\tvarying vec3 vViewPosition;\r\n\r\n#endif\r\n\r\n#ifndef FLAT_SHADED\r\n\r\n\tvarying vec3 vNormal;\r\n\r\n#endif\r\n\r\n#include <packing>\r\n#include <uv_pars_fragment>\r\n#include <bumpmap_pars_fragment>\r\n#include <normalmap_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\t#include <normal_fragment_begin>\r\n\t#include <normal_fragment_maps>\r\n\r\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\r\n\r\n}\r\n";
  7545. var normal_vert = "#define NORMAL\r\n\r\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || ( defined( USE_NORMALMAP ) && ! defined( OBJECTSPACE_NORMALMAP ) )\r\n\r\n\tvarying vec3 vViewPosition;\r\n\r\n#endif\r\n\r\n#ifndef FLAT_SHADED\r\n\r\n\tvarying vec3 vNormal;\r\n\r\n#endif\r\n\r\n#include <uv_pars_vertex>\r\n#include <displacementmap_pars_vertex>\r\n#include <morphtarget_pars_vertex>\r\n#include <skinning_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <uv_vertex>\r\n\r\n\t#include <beginnormal_vertex>\r\n\t#include <morphnormal_vertex>\r\n\t#include <skinbase_vertex>\r\n\t#include <skinnormal_vertex>\r\n\t#include <defaultnormal_vertex>\r\n\r\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\r\n\r\n\tvNormal = normalize( transformedNormal );\r\n\r\n#endif\r\n\r\n\t#include <begin_vertex>\r\n\t#include <morphtarget_vertex>\r\n\t#include <skinning_vertex>\r\n\t#include <displacementmap_vertex>\r\n\t#include <project_vertex>\r\n\t#include <logdepthbuf_vertex>\r\n\r\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || ( defined( USE_NORMALMAP ) && ! defined( OBJECTSPACE_NORMALMAP ) )\r\n\r\n\tvViewPosition = - mvPosition.xyz;\r\n\r\n#endif\r\n\r\n}\r\n";
  7546. var points_frag = "uniform vec3 diffuse;\r\nuniform float opacity;\r\n\r\n#include <common>\r\n#include <color_pars_fragment>\r\n#include <map_particle_pars_fragment>\r\n#include <fog_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tvec3 outgoingLight = vec3( 0.0 );\r\n\tvec4 diffuseColor = vec4( diffuse, opacity );\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\t#include <map_particle_fragment>\r\n\t#include <color_fragment>\r\n\t#include <alphatest_fragment>\r\n\r\n\toutgoingLight = diffuseColor.rgb;\r\n\r\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\r\n\r\n\t#include <premultiplied_alpha_fragment>\r\n\t#include <tonemapping_fragment>\r\n\t#include <encodings_fragment>\r\n\t#include <fog_fragment>\r\n\r\n}\r\n";
  7547. var points_vert = "uniform float size;\r\nuniform float scale;\r\n\r\n#include <common>\r\n#include <color_pars_vertex>\r\n#include <fog_pars_vertex>\r\n#include <morphtarget_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <color_vertex>\r\n\t#include <begin_vertex>\r\n\t#include <morphtarget_vertex>\r\n\t#include <project_vertex>\r\n\r\n\tgl_PointSize = size;\r\n\r\n\t#ifdef USE_SIZEATTENUATION\r\n\r\n\t\tbool isPerspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 );\r\n\r\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\r\n\r\n\t#endif\r\n\r\n\t#include <logdepthbuf_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\t#include <worldpos_vertex>\r\n\t#include <fog_vertex>\r\n\r\n}\r\n";
  7548. var shadow_frag = "uniform vec3 color;\r\nuniform float opacity;\r\n\r\n#include <common>\r\n#include <packing>\r\n#include <fog_pars_fragment>\r\n#include <bsdfs>\r\n#include <lights_pars_begin>\r\n#include <shadowmap_pars_fragment>\r\n#include <shadowmask_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\r\n\r\n\t#include <fog_fragment>\r\n\r\n}\r\n";
  7549. var shadow_vert = "#include <fog_pars_vertex>\r\n#include <shadowmap_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <begin_vertex>\r\n\t#include <project_vertex>\r\n\t#include <worldpos_vertex>\r\n\t#include <shadowmap_vertex>\r\n\t#include <fog_vertex>\r\n\r\n}\r\n";
  7550. var sprite_frag = "uniform vec3 diffuse;\r\nuniform float opacity;\r\n\r\n#include <common>\r\n#include <uv_pars_fragment>\r\n#include <map_pars_fragment>\r\n#include <fog_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tvec3 outgoingLight = vec3( 0.0 );\r\n\tvec4 diffuseColor = vec4( diffuse, opacity );\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\t#include <map_fragment>\r\n\t#include <alphatest_fragment>\r\n\r\n\toutgoingLight = diffuseColor.rgb;\r\n\r\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\r\n\r\n\t#include <tonemapping_fragment>\r\n\t#include <encodings_fragment>\r\n\t#include <fog_fragment>\r\n\r\n}\r\n";
  7551. var sprite_vert = "uniform float rotation;\r\nuniform vec2 center;\r\n\r\n#include <common>\r\n#include <uv_pars_vertex>\r\n#include <fog_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <uv_vertex>\r\n\r\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\r\n\r\n\tvec2 scale;\r\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\r\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\r\n\r\n\t#ifndef USE_SIZEATTENUATION\r\n\r\n\t\tbool isPerspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 );\r\n\r\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\r\n\r\n\t#endif\r\n\r\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\r\n\r\n\tvec2 rotatedPosition;\r\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\r\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\r\n\r\n\tmvPosition.xy += rotatedPosition;\r\n\r\n\tgl_Position = projectionMatrix * mvPosition;\r\n\r\n\t#include <logdepthbuf_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\t#include <fog_vertex>\r\n\r\n}\r\n";
  7552. var ShaderChunk = {
  7553. alphamap_fragment: alphamap_fragment,
  7554. alphamap_pars_fragment: alphamap_pars_fragment,
  7555. alphatest_fragment: alphatest_fragment,
  7556. aomap_fragment: aomap_fragment,
  7557. aomap_pars_fragment: aomap_pars_fragment,
  7558. begin_vertex: begin_vertex,
  7559. beginnormal_vertex: beginnormal_vertex,
  7560. bsdfs: bsdfs,
  7561. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7562. clipping_planes_fragment: clipping_planes_fragment,
  7563. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7564. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7565. clipping_planes_vertex: clipping_planes_vertex,
  7566. color_fragment: color_fragment,
  7567. color_pars_fragment: color_pars_fragment,
  7568. color_pars_vertex: color_pars_vertex,
  7569. color_vertex: color_vertex,
  7570. common: common,
  7571. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7572. defaultnormal_vertex: defaultnormal_vertex,
  7573. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7574. displacementmap_vertex: displacementmap_vertex,
  7575. emissivemap_fragment: emissivemap_fragment,
  7576. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7577. encodings_fragment: encodings_fragment,
  7578. encodings_pars_fragment: encodings_pars_fragment,
  7579. envmap_fragment: envmap_fragment,
  7580. envmap_pars_fragment: envmap_pars_fragment,
  7581. envmap_pars_vertex: envmap_pars_vertex,
  7582. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7583. envmap_vertex: envmap_vertex,
  7584. fog_vertex: fog_vertex,
  7585. fog_pars_vertex: fog_pars_vertex,
  7586. fog_fragment: fog_fragment,
  7587. fog_pars_fragment: fog_pars_fragment,
  7588. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7589. lightmap_fragment: lightmap_fragment,
  7590. lightmap_pars_fragment: lightmap_pars_fragment,
  7591. lights_lambert_vertex: lights_lambert_vertex,
  7592. lights_pars_begin: lights_pars_begin,
  7593. lights_phong_fragment: lights_phong_fragment,
  7594. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7595. lights_physical_fragment: lights_physical_fragment,
  7596. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7597. lights_fragment_begin: lights_fragment_begin,
  7598. lights_fragment_maps: lights_fragment_maps,
  7599. lights_fragment_end: lights_fragment_end,
  7600. logdepthbuf_fragment: logdepthbuf_fragment,
  7601. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7602. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7603. logdepthbuf_vertex: logdepthbuf_vertex,
  7604. map_fragment: map_fragment,
  7605. map_pars_fragment: map_pars_fragment,
  7606. map_particle_fragment: map_particle_fragment,
  7607. map_particle_pars_fragment: map_particle_pars_fragment,
  7608. metalnessmap_fragment: metalnessmap_fragment,
  7609. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7610. morphnormal_vertex: morphnormal_vertex,
  7611. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7612. morphtarget_vertex: morphtarget_vertex,
  7613. normal_fragment_begin: normal_fragment_begin,
  7614. normal_fragment_maps: normal_fragment_maps,
  7615. normalmap_pars_fragment: normalmap_pars_fragment,
  7616. packing: packing,
  7617. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  7618. project_vertex: project_vertex,
  7619. dithering_fragment: dithering_fragment,
  7620. dithering_pars_fragment: dithering_pars_fragment,
  7621. roughnessmap_fragment: roughnessmap_fragment,
  7622. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  7623. shadowmap_pars_fragment: shadowmap_pars_fragment,
  7624. shadowmap_pars_vertex: shadowmap_pars_vertex,
  7625. shadowmap_vertex: shadowmap_vertex,
  7626. shadowmask_pars_fragment: shadowmask_pars_fragment,
  7627. skinbase_vertex: skinbase_vertex,
  7628. skinning_pars_vertex: skinning_pars_vertex,
  7629. skinning_vertex: skinning_vertex,
  7630. skinnormal_vertex: skinnormal_vertex,
  7631. specularmap_fragment: specularmap_fragment,
  7632. specularmap_pars_fragment: specularmap_pars_fragment,
  7633. tonemapping_fragment: tonemapping_fragment,
  7634. tonemapping_pars_fragment: tonemapping_pars_fragment,
  7635. uv_pars_fragment: uv_pars_fragment,
  7636. uv_pars_vertex: uv_pars_vertex,
  7637. uv_vertex: uv_vertex,
  7638. uv2_pars_fragment: uv2_pars_fragment,
  7639. uv2_pars_vertex: uv2_pars_vertex,
  7640. uv2_vertex: uv2_vertex,
  7641. worldpos_vertex: worldpos_vertex,
  7642. background_frag: background_frag,
  7643. background_vert: background_vert,
  7644. cube_frag: cube_frag,
  7645. cube_vert: cube_vert,
  7646. depth_frag: depth_frag,
  7647. depth_vert: depth_vert,
  7648. distanceRGBA_frag: distanceRGBA_frag,
  7649. distanceRGBA_vert: distanceRGBA_vert,
  7650. equirect_frag: equirect_frag,
  7651. equirect_vert: equirect_vert,
  7652. linedashed_frag: linedashed_frag,
  7653. linedashed_vert: linedashed_vert,
  7654. meshbasic_frag: meshbasic_frag,
  7655. meshbasic_vert: meshbasic_vert,
  7656. meshlambert_frag: meshlambert_frag,
  7657. meshlambert_vert: meshlambert_vert,
  7658. meshmatcap_frag: meshmatcap_frag,
  7659. meshmatcap_vert: meshmatcap_vert,
  7660. meshphong_frag: meshphong_frag,
  7661. meshphong_vert: meshphong_vert,
  7662. meshphysical_frag: meshphysical_frag,
  7663. meshphysical_vert: meshphysical_vert,
  7664. normal_frag: normal_frag,
  7665. normal_vert: normal_vert,
  7666. points_frag: points_frag,
  7667. points_vert: points_vert,
  7668. shadow_frag: shadow_frag,
  7669. shadow_vert: shadow_vert,
  7670. sprite_frag: sprite_frag,
  7671. sprite_vert: sprite_vert
  7672. };
  7673. /**
  7674. * Uniform Utilities
  7675. */
  7676. var UniformsUtils = {
  7677. merge: function ( uniforms ) {
  7678. var merged = {};
  7679. for ( var u = 0; u < uniforms.length; u ++ ) {
  7680. var tmp = this.clone( uniforms[ u ] );
  7681. for ( var p in tmp ) {
  7682. merged[ p ] = tmp[ p ];
  7683. }
  7684. }
  7685. return merged;
  7686. },
  7687. clone: function ( uniforms_src ) {
  7688. var uniforms_dst = {};
  7689. for ( var u in uniforms_src ) {
  7690. uniforms_dst[ u ] = {};
  7691. for ( var p in uniforms_src[ u ] ) {
  7692. var parameter_src = uniforms_src[ u ][ p ];
  7693. if ( parameter_src && ( parameter_src.isColor ||
  7694. parameter_src.isMatrix3 || parameter_src.isMatrix4 ||
  7695. parameter_src.isVector2 || parameter_src.isVector3 || parameter_src.isVector4 ||
  7696. parameter_src.isTexture ) ) {
  7697. uniforms_dst[ u ][ p ] = parameter_src.clone();
  7698. } else if ( Array.isArray( parameter_src ) ) {
  7699. uniforms_dst[ u ][ p ] = parameter_src.slice();
  7700. } else {
  7701. uniforms_dst[ u ][ p ] = parameter_src;
  7702. }
  7703. }
  7704. }
  7705. return uniforms_dst;
  7706. }
  7707. };
  7708. /**
  7709. * @author mrdoob / http://mrdoob.com/
  7710. */
  7711. var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  7712. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  7713. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  7714. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  7715. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  7716. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  7717. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  7718. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  7719. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  7720. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  7721. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  7722. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  7723. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  7724. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  7725. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  7726. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  7727. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  7728. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  7729. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  7730. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  7731. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  7732. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  7733. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  7734. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  7735. function Color( r, g, b ) {
  7736. if ( g === undefined && b === undefined ) {
  7737. // r is THREE.Color, hex or string
  7738. return this.set( r );
  7739. }
  7740. return this.setRGB( r, g, b );
  7741. }
  7742. Object.assign( Color.prototype, {
  7743. isColor: true,
  7744. r: 1, g: 1, b: 1,
  7745. set: function ( value ) {
  7746. if ( value && value.isColor ) {
  7747. this.copy( value );
  7748. } else if ( typeof value === 'number' ) {
  7749. this.setHex( value );
  7750. } else if ( typeof value === 'string' ) {
  7751. this.setStyle( value );
  7752. }
  7753. return this;
  7754. },
  7755. setScalar: function ( scalar ) {
  7756. this.r = scalar;
  7757. this.g = scalar;
  7758. this.b = scalar;
  7759. return this;
  7760. },
  7761. setHex: function ( hex ) {
  7762. hex = Math.floor( hex );
  7763. this.r = ( hex >> 16 & 255 ) / 255;
  7764. this.g = ( hex >> 8 & 255 ) / 255;
  7765. this.b = ( hex & 255 ) / 255;
  7766. return this;
  7767. },
  7768. setRGB: function ( r, g, b ) {
  7769. this.r = r;
  7770. this.g = g;
  7771. this.b = b;
  7772. return this;
  7773. },
  7774. setHSL: function () {
  7775. function hue2rgb( p, q, t ) {
  7776. if ( t < 0 ) t += 1;
  7777. if ( t > 1 ) t -= 1;
  7778. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  7779. if ( t < 1 / 2 ) return q;
  7780. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  7781. return p;
  7782. }
  7783. return function setHSL( h, s, l ) {
  7784. // h,s,l ranges are in 0.0 - 1.0
  7785. h = _Math.euclideanModulo( h, 1 );
  7786. s = _Math.clamp( s, 0, 1 );
  7787. l = _Math.clamp( l, 0, 1 );
  7788. if ( s === 0 ) {
  7789. this.r = this.g = this.b = l;
  7790. } else {
  7791. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  7792. var q = ( 2 * l ) - p;
  7793. this.r = hue2rgb( q, p, h + 1 / 3 );
  7794. this.g = hue2rgb( q, p, h );
  7795. this.b = hue2rgb( q, p, h - 1 / 3 );
  7796. }
  7797. return this;
  7798. };
  7799. }(),
  7800. setStyle: function ( style ) {
  7801. function handleAlpha( string ) {
  7802. if ( string === undefined ) return;
  7803. if ( parseFloat( string ) < 1 ) {
  7804. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  7805. }
  7806. }
  7807. var m;
  7808. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  7809. // rgb / hsl
  7810. var color;
  7811. var name = m[ 1 ];
  7812. var components = m[ 2 ];
  7813. switch ( name ) {
  7814. case 'rgb':
  7815. case 'rgba':
  7816. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  7817. // rgb(255,0,0) rgba(255,0,0,0.5)
  7818. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  7819. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  7820. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  7821. handleAlpha( color[ 5 ] );
  7822. return this;
  7823. }
  7824. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  7825. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  7826. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  7827. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  7828. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  7829. handleAlpha( color[ 5 ] );
  7830. return this;
  7831. }
  7832. break;
  7833. case 'hsl':
  7834. case 'hsla':
  7835. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  7836. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  7837. var h = parseFloat( color[ 1 ] ) / 360;
  7838. var s = parseInt( color[ 2 ], 10 ) / 100;
  7839. var l = parseInt( color[ 3 ], 10 ) / 100;
  7840. handleAlpha( color[ 5 ] );
  7841. return this.setHSL( h, s, l );
  7842. }
  7843. break;
  7844. }
  7845. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  7846. // hex color
  7847. var hex = m[ 1 ];
  7848. var size = hex.length;
  7849. if ( size === 3 ) {
  7850. // #ff0
  7851. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  7852. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  7853. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  7854. return this;
  7855. } else if ( size === 6 ) {
  7856. // #ff0000
  7857. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  7858. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  7859. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  7860. return this;
  7861. }
  7862. }
  7863. if ( style && style.length > 0 ) {
  7864. // color keywords
  7865. var hex = ColorKeywords[ style ];
  7866. if ( hex !== undefined ) {
  7867. // red
  7868. this.setHex( hex );
  7869. } else {
  7870. // unknown color
  7871. console.warn( 'THREE.Color: Unknown color ' + style );
  7872. }
  7873. }
  7874. return this;
  7875. },
  7876. clone: function () {
  7877. return new this.constructor( this.r, this.g, this.b );
  7878. },
  7879. copy: function ( color ) {
  7880. this.r = color.r;
  7881. this.g = color.g;
  7882. this.b = color.b;
  7883. return this;
  7884. },
  7885. copyGammaToLinear: function ( color, gammaFactor ) {
  7886. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  7887. this.r = Math.pow( color.r, gammaFactor );
  7888. this.g = Math.pow( color.g, gammaFactor );
  7889. this.b = Math.pow( color.b, gammaFactor );
  7890. return this;
  7891. },
  7892. copyLinearToGamma: function ( color, gammaFactor ) {
  7893. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  7894. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  7895. this.r = Math.pow( color.r, safeInverse );
  7896. this.g = Math.pow( color.g, safeInverse );
  7897. this.b = Math.pow( color.b, safeInverse );
  7898. return this;
  7899. },
  7900. convertGammaToLinear: function ( gammaFactor ) {
  7901. this.copyGammaToLinear( this, gammaFactor );
  7902. return this;
  7903. },
  7904. convertLinearToGamma: function ( gammaFactor ) {
  7905. this.copyLinearToGamma( this, gammaFactor );
  7906. return this;
  7907. },
  7908. copySRGBToLinear: function () {
  7909. function SRGBToLinear( c ) {
  7910. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  7911. }
  7912. return function copySRGBToLinear( color ) {
  7913. this.r = SRGBToLinear( color.r );
  7914. this.g = SRGBToLinear( color.g );
  7915. this.b = SRGBToLinear( color.b );
  7916. return this;
  7917. };
  7918. }(),
  7919. copyLinearToSRGB: function () {
  7920. function LinearToSRGB( c ) {
  7921. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  7922. }
  7923. return function copyLinearToSRGB( color ) {
  7924. this.r = LinearToSRGB( color.r );
  7925. this.g = LinearToSRGB( color.g );
  7926. this.b = LinearToSRGB( color.b );
  7927. return this;
  7928. };
  7929. }(),
  7930. convertSRGBToLinear: function () {
  7931. this.copySRGBToLinear( this );
  7932. return this;
  7933. },
  7934. convertLinearToSRGB: function () {
  7935. this.copyLinearToSRGB( this );
  7936. return this;
  7937. },
  7938. getHex: function () {
  7939. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  7940. },
  7941. getHexString: function () {
  7942. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  7943. },
  7944. getHSL: function ( target ) {
  7945. // h,s,l ranges are in 0.0 - 1.0
  7946. if ( target === undefined ) {
  7947. console.warn( 'THREE.Color: .getHSL() target is now required' );
  7948. target = { h: 0, s: 0, l: 0 };
  7949. }
  7950. var r = this.r, g = this.g, b = this.b;
  7951. var max = Math.max( r, g, b );
  7952. var min = Math.min( r, g, b );
  7953. var hue, saturation;
  7954. var lightness = ( min + max ) / 2.0;
  7955. if ( min === max ) {
  7956. hue = 0;
  7957. saturation = 0;
  7958. } else {
  7959. var delta = max - min;
  7960. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  7961. switch ( max ) {
  7962. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  7963. case g: hue = ( b - r ) / delta + 2; break;
  7964. case b: hue = ( r - g ) / delta + 4; break;
  7965. }
  7966. hue /= 6;
  7967. }
  7968. target.h = hue;
  7969. target.s = saturation;
  7970. target.l = lightness;
  7971. return target;
  7972. },
  7973. getStyle: function () {
  7974. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  7975. },
  7976. offsetHSL: function () {
  7977. var hsl = {};
  7978. return function ( h, s, l ) {
  7979. this.getHSL( hsl );
  7980. hsl.h += h; hsl.s += s; hsl.l += l;
  7981. this.setHSL( hsl.h, hsl.s, hsl.l );
  7982. return this;
  7983. };
  7984. }(),
  7985. add: function ( color ) {
  7986. this.r += color.r;
  7987. this.g += color.g;
  7988. this.b += color.b;
  7989. return this;
  7990. },
  7991. addColors: function ( color1, color2 ) {
  7992. this.r = color1.r + color2.r;
  7993. this.g = color1.g + color2.g;
  7994. this.b = color1.b + color2.b;
  7995. return this;
  7996. },
  7997. addScalar: function ( s ) {
  7998. this.r += s;
  7999. this.g += s;
  8000. this.b += s;
  8001. return this;
  8002. },
  8003. sub: function ( color ) {
  8004. this.r = Math.max( 0, this.r - color.r );
  8005. this.g = Math.max( 0, this.g - color.g );
  8006. this.b = Math.max( 0, this.b - color.b );
  8007. return this;
  8008. },
  8009. multiply: function ( color ) {
  8010. this.r *= color.r;
  8011. this.g *= color.g;
  8012. this.b *= color.b;
  8013. return this;
  8014. },
  8015. multiplyScalar: function ( s ) {
  8016. this.r *= s;
  8017. this.g *= s;
  8018. this.b *= s;
  8019. return this;
  8020. },
  8021. lerp: function ( color, alpha ) {
  8022. this.r += ( color.r - this.r ) * alpha;
  8023. this.g += ( color.g - this.g ) * alpha;
  8024. this.b += ( color.b - this.b ) * alpha;
  8025. return this;
  8026. },
  8027. lerpHSL: function () {
  8028. var hslA = { h: 0, s: 0, l: 0 };
  8029. var hslB = { h: 0, s: 0, l: 0 };
  8030. return function lerpHSL( color, alpha ) {
  8031. this.getHSL( hslA );
  8032. color.getHSL( hslB );
  8033. var h = _Math.lerp( hslA.h, hslB.h, alpha );
  8034. var s = _Math.lerp( hslA.s, hslB.s, alpha );
  8035. var l = _Math.lerp( hslA.l, hslB.l, alpha );
  8036. this.setHSL( h, s, l );
  8037. return this;
  8038. };
  8039. }(),
  8040. equals: function ( c ) {
  8041. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  8042. },
  8043. fromArray: function ( array, offset ) {
  8044. if ( offset === undefined ) offset = 0;
  8045. this.r = array[ offset ];
  8046. this.g = array[ offset + 1 ];
  8047. this.b = array[ offset + 2 ];
  8048. return this;
  8049. },
  8050. toArray: function ( array, offset ) {
  8051. if ( array === undefined ) array = [];
  8052. if ( offset === undefined ) offset = 0;
  8053. array[ offset ] = this.r;
  8054. array[ offset + 1 ] = this.g;
  8055. array[ offset + 2 ] = this.b;
  8056. return array;
  8057. },
  8058. toJSON: function () {
  8059. return this.getHex();
  8060. }
  8061. } );
  8062. /**
  8063. * Uniforms library for shared webgl shaders
  8064. */
  8065. var UniformsLib = {
  8066. common: {
  8067. diffuse: { value: new Color( 0xeeeeee ) },
  8068. opacity: { value: 1.0 },
  8069. map: { value: null },
  8070. uvTransform: { value: new Matrix3() },
  8071. alphaMap: { value: null },
  8072. },
  8073. specularmap: {
  8074. specularMap: { value: null },
  8075. },
  8076. envmap: {
  8077. envMap: { value: null },
  8078. flipEnvMap: { value: - 1 },
  8079. reflectivity: { value: 1.0 },
  8080. refractionRatio: { value: 0.98 },
  8081. maxMipLevel: { value: 0 }
  8082. },
  8083. aomap: {
  8084. aoMap: { value: null },
  8085. aoMapIntensity: { value: 1 }
  8086. },
  8087. lightmap: {
  8088. lightMap: { value: null },
  8089. lightMapIntensity: { value: 1 }
  8090. },
  8091. emissivemap: {
  8092. emissiveMap: { value: null }
  8093. },
  8094. bumpmap: {
  8095. bumpMap: { value: null },
  8096. bumpScale: { value: 1 }
  8097. },
  8098. normalmap: {
  8099. normalMap: { value: null },
  8100. normalScale: { value: new Vector2( 1, 1 ) }
  8101. },
  8102. displacementmap: {
  8103. displacementMap: { value: null },
  8104. displacementScale: { value: 1 },
  8105. displacementBias: { value: 0 }
  8106. },
  8107. roughnessmap: {
  8108. roughnessMap: { value: null }
  8109. },
  8110. metalnessmap: {
  8111. metalnessMap: { value: null }
  8112. },
  8113. gradientmap: {
  8114. gradientMap: { value: null }
  8115. },
  8116. fog: {
  8117. fogDensity: { value: 0.00025 },
  8118. fogNear: { value: 1 },
  8119. fogFar: { value: 2000 },
  8120. fogColor: { value: new Color( 0xffffff ) }
  8121. },
  8122. lights: {
  8123. ambientLightColor: { value: [] },
  8124. directionalLights: { value: [], properties: {
  8125. direction: {},
  8126. color: {},
  8127. shadow: {},
  8128. shadowBias: {},
  8129. shadowRadius: {},
  8130. shadowMapSize: {}
  8131. } },
  8132. directionalShadowMap: { value: [] },
  8133. directionalShadowMatrix: { value: [] },
  8134. spotLights: { value: [], properties: {
  8135. color: {},
  8136. position: {},
  8137. direction: {},
  8138. distance: {},
  8139. coneCos: {},
  8140. penumbraCos: {},
  8141. decay: {},
  8142. shadow: {},
  8143. shadowBias: {},
  8144. shadowRadius: {},
  8145. shadowMapSize: {}
  8146. } },
  8147. spotShadowMap: { value: [] },
  8148. spotShadowMatrix: { value: [] },
  8149. pointLights: { value: [], properties: {
  8150. color: {},
  8151. position: {},
  8152. decay: {},
  8153. distance: {},
  8154. shadow: {},
  8155. shadowBias: {},
  8156. shadowRadius: {},
  8157. shadowMapSize: {},
  8158. shadowCameraNear: {},
  8159. shadowCameraFar: {}
  8160. } },
  8161. pointShadowMap: { value: [] },
  8162. pointShadowMatrix: { value: [] },
  8163. hemisphereLights: { value: [], properties: {
  8164. direction: {},
  8165. skyColor: {},
  8166. groundColor: {}
  8167. } },
  8168. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8169. rectAreaLights: { value: [], properties: {
  8170. color: {},
  8171. position: {},
  8172. width: {},
  8173. height: {}
  8174. } }
  8175. },
  8176. points: {
  8177. diffuse: { value: new Color( 0xeeeeee ) },
  8178. opacity: { value: 1.0 },
  8179. size: { value: 1.0 },
  8180. scale: { value: 1.0 },
  8181. map: { value: null },
  8182. uvTransform: { value: new Matrix3() }
  8183. },
  8184. sprite: {
  8185. diffuse: { value: new Color( 0xeeeeee ) },
  8186. opacity: { value: 1.0 },
  8187. center: { value: new Vector2( 0.5, 0.5 ) },
  8188. rotation: { value: 0.0 },
  8189. map: { value: null },
  8190. uvTransform: { value: new Matrix3() }
  8191. }
  8192. };
  8193. /**
  8194. * @author alteredq / http://alteredqualia.com/
  8195. * @author mrdoob / http://mrdoob.com/
  8196. * @author mikael emtinger / http://gomo.se/
  8197. */
  8198. var ShaderLib = {
  8199. basic: {
  8200. uniforms: UniformsUtils.merge( [
  8201. UniformsLib.common,
  8202. UniformsLib.specularmap,
  8203. UniformsLib.envmap,
  8204. UniformsLib.aomap,
  8205. UniformsLib.lightmap,
  8206. UniformsLib.fog
  8207. ] ),
  8208. vertexShader: ShaderChunk.meshbasic_vert,
  8209. fragmentShader: ShaderChunk.meshbasic_frag
  8210. },
  8211. lambert: {
  8212. uniforms: UniformsUtils.merge( [
  8213. UniformsLib.common,
  8214. UniformsLib.specularmap,
  8215. UniformsLib.envmap,
  8216. UniformsLib.aomap,
  8217. UniformsLib.lightmap,
  8218. UniformsLib.emissivemap,
  8219. UniformsLib.fog,
  8220. UniformsLib.lights,
  8221. {
  8222. emissive: { value: new Color( 0x000000 ) }
  8223. }
  8224. ] ),
  8225. vertexShader: ShaderChunk.meshlambert_vert,
  8226. fragmentShader: ShaderChunk.meshlambert_frag
  8227. },
  8228. phong: {
  8229. uniforms: UniformsUtils.merge( [
  8230. UniformsLib.common,
  8231. UniformsLib.specularmap,
  8232. UniformsLib.envmap,
  8233. UniformsLib.aomap,
  8234. UniformsLib.lightmap,
  8235. UniformsLib.emissivemap,
  8236. UniformsLib.bumpmap,
  8237. UniformsLib.normalmap,
  8238. UniformsLib.displacementmap,
  8239. UniformsLib.gradientmap,
  8240. UniformsLib.fog,
  8241. UniformsLib.lights,
  8242. {
  8243. emissive: { value: new Color( 0x000000 ) },
  8244. specular: { value: new Color( 0x111111 ) },
  8245. shininess: { value: 30 }
  8246. }
  8247. ] ),
  8248. vertexShader: ShaderChunk.meshphong_vert,
  8249. fragmentShader: ShaderChunk.meshphong_frag
  8250. },
  8251. standard: {
  8252. uniforms: UniformsUtils.merge( [
  8253. UniformsLib.common,
  8254. UniformsLib.envmap,
  8255. UniformsLib.aomap,
  8256. UniformsLib.lightmap,
  8257. UniformsLib.emissivemap,
  8258. UniformsLib.bumpmap,
  8259. UniformsLib.normalmap,
  8260. UniformsLib.displacementmap,
  8261. UniformsLib.roughnessmap,
  8262. UniformsLib.metalnessmap,
  8263. UniformsLib.fog,
  8264. UniformsLib.lights,
  8265. {
  8266. emissive: { value: new Color( 0x000000 ) },
  8267. roughness: { value: 0.5 },
  8268. metalness: { value: 0.5 },
  8269. envMapIntensity: { value: 1 } // temporary
  8270. }
  8271. ] ),
  8272. vertexShader: ShaderChunk.meshphysical_vert,
  8273. fragmentShader: ShaderChunk.meshphysical_frag
  8274. },
  8275. matcap: {
  8276. uniforms: UniformsUtils.merge( [
  8277. UniformsLib.common,
  8278. UniformsLib.bumpmap,
  8279. UniformsLib.normalmap,
  8280. UniformsLib.displacementmap,
  8281. UniformsLib.fog,
  8282. {
  8283. matcap: { value: null }
  8284. }
  8285. ] ),
  8286. vertexShader: ShaderChunk.meshmatcap_vert,
  8287. fragmentShader: ShaderChunk.meshmatcap_frag
  8288. },
  8289. points: {
  8290. uniforms: UniformsUtils.merge( [
  8291. UniformsLib.points,
  8292. UniformsLib.fog
  8293. ] ),
  8294. vertexShader: ShaderChunk.points_vert,
  8295. fragmentShader: ShaderChunk.points_frag
  8296. },
  8297. dashed: {
  8298. uniforms: UniformsUtils.merge( [
  8299. UniformsLib.common,
  8300. UniformsLib.fog,
  8301. {
  8302. scale: { value: 1 },
  8303. dashSize: { value: 1 },
  8304. totalSize: { value: 2 }
  8305. }
  8306. ] ),
  8307. vertexShader: ShaderChunk.linedashed_vert,
  8308. fragmentShader: ShaderChunk.linedashed_frag
  8309. },
  8310. depth: {
  8311. uniforms: UniformsUtils.merge( [
  8312. UniformsLib.common,
  8313. UniformsLib.displacementmap
  8314. ] ),
  8315. vertexShader: ShaderChunk.depth_vert,
  8316. fragmentShader: ShaderChunk.depth_frag
  8317. },
  8318. normal: {
  8319. uniforms: UniformsUtils.merge( [
  8320. UniformsLib.common,
  8321. UniformsLib.bumpmap,
  8322. UniformsLib.normalmap,
  8323. UniformsLib.displacementmap,
  8324. {
  8325. opacity: { value: 1.0 }
  8326. }
  8327. ] ),
  8328. vertexShader: ShaderChunk.normal_vert,
  8329. fragmentShader: ShaderChunk.normal_frag
  8330. },
  8331. sprite: {
  8332. uniforms: UniformsUtils.merge( [
  8333. UniformsLib.sprite,
  8334. UniformsLib.fog
  8335. ] ),
  8336. vertexShader: ShaderChunk.sprite_vert,
  8337. fragmentShader: ShaderChunk.sprite_frag
  8338. },
  8339. background: {
  8340. uniforms: {
  8341. uvTransform: { value: new Matrix3() },
  8342. t2D: { value: null },
  8343. },
  8344. vertexShader: ShaderChunk.background_vert,
  8345. fragmentShader: ShaderChunk.background_frag
  8346. },
  8347. /* -------------------------------------------------------------------------
  8348. // Cube map shader
  8349. ------------------------------------------------------------------------- */
  8350. cube: {
  8351. uniforms: {
  8352. tCube: { value: null },
  8353. tFlip: { value: - 1 },
  8354. opacity: { value: 1.0 }
  8355. },
  8356. vertexShader: ShaderChunk.cube_vert,
  8357. fragmentShader: ShaderChunk.cube_frag
  8358. },
  8359. equirect: {
  8360. uniforms: {
  8361. tEquirect: { value: null },
  8362. },
  8363. vertexShader: ShaderChunk.equirect_vert,
  8364. fragmentShader: ShaderChunk.equirect_frag
  8365. },
  8366. distanceRGBA: {
  8367. uniforms: UniformsUtils.merge( [
  8368. UniformsLib.common,
  8369. UniformsLib.displacementmap,
  8370. {
  8371. referencePosition: { value: new Vector3() },
  8372. nearDistance: { value: 1 },
  8373. farDistance: { value: 1000 }
  8374. }
  8375. ] ),
  8376. vertexShader: ShaderChunk.distanceRGBA_vert,
  8377. fragmentShader: ShaderChunk.distanceRGBA_frag
  8378. },
  8379. shadow: {
  8380. uniforms: UniformsUtils.merge( [
  8381. UniformsLib.lights,
  8382. UniformsLib.fog,
  8383. {
  8384. color: { value: new Color( 0x00000 ) },
  8385. opacity: { value: 1.0 }
  8386. },
  8387. ] ),
  8388. vertexShader: ShaderChunk.shadow_vert,
  8389. fragmentShader: ShaderChunk.shadow_frag
  8390. }
  8391. };
  8392. ShaderLib.physical = {
  8393. uniforms: UniformsUtils.merge( [
  8394. ShaderLib.standard.uniforms,
  8395. {
  8396. clearCoat: { value: 0 },
  8397. clearCoatRoughness: { value: 0 }
  8398. }
  8399. ] ),
  8400. vertexShader: ShaderChunk.meshphysical_vert,
  8401. fragmentShader: ShaderChunk.meshphysical_frag
  8402. };
  8403. /**
  8404. * @author mrdoob / http://mrdoob.com/
  8405. */
  8406. function WebGLAnimation() {
  8407. var context = null;
  8408. var isAnimating = false;
  8409. var animationLoop = null;
  8410. function onAnimationFrame( time, frame ) {
  8411. if ( isAnimating === false ) return;
  8412. animationLoop( time, frame );
  8413. context.requestAnimationFrame( onAnimationFrame );
  8414. }
  8415. return {
  8416. start: function () {
  8417. if ( isAnimating === true ) return;
  8418. if ( animationLoop === null ) return;
  8419. context.requestAnimationFrame( onAnimationFrame );
  8420. isAnimating = true;
  8421. },
  8422. stop: function () {
  8423. isAnimating = false;
  8424. },
  8425. setAnimationLoop: function ( callback ) {
  8426. animationLoop = callback;
  8427. },
  8428. setContext: function ( value ) {
  8429. context = value;
  8430. }
  8431. };
  8432. }
  8433. /**
  8434. * @author mrdoob / http://mrdoob.com/
  8435. */
  8436. function WebGLAttributes( gl ) {
  8437. var buffers = new WeakMap();
  8438. function createBuffer( attribute, bufferType ) {
  8439. var array = attribute.array;
  8440. var usage = attribute.dynamic ? 35048 : 35044;
  8441. var buffer = gl.createBuffer();
  8442. gl.bindBuffer( bufferType, buffer );
  8443. gl.bufferData( bufferType, array, usage );
  8444. attribute.onUploadCallback();
  8445. var type = 5126;
  8446. if ( array instanceof Float32Array ) {
  8447. type = 5126;
  8448. } else if ( array instanceof Float64Array ) {
  8449. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  8450. } else if ( array instanceof Uint16Array ) {
  8451. type = 5123;
  8452. } else if ( array instanceof Int16Array ) {
  8453. type = 5122;
  8454. } else if ( array instanceof Uint32Array ) {
  8455. type = 5125;
  8456. } else if ( array instanceof Int32Array ) {
  8457. type = 5124;
  8458. } else if ( array instanceof Int8Array ) {
  8459. type = 5120;
  8460. } else if ( array instanceof Uint8Array ) {
  8461. type = 5121;
  8462. }
  8463. return {
  8464. buffer: buffer,
  8465. type: type,
  8466. bytesPerElement: array.BYTES_PER_ELEMENT,
  8467. version: attribute.version
  8468. };
  8469. }
  8470. function updateBuffer( buffer, attribute, bufferType ) {
  8471. var array = attribute.array;
  8472. var updateRange = attribute.updateRange;
  8473. gl.bindBuffer( bufferType, buffer );
  8474. if ( attribute.dynamic === false ) {
  8475. gl.bufferData( bufferType, array, 35044 );
  8476. } else if ( updateRange.count === - 1 ) {
  8477. // Not using update ranges
  8478. gl.bufferSubData( bufferType, 0, array );
  8479. } else if ( updateRange.count === 0 ) {
  8480. 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.' );
  8481. } else {
  8482. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8483. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  8484. updateRange.count = - 1; // reset range
  8485. }
  8486. }
  8487. //
  8488. function get( attribute ) {
  8489. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8490. return buffers.get( attribute );
  8491. }
  8492. function remove( attribute ) {
  8493. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8494. var data = buffers.get( attribute );
  8495. if ( data ) {
  8496. gl.deleteBuffer( data.buffer );
  8497. buffers.delete( attribute );
  8498. }
  8499. }
  8500. function update( attribute, bufferType ) {
  8501. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8502. var data = buffers.get( attribute );
  8503. if ( data === undefined ) {
  8504. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  8505. } else if ( data.version < attribute.version ) {
  8506. updateBuffer( data.buffer, attribute, bufferType );
  8507. data.version = attribute.version;
  8508. }
  8509. }
  8510. return {
  8511. get: get,
  8512. remove: remove,
  8513. update: update
  8514. };
  8515. }
  8516. /**
  8517. * @author mrdoob / http://mrdoob.com/
  8518. * @author alteredq / http://alteredqualia.com/
  8519. */
  8520. function Face3( a, b, c, normal, color, materialIndex ) {
  8521. this.a = a;
  8522. this.b = b;
  8523. this.c = c;
  8524. this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
  8525. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  8526. this.color = ( color && color.isColor ) ? color : new Color();
  8527. this.vertexColors = Array.isArray( color ) ? color : [];
  8528. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  8529. }
  8530. Object.assign( Face3.prototype, {
  8531. clone: function () {
  8532. return new this.constructor().copy( this );
  8533. },
  8534. copy: function ( source ) {
  8535. this.a = source.a;
  8536. this.b = source.b;
  8537. this.c = source.c;
  8538. this.normal.copy( source.normal );
  8539. this.color.copy( source.color );
  8540. this.materialIndex = source.materialIndex;
  8541. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  8542. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  8543. }
  8544. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  8545. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  8546. }
  8547. return this;
  8548. }
  8549. } );
  8550. /**
  8551. * @author mrdoob / http://mrdoob.com/
  8552. * @author WestLangley / http://github.com/WestLangley
  8553. * @author bhouston / http://clara.io
  8554. */
  8555. function Euler( x, y, z, order ) {
  8556. this._x = x || 0;
  8557. this._y = y || 0;
  8558. this._z = z || 0;
  8559. this._order = order || Euler.DefaultOrder;
  8560. }
  8561. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  8562. Euler.DefaultOrder = 'XYZ';
  8563. Object.defineProperties( Euler.prototype, {
  8564. x: {
  8565. get: function () {
  8566. return this._x;
  8567. },
  8568. set: function ( value ) {
  8569. this._x = value;
  8570. this.onChangeCallback();
  8571. }
  8572. },
  8573. y: {
  8574. get: function () {
  8575. return this._y;
  8576. },
  8577. set: function ( value ) {
  8578. this._y = value;
  8579. this.onChangeCallback();
  8580. }
  8581. },
  8582. z: {
  8583. get: function () {
  8584. return this._z;
  8585. },
  8586. set: function ( value ) {
  8587. this._z = value;
  8588. this.onChangeCallback();
  8589. }
  8590. },
  8591. order: {
  8592. get: function () {
  8593. return this._order;
  8594. },
  8595. set: function ( value ) {
  8596. this._order = value;
  8597. this.onChangeCallback();
  8598. }
  8599. }
  8600. } );
  8601. Object.assign( Euler.prototype, {
  8602. isEuler: true,
  8603. set: function ( x, y, z, order ) {
  8604. this._x = x;
  8605. this._y = y;
  8606. this._z = z;
  8607. this._order = order || this._order;
  8608. this.onChangeCallback();
  8609. return this;
  8610. },
  8611. clone: function () {
  8612. return new this.constructor( this._x, this._y, this._z, this._order );
  8613. },
  8614. copy: function ( euler ) {
  8615. this._x = euler._x;
  8616. this._y = euler._y;
  8617. this._z = euler._z;
  8618. this._order = euler._order;
  8619. this.onChangeCallback();
  8620. return this;
  8621. },
  8622. setFromRotationMatrix: function ( m, order, update ) {
  8623. var clamp = _Math.clamp;
  8624. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  8625. var te = m.elements;
  8626. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  8627. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  8628. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  8629. order = order || this._order;
  8630. if ( order === 'XYZ' ) {
  8631. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  8632. if ( Math.abs( m13 ) < 0.99999 ) {
  8633. this._x = Math.atan2( - m23, m33 );
  8634. this._z = Math.atan2( - m12, m11 );
  8635. } else {
  8636. this._x = Math.atan2( m32, m22 );
  8637. this._z = 0;
  8638. }
  8639. } else if ( order === 'YXZ' ) {
  8640. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  8641. if ( Math.abs( m23 ) < 0.99999 ) {
  8642. this._y = Math.atan2( m13, m33 );
  8643. this._z = Math.atan2( m21, m22 );
  8644. } else {
  8645. this._y = Math.atan2( - m31, m11 );
  8646. this._z = 0;
  8647. }
  8648. } else if ( order === 'ZXY' ) {
  8649. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  8650. if ( Math.abs( m32 ) < 0.99999 ) {
  8651. this._y = Math.atan2( - m31, m33 );
  8652. this._z = Math.atan2( - m12, m22 );
  8653. } else {
  8654. this._y = 0;
  8655. this._z = Math.atan2( m21, m11 );
  8656. }
  8657. } else if ( order === 'ZYX' ) {
  8658. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  8659. if ( Math.abs( m31 ) < 0.99999 ) {
  8660. this._x = Math.atan2( m32, m33 );
  8661. this._z = Math.atan2( m21, m11 );
  8662. } else {
  8663. this._x = 0;
  8664. this._z = Math.atan2( - m12, m22 );
  8665. }
  8666. } else if ( order === 'YZX' ) {
  8667. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  8668. if ( Math.abs( m21 ) < 0.99999 ) {
  8669. this._x = Math.atan2( - m23, m22 );
  8670. this._y = Math.atan2( - m31, m11 );
  8671. } else {
  8672. this._x = 0;
  8673. this._y = Math.atan2( m13, m33 );
  8674. }
  8675. } else if ( order === 'XZY' ) {
  8676. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  8677. if ( Math.abs( m12 ) < 0.99999 ) {
  8678. this._x = Math.atan2( m32, m22 );
  8679. this._y = Math.atan2( m13, m11 );
  8680. } else {
  8681. this._x = Math.atan2( - m23, m33 );
  8682. this._y = 0;
  8683. }
  8684. } else {
  8685. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  8686. }
  8687. this._order = order;
  8688. if ( update !== false ) this.onChangeCallback();
  8689. return this;
  8690. },
  8691. setFromQuaternion: function () {
  8692. var matrix = new Matrix4();
  8693. return function setFromQuaternion( q, order, update ) {
  8694. matrix.makeRotationFromQuaternion( q );
  8695. return this.setFromRotationMatrix( matrix, order, update );
  8696. };
  8697. }(),
  8698. setFromVector3: function ( v, order ) {
  8699. return this.set( v.x, v.y, v.z, order || this._order );
  8700. },
  8701. reorder: function () {
  8702. // WARNING: this discards revolution information -bhouston
  8703. var q = new Quaternion();
  8704. return function reorder( newOrder ) {
  8705. q.setFromEuler( this );
  8706. return this.setFromQuaternion( q, newOrder );
  8707. };
  8708. }(),
  8709. equals: function ( euler ) {
  8710. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  8711. },
  8712. fromArray: function ( array ) {
  8713. this._x = array[ 0 ];
  8714. this._y = array[ 1 ];
  8715. this._z = array[ 2 ];
  8716. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  8717. this.onChangeCallback();
  8718. return this;
  8719. },
  8720. toArray: function ( array, offset ) {
  8721. if ( array === undefined ) array = [];
  8722. if ( offset === undefined ) offset = 0;
  8723. array[ offset ] = this._x;
  8724. array[ offset + 1 ] = this._y;
  8725. array[ offset + 2 ] = this._z;
  8726. array[ offset + 3 ] = this._order;
  8727. return array;
  8728. },
  8729. toVector3: function ( optionalResult ) {
  8730. if ( optionalResult ) {
  8731. return optionalResult.set( this._x, this._y, this._z );
  8732. } else {
  8733. return new Vector3( this._x, this._y, this._z );
  8734. }
  8735. },
  8736. onChange: function ( callback ) {
  8737. this.onChangeCallback = callback;
  8738. return this;
  8739. },
  8740. onChangeCallback: function () {}
  8741. } );
  8742. /**
  8743. * @author mrdoob / http://mrdoob.com/
  8744. */
  8745. function Layers() {
  8746. this.mask = 1 | 0;
  8747. }
  8748. Object.assign( Layers.prototype, {
  8749. set: function ( channel ) {
  8750. this.mask = 1 << channel | 0;
  8751. },
  8752. enable: function ( channel ) {
  8753. this.mask |= 1 << channel | 0;
  8754. },
  8755. toggle: function ( channel ) {
  8756. this.mask ^= 1 << channel | 0;
  8757. },
  8758. disable: function ( channel ) {
  8759. this.mask &= ~ ( 1 << channel | 0 );
  8760. },
  8761. test: function ( layers ) {
  8762. return ( this.mask & layers.mask ) !== 0;
  8763. }
  8764. } );
  8765. /**
  8766. * @author mrdoob / http://mrdoob.com/
  8767. * @author mikael emtinger / http://gomo.se/
  8768. * @author alteredq / http://alteredqualia.com/
  8769. * @author WestLangley / http://github.com/WestLangley
  8770. * @author elephantatwork / www.elephantatwork.ch
  8771. */
  8772. var object3DId = 0;
  8773. function Object3D() {
  8774. Object.defineProperty( this, 'id', { value: object3DId ++ } );
  8775. this.uuid = _Math.generateUUID();
  8776. this.name = '';
  8777. this.type = 'Object3D';
  8778. this.parent = null;
  8779. this.children = [];
  8780. this.up = Object3D.DefaultUp.clone();
  8781. var position = new Vector3();
  8782. var rotation = new Euler();
  8783. var quaternion = new Quaternion();
  8784. var scale = new Vector3( 1, 1, 1 );
  8785. function onRotationChange() {
  8786. quaternion.setFromEuler( rotation, false );
  8787. }
  8788. function onQuaternionChange() {
  8789. rotation.setFromQuaternion( quaternion, undefined, false );
  8790. }
  8791. rotation.onChange( onRotationChange );
  8792. quaternion.onChange( onQuaternionChange );
  8793. Object.defineProperties( this, {
  8794. position: {
  8795. configurable: true,
  8796. enumerable: true,
  8797. value: position
  8798. },
  8799. rotation: {
  8800. configurable: true,
  8801. enumerable: true,
  8802. value: rotation
  8803. },
  8804. quaternion: {
  8805. configurable: true,
  8806. enumerable: true,
  8807. value: quaternion
  8808. },
  8809. scale: {
  8810. configurable: true,
  8811. enumerable: true,
  8812. value: scale
  8813. },
  8814. modelViewMatrix: {
  8815. value: new Matrix4()
  8816. },
  8817. normalMatrix: {
  8818. value: new Matrix3()
  8819. }
  8820. } );
  8821. this.matrix = new Matrix4();
  8822. this.matrixWorld = new Matrix4();
  8823. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  8824. this.matrixWorldNeedsUpdate = false;
  8825. this.layers = new Layers();
  8826. this.visible = true;
  8827. this.castShadow = false;
  8828. this.receiveShadow = false;
  8829. this.frustumCulled = true;
  8830. this.renderOrder = 0;
  8831. this.userData = {};
  8832. }
  8833. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  8834. Object3D.DefaultMatrixAutoUpdate = true;
  8835. Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  8836. constructor: Object3D,
  8837. isObject3D: true,
  8838. onBeforeRender: function () {},
  8839. onAfterRender: function () {},
  8840. applyMatrix: function ( matrix ) {
  8841. this.matrix.multiplyMatrices( matrix, this.matrix );
  8842. this.matrix.decompose( this.position, this.quaternion, this.scale );
  8843. },
  8844. applyQuaternion: function ( q ) {
  8845. this.quaternion.premultiply( q );
  8846. return this;
  8847. },
  8848. setRotationFromAxisAngle: function ( axis, angle ) {
  8849. // assumes axis is normalized
  8850. this.quaternion.setFromAxisAngle( axis, angle );
  8851. },
  8852. setRotationFromEuler: function ( euler ) {
  8853. this.quaternion.setFromEuler( euler, true );
  8854. },
  8855. setRotationFromMatrix: function ( m ) {
  8856. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  8857. this.quaternion.setFromRotationMatrix( m );
  8858. },
  8859. setRotationFromQuaternion: function ( q ) {
  8860. // assumes q is normalized
  8861. this.quaternion.copy( q );
  8862. },
  8863. rotateOnAxis: function () {
  8864. // rotate object on axis in object space
  8865. // axis is assumed to be normalized
  8866. var q1 = new Quaternion();
  8867. return function rotateOnAxis( axis, angle ) {
  8868. q1.setFromAxisAngle( axis, angle );
  8869. this.quaternion.multiply( q1 );
  8870. return this;
  8871. };
  8872. }(),
  8873. rotateOnWorldAxis: function () {
  8874. // rotate object on axis in world space
  8875. // axis is assumed to be normalized
  8876. // method assumes no rotated parent
  8877. var q1 = new Quaternion();
  8878. return function rotateOnWorldAxis( axis, angle ) {
  8879. q1.setFromAxisAngle( axis, angle );
  8880. this.quaternion.premultiply( q1 );
  8881. return this;
  8882. };
  8883. }(),
  8884. rotateX: function () {
  8885. var v1 = new Vector3( 1, 0, 0 );
  8886. return function rotateX( angle ) {
  8887. return this.rotateOnAxis( v1, angle );
  8888. };
  8889. }(),
  8890. rotateY: function () {
  8891. var v1 = new Vector3( 0, 1, 0 );
  8892. return function rotateY( angle ) {
  8893. return this.rotateOnAxis( v1, angle );
  8894. };
  8895. }(),
  8896. rotateZ: function () {
  8897. var v1 = new Vector3( 0, 0, 1 );
  8898. return function rotateZ( angle ) {
  8899. return this.rotateOnAxis( v1, angle );
  8900. };
  8901. }(),
  8902. translateOnAxis: function () {
  8903. // translate object by distance along axis in object space
  8904. // axis is assumed to be normalized
  8905. var v1 = new Vector3();
  8906. return function translateOnAxis( axis, distance ) {
  8907. v1.copy( axis ).applyQuaternion( this.quaternion );
  8908. this.position.add( v1.multiplyScalar( distance ) );
  8909. return this;
  8910. };
  8911. }(),
  8912. translateX: function () {
  8913. var v1 = new Vector3( 1, 0, 0 );
  8914. return function translateX( distance ) {
  8915. return this.translateOnAxis( v1, distance );
  8916. };
  8917. }(),
  8918. translateY: function () {
  8919. var v1 = new Vector3( 0, 1, 0 );
  8920. return function translateY( distance ) {
  8921. return this.translateOnAxis( v1, distance );
  8922. };
  8923. }(),
  8924. translateZ: function () {
  8925. var v1 = new Vector3( 0, 0, 1 );
  8926. return function translateZ( distance ) {
  8927. return this.translateOnAxis( v1, distance );
  8928. };
  8929. }(),
  8930. localToWorld: function ( vector ) {
  8931. return vector.applyMatrix4( this.matrixWorld );
  8932. },
  8933. worldToLocal: function () {
  8934. var m1 = new Matrix4();
  8935. return function worldToLocal( vector ) {
  8936. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  8937. };
  8938. }(),
  8939. lookAt: function () {
  8940. // This method does not support objects having non-uniformly-scaled parent(s)
  8941. var q1 = new Quaternion();
  8942. var m1 = new Matrix4();
  8943. var target = new Vector3();
  8944. var position = new Vector3();
  8945. return function lookAt( x, y, z ) {
  8946. if ( x.isVector3 ) {
  8947. target.copy( x );
  8948. } else {
  8949. target.set( x, y, z );
  8950. }
  8951. var parent = this.parent;
  8952. this.updateWorldMatrix( true, false );
  8953. position.setFromMatrixPosition( this.matrixWorld );
  8954. if ( this.isCamera ) {
  8955. m1.lookAt( position, target, this.up );
  8956. } else {
  8957. m1.lookAt( target, position, this.up );
  8958. }
  8959. this.quaternion.setFromRotationMatrix( m1 );
  8960. if ( parent ) {
  8961. m1.extractRotation( parent.matrixWorld );
  8962. q1.setFromRotationMatrix( m1 );
  8963. this.quaternion.premultiply( q1.inverse() );
  8964. }
  8965. };
  8966. }(),
  8967. add: function ( object ) {
  8968. if ( arguments.length > 1 ) {
  8969. for ( var i = 0; i < arguments.length; i ++ ) {
  8970. this.add( arguments[ i ] );
  8971. }
  8972. return this;
  8973. }
  8974. if ( object === this ) {
  8975. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  8976. return this;
  8977. }
  8978. if ( ( object && object.isObject3D ) ) {
  8979. if ( object.parent !== null ) {
  8980. object.parent.remove( object );
  8981. }
  8982. object.parent = this;
  8983. object.dispatchEvent( { type: 'added' } );
  8984. this.children.push( object );
  8985. } else {
  8986. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  8987. }
  8988. return this;
  8989. },
  8990. remove: function ( object ) {
  8991. if ( arguments.length > 1 ) {
  8992. for ( var i = 0; i < arguments.length; i ++ ) {
  8993. this.remove( arguments[ i ] );
  8994. }
  8995. return this;
  8996. }
  8997. var index = this.children.indexOf( object );
  8998. if ( index !== - 1 ) {
  8999. object.parent = null;
  9000. object.dispatchEvent( { type: 'removed' } );
  9001. this.children.splice( index, 1 );
  9002. }
  9003. return this;
  9004. },
  9005. getObjectById: function ( id ) {
  9006. return this.getObjectByProperty( 'id', id );
  9007. },
  9008. getObjectByName: function ( name ) {
  9009. return this.getObjectByProperty( 'name', name );
  9010. },
  9011. getObjectByProperty: function ( name, value ) {
  9012. if ( this[ name ] === value ) return this;
  9013. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  9014. var child = this.children[ i ];
  9015. var object = child.getObjectByProperty( name, value );
  9016. if ( object !== undefined ) {
  9017. return object;
  9018. }
  9019. }
  9020. return undefined;
  9021. },
  9022. getWorldPosition: function ( target ) {
  9023. if ( target === undefined ) {
  9024. console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' );
  9025. target = new Vector3();
  9026. }
  9027. this.updateMatrixWorld( true );
  9028. return target.setFromMatrixPosition( this.matrixWorld );
  9029. },
  9030. getWorldQuaternion: function () {
  9031. var position = new Vector3();
  9032. var scale = new Vector3();
  9033. return function getWorldQuaternion( target ) {
  9034. if ( target === undefined ) {
  9035. console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' );
  9036. target = new Quaternion();
  9037. }
  9038. this.updateMatrixWorld( true );
  9039. this.matrixWorld.decompose( position, target, scale );
  9040. return target;
  9041. };
  9042. }(),
  9043. getWorldScale: function () {
  9044. var position = new Vector3();
  9045. var quaternion = new Quaternion();
  9046. return function getWorldScale( target ) {
  9047. if ( target === undefined ) {
  9048. console.warn( 'THREE.Object3D: .getWorldScale() target is now required' );
  9049. target = new Vector3();
  9050. }
  9051. this.updateMatrixWorld( true );
  9052. this.matrixWorld.decompose( position, quaternion, target );
  9053. return target;
  9054. };
  9055. }(),
  9056. getWorldDirection: function ( target ) {
  9057. if ( target === undefined ) {
  9058. console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' );
  9059. target = new Vector3();
  9060. }
  9061. this.updateMatrixWorld( true );
  9062. var e = this.matrixWorld.elements;
  9063. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  9064. },
  9065. raycast: function () {},
  9066. traverse: function ( callback ) {
  9067. callback( this );
  9068. var children = this.children;
  9069. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9070. children[ i ].traverse( callback );
  9071. }
  9072. },
  9073. traverseVisible: function ( callback ) {
  9074. if ( this.visible === false ) return;
  9075. callback( this );
  9076. var children = this.children;
  9077. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9078. children[ i ].traverseVisible( callback );
  9079. }
  9080. },
  9081. traverseAncestors: function ( callback ) {
  9082. var parent = this.parent;
  9083. if ( parent !== null ) {
  9084. callback( parent );
  9085. parent.traverseAncestors( callback );
  9086. }
  9087. },
  9088. updateMatrix: function () {
  9089. this.matrix.compose( this.position, this.quaternion, this.scale );
  9090. this.matrixWorldNeedsUpdate = true;
  9091. },
  9092. updateMatrixWorld: function ( force ) {
  9093. if ( this.matrixAutoUpdate ) this.updateMatrix();
  9094. if ( this.matrixWorldNeedsUpdate || force ) {
  9095. if ( this.parent === null ) {
  9096. this.matrixWorld.copy( this.matrix );
  9097. } else {
  9098. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9099. }
  9100. this.matrixWorldNeedsUpdate = false;
  9101. force = true;
  9102. }
  9103. // update children
  9104. var children = this.children;
  9105. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9106. children[ i ].updateMatrixWorld( force );
  9107. }
  9108. },
  9109. updateWorldMatrix: function ( updateParents, updateChildren ) {
  9110. var parent = this.parent;
  9111. if ( updateParents === true && parent !== null ) {
  9112. parent.updateWorldMatrix( true, false );
  9113. }
  9114. if ( this.matrixAutoUpdate ) this.updateMatrix();
  9115. if ( this.parent === null ) {
  9116. this.matrixWorld.copy( this.matrix );
  9117. } else {
  9118. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9119. }
  9120. // update children
  9121. if ( updateChildren === true ) {
  9122. var children = this.children;
  9123. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9124. children[ i ].updateWorldMatrix( false, true );
  9125. }
  9126. }
  9127. },
  9128. toJSON: function ( meta ) {
  9129. // meta is a string when called from JSON.stringify
  9130. var isRootObject = ( meta === undefined || typeof meta === 'string' );
  9131. var output = {};
  9132. // meta is a hash used to collect geometries, materials.
  9133. // not providing it implies that this is the root object
  9134. // being serialized.
  9135. if ( isRootObject ) {
  9136. // initialize meta obj
  9137. meta = {
  9138. geometries: {},
  9139. materials: {},
  9140. textures: {},
  9141. images: {},
  9142. shapes: {}
  9143. };
  9144. output.metadata = {
  9145. version: 4.5,
  9146. type: 'Object',
  9147. generator: 'Object3D.toJSON'
  9148. };
  9149. }
  9150. // standard Object3D serialization
  9151. var object = {};
  9152. object.uuid = this.uuid;
  9153. object.type = this.type;
  9154. if ( this.name !== '' ) object.name = this.name;
  9155. if ( this.castShadow === true ) object.castShadow = true;
  9156. if ( this.receiveShadow === true ) object.receiveShadow = true;
  9157. if ( this.visible === false ) object.visible = false;
  9158. if ( this.frustumCulled === false ) object.frustumCulled = false;
  9159. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  9160. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  9161. object.layers = this.layers.mask;
  9162. object.matrix = this.matrix.toArray();
  9163. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  9164. //
  9165. function serialize( library, element ) {
  9166. if ( library[ element.uuid ] === undefined ) {
  9167. library[ element.uuid ] = element.toJSON( meta );
  9168. }
  9169. return element.uuid;
  9170. }
  9171. if ( this.isMesh || this.isLine || this.isPoints ) {
  9172. object.geometry = serialize( meta.geometries, this.geometry );
  9173. var parameters = this.geometry.parameters;
  9174. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  9175. var shapes = parameters.shapes;
  9176. if ( Array.isArray( shapes ) ) {
  9177. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  9178. var shape = shapes[ i ];
  9179. serialize( meta.shapes, shape );
  9180. }
  9181. } else {
  9182. serialize( meta.shapes, shapes );
  9183. }
  9184. }
  9185. }
  9186. if ( this.material !== undefined ) {
  9187. if ( Array.isArray( this.material ) ) {
  9188. var uuids = [];
  9189. for ( var i = 0, l = this.material.length; i < l; i ++ ) {
  9190. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  9191. }
  9192. object.material = uuids;
  9193. } else {
  9194. object.material = serialize( meta.materials, this.material );
  9195. }
  9196. }
  9197. //
  9198. if ( this.children.length > 0 ) {
  9199. object.children = [];
  9200. for ( var i = 0; i < this.children.length; i ++ ) {
  9201. object.children.push( this.children[ i ].toJSON( meta ).object );
  9202. }
  9203. }
  9204. if ( isRootObject ) {
  9205. var geometries = extractFromCache( meta.geometries );
  9206. var materials = extractFromCache( meta.materials );
  9207. var textures = extractFromCache( meta.textures );
  9208. var images = extractFromCache( meta.images );
  9209. var shapes = extractFromCache( meta.shapes );
  9210. if ( geometries.length > 0 ) output.geometries = geometries;
  9211. if ( materials.length > 0 ) output.materials = materials;
  9212. if ( textures.length > 0 ) output.textures = textures;
  9213. if ( images.length > 0 ) output.images = images;
  9214. if ( shapes.length > 0 ) output.shapes = shapes;
  9215. }
  9216. output.object = object;
  9217. return output;
  9218. // extract data from the cache hash
  9219. // remove metadata on each item
  9220. // and return as array
  9221. function extractFromCache( cache ) {
  9222. var values = [];
  9223. for ( var key in cache ) {
  9224. var data = cache[ key ];
  9225. delete data.metadata;
  9226. values.push( data );
  9227. }
  9228. return values;
  9229. }
  9230. },
  9231. clone: function ( recursive ) {
  9232. return new this.constructor().copy( this, recursive );
  9233. },
  9234. copy: function ( source, recursive ) {
  9235. if ( recursive === undefined ) recursive = true;
  9236. this.name = source.name;
  9237. this.up.copy( source.up );
  9238. this.position.copy( source.position );
  9239. this.quaternion.copy( source.quaternion );
  9240. this.scale.copy( source.scale );
  9241. this.matrix.copy( source.matrix );
  9242. this.matrixWorld.copy( source.matrixWorld );
  9243. this.matrixAutoUpdate = source.matrixAutoUpdate;
  9244. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  9245. this.layers.mask = source.layers.mask;
  9246. this.visible = source.visible;
  9247. this.castShadow = source.castShadow;
  9248. this.receiveShadow = source.receiveShadow;
  9249. this.frustumCulled = source.frustumCulled;
  9250. this.renderOrder = source.renderOrder;
  9251. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  9252. if ( recursive === true ) {
  9253. for ( var i = 0; i < source.children.length; i ++ ) {
  9254. var child = source.children[ i ];
  9255. this.add( child.clone() );
  9256. }
  9257. }
  9258. return this;
  9259. }
  9260. } );
  9261. /**
  9262. * @author mrdoob / http://mrdoob.com/
  9263. * @author kile / http://kile.stravaganza.org/
  9264. * @author alteredq / http://alteredqualia.com/
  9265. * @author mikael emtinger / http://gomo.se/
  9266. * @author zz85 / http://www.lab4games.net/zz85/blog
  9267. * @author bhouston / http://clara.io
  9268. */
  9269. var geometryId = 0; // Geometry uses even numbers as Id
  9270. function Geometry() {
  9271. Object.defineProperty( this, 'id', { value: geometryId += 2 } );
  9272. this.uuid = _Math.generateUUID();
  9273. this.name = '';
  9274. this.type = 'Geometry';
  9275. this.vertices = [];
  9276. this.colors = [];
  9277. this.faces = [];
  9278. this.faceVertexUvs = [[]];
  9279. this.morphTargets = [];
  9280. this.morphNormals = [];
  9281. this.skinWeights = [];
  9282. this.skinIndices = [];
  9283. this.lineDistances = [];
  9284. this.boundingBox = null;
  9285. this.boundingSphere = null;
  9286. // update flags
  9287. this.elementsNeedUpdate = false;
  9288. this.verticesNeedUpdate = false;
  9289. this.uvsNeedUpdate = false;
  9290. this.normalsNeedUpdate = false;
  9291. this.colorsNeedUpdate = false;
  9292. this.lineDistancesNeedUpdate = false;
  9293. this.groupsNeedUpdate = false;
  9294. }
  9295. Geometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  9296. constructor: Geometry,
  9297. isGeometry: true,
  9298. applyMatrix: function ( matrix ) {
  9299. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  9300. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  9301. var vertex = this.vertices[ i ];
  9302. vertex.applyMatrix4( matrix );
  9303. }
  9304. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  9305. var face = this.faces[ i ];
  9306. face.normal.applyMatrix3( normalMatrix ).normalize();
  9307. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  9308. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  9309. }
  9310. }
  9311. if ( this.boundingBox !== null ) {
  9312. this.computeBoundingBox();
  9313. }
  9314. if ( this.boundingSphere !== null ) {
  9315. this.computeBoundingSphere();
  9316. }
  9317. this.verticesNeedUpdate = true;
  9318. this.normalsNeedUpdate = true;
  9319. return this;
  9320. },
  9321. rotateX: function () {
  9322. // rotate geometry around world x-axis
  9323. var m1 = new Matrix4();
  9324. return function rotateX( angle ) {
  9325. m1.makeRotationX( angle );
  9326. this.applyMatrix( m1 );
  9327. return this;
  9328. };
  9329. }(),
  9330. rotateY: function () {
  9331. // rotate geometry around world y-axis
  9332. var m1 = new Matrix4();
  9333. return function rotateY( angle ) {
  9334. m1.makeRotationY( angle );
  9335. this.applyMatrix( m1 );
  9336. return this;
  9337. };
  9338. }(),
  9339. rotateZ: function () {
  9340. // rotate geometry around world z-axis
  9341. var m1 = new Matrix4();
  9342. return function rotateZ( angle ) {
  9343. m1.makeRotationZ( angle );
  9344. this.applyMatrix( m1 );
  9345. return this;
  9346. };
  9347. }(),
  9348. translate: function () {
  9349. // translate geometry
  9350. var m1 = new Matrix4();
  9351. return function translate( x, y, z ) {
  9352. m1.makeTranslation( x, y, z );
  9353. this.applyMatrix( m1 );
  9354. return this;
  9355. };
  9356. }(),
  9357. scale: function () {
  9358. // scale geometry
  9359. var m1 = new Matrix4();
  9360. return function scale( x, y, z ) {
  9361. m1.makeScale( x, y, z );
  9362. this.applyMatrix( m1 );
  9363. return this;
  9364. };
  9365. }(),
  9366. lookAt: function () {
  9367. var obj = new Object3D();
  9368. return function lookAt( vector ) {
  9369. obj.lookAt( vector );
  9370. obj.updateMatrix();
  9371. this.applyMatrix( obj.matrix );
  9372. };
  9373. }(),
  9374. fromBufferGeometry: function ( geometry ) {
  9375. var scope = this;
  9376. var indices = geometry.index !== null ? geometry.index.array : undefined;
  9377. var attributes = geometry.attributes;
  9378. var positions = attributes.position.array;
  9379. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  9380. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  9381. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  9382. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  9383. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  9384. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  9385. scope.vertices.push( new Vector3().fromArray( positions, i ) );
  9386. if ( colors !== undefined ) {
  9387. scope.colors.push( new Color().fromArray( colors, i ) );
  9388. }
  9389. }
  9390. function addFace( a, b, c, materialIndex ) {
  9391. var vertexColors = ( colors === undefined ) ? [] : [
  9392. scope.colors[ a ].clone(),
  9393. scope.colors[ b ].clone(),
  9394. scope.colors[ c ].clone() ];
  9395. var vertexNormals = ( normals === undefined ) ? [] : [
  9396. new Vector3().fromArray( normals, a * 3 ),
  9397. new Vector3().fromArray( normals, b * 3 ),
  9398. new Vector3().fromArray( normals, c * 3 )
  9399. ];
  9400. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  9401. scope.faces.push( face );
  9402. if ( uvs !== undefined ) {
  9403. scope.faceVertexUvs[ 0 ].push( [
  9404. new Vector2().fromArray( uvs, a * 2 ),
  9405. new Vector2().fromArray( uvs, b * 2 ),
  9406. new Vector2().fromArray( uvs, c * 2 )
  9407. ] );
  9408. }
  9409. if ( uvs2 !== undefined ) {
  9410. scope.faceVertexUvs[ 1 ].push( [
  9411. new Vector2().fromArray( uvs2, a * 2 ),
  9412. new Vector2().fromArray( uvs2, b * 2 ),
  9413. new Vector2().fromArray( uvs2, c * 2 )
  9414. ] );
  9415. }
  9416. }
  9417. var groups = geometry.groups;
  9418. if ( groups.length > 0 ) {
  9419. for ( var i = 0; i < groups.length; i ++ ) {
  9420. var group = groups[ i ];
  9421. var start = group.start;
  9422. var count = group.count;
  9423. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  9424. if ( indices !== undefined ) {
  9425. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  9426. } else {
  9427. addFace( j, j + 1, j + 2, group.materialIndex );
  9428. }
  9429. }
  9430. }
  9431. } else {
  9432. if ( indices !== undefined ) {
  9433. for ( var i = 0; i < indices.length; i += 3 ) {
  9434. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  9435. }
  9436. } else {
  9437. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  9438. addFace( i, i + 1, i + 2 );
  9439. }
  9440. }
  9441. }
  9442. this.computeFaceNormals();
  9443. if ( geometry.boundingBox !== null ) {
  9444. this.boundingBox = geometry.boundingBox.clone();
  9445. }
  9446. if ( geometry.boundingSphere !== null ) {
  9447. this.boundingSphere = geometry.boundingSphere.clone();
  9448. }
  9449. return this;
  9450. },
  9451. center: function () {
  9452. var offset = new Vector3();
  9453. return function center() {
  9454. this.computeBoundingBox();
  9455. this.boundingBox.getCenter( offset ).negate();
  9456. this.translate( offset.x, offset.y, offset.z );
  9457. return this;
  9458. };
  9459. }(),
  9460. normalize: function () {
  9461. this.computeBoundingSphere();
  9462. var center = this.boundingSphere.center;
  9463. var radius = this.boundingSphere.radius;
  9464. var s = radius === 0 ? 1 : 1.0 / radius;
  9465. var matrix = new Matrix4();
  9466. matrix.set(
  9467. s, 0, 0, - s * center.x,
  9468. 0, s, 0, - s * center.y,
  9469. 0, 0, s, - s * center.z,
  9470. 0, 0, 0, 1
  9471. );
  9472. this.applyMatrix( matrix );
  9473. return this;
  9474. },
  9475. computeFaceNormals: function () {
  9476. var cb = new Vector3(), ab = new Vector3();
  9477. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  9478. var face = this.faces[ f ];
  9479. var vA = this.vertices[ face.a ];
  9480. var vB = this.vertices[ face.b ];
  9481. var vC = this.vertices[ face.c ];
  9482. cb.subVectors( vC, vB );
  9483. ab.subVectors( vA, vB );
  9484. cb.cross( ab );
  9485. cb.normalize();
  9486. face.normal.copy( cb );
  9487. }
  9488. },
  9489. computeVertexNormals: function ( areaWeighted ) {
  9490. if ( areaWeighted === undefined ) areaWeighted = true;
  9491. var v, vl, f, fl, face, vertices;
  9492. vertices = new Array( this.vertices.length );
  9493. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  9494. vertices[ v ] = new Vector3();
  9495. }
  9496. if ( areaWeighted ) {
  9497. // vertex normals weighted by triangle areas
  9498. // http://www.iquilezles.org/www/articles/normals/normals.htm
  9499. var vA, vB, vC;
  9500. var cb = new Vector3(), ab = new Vector3();
  9501. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  9502. face = this.faces[ f ];
  9503. vA = this.vertices[ face.a ];
  9504. vB = this.vertices[ face.b ];
  9505. vC = this.vertices[ face.c ];
  9506. cb.subVectors( vC, vB );
  9507. ab.subVectors( vA, vB );
  9508. cb.cross( ab );
  9509. vertices[ face.a ].add( cb );
  9510. vertices[ face.b ].add( cb );
  9511. vertices[ face.c ].add( cb );
  9512. }
  9513. } else {
  9514. this.computeFaceNormals();
  9515. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  9516. face = this.faces[ f ];
  9517. vertices[ face.a ].add( face.normal );
  9518. vertices[ face.b ].add( face.normal );
  9519. vertices[ face.c ].add( face.normal );
  9520. }
  9521. }
  9522. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  9523. vertices[ v ].normalize();
  9524. }
  9525. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  9526. face = this.faces[ f ];
  9527. var vertexNormals = face.vertexNormals;
  9528. if ( vertexNormals.length === 3 ) {
  9529. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  9530. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  9531. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  9532. } else {
  9533. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  9534. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  9535. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  9536. }
  9537. }
  9538. if ( this.faces.length > 0 ) {
  9539. this.normalsNeedUpdate = true;
  9540. }
  9541. },
  9542. computeFlatVertexNormals: function () {
  9543. var f, fl, face;
  9544. this.computeFaceNormals();
  9545. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  9546. face = this.faces[ f ];
  9547. var vertexNormals = face.vertexNormals;
  9548. if ( vertexNormals.length === 3 ) {
  9549. vertexNormals[ 0 ].copy( face.normal );
  9550. vertexNormals[ 1 ].copy( face.normal );
  9551. vertexNormals[ 2 ].copy( face.normal );
  9552. } else {
  9553. vertexNormals[ 0 ] = face.normal.clone();
  9554. vertexNormals[ 1 ] = face.normal.clone();
  9555. vertexNormals[ 2 ] = face.normal.clone();
  9556. }
  9557. }
  9558. if ( this.faces.length > 0 ) {
  9559. this.normalsNeedUpdate = true;
  9560. }
  9561. },
  9562. computeMorphNormals: function () {
  9563. var i, il, f, fl, face;
  9564. // save original normals
  9565. // - create temp variables on first access
  9566. // otherwise just copy (for faster repeated calls)
  9567. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  9568. face = this.faces[ f ];
  9569. if ( ! face.__originalFaceNormal ) {
  9570. face.__originalFaceNormal = face.normal.clone();
  9571. } else {
  9572. face.__originalFaceNormal.copy( face.normal );
  9573. }
  9574. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  9575. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  9576. if ( ! face.__originalVertexNormals[ i ] ) {
  9577. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  9578. } else {
  9579. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  9580. }
  9581. }
  9582. }
  9583. // use temp geometry to compute face and vertex normals for each morph
  9584. var tmpGeo = new Geometry();
  9585. tmpGeo.faces = this.faces;
  9586. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  9587. // create on first access
  9588. if ( ! this.morphNormals[ i ] ) {
  9589. this.morphNormals[ i ] = {};
  9590. this.morphNormals[ i ].faceNormals = [];
  9591. this.morphNormals[ i ].vertexNormals = [];
  9592. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  9593. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  9594. var faceNormal, vertexNormals;
  9595. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  9596. faceNormal = new Vector3();
  9597. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  9598. dstNormalsFace.push( faceNormal );
  9599. dstNormalsVertex.push( vertexNormals );
  9600. }
  9601. }
  9602. var morphNormals = this.morphNormals[ i ];
  9603. // set vertices to morph target
  9604. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  9605. // compute morph normals
  9606. tmpGeo.computeFaceNormals();
  9607. tmpGeo.computeVertexNormals();
  9608. // store morph normals
  9609. var faceNormal, vertexNormals;
  9610. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  9611. face = this.faces[ f ];
  9612. faceNormal = morphNormals.faceNormals[ f ];
  9613. vertexNormals = morphNormals.vertexNormals[ f ];
  9614. faceNormal.copy( face.normal );
  9615. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  9616. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  9617. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  9618. }
  9619. }
  9620. // restore original normals
  9621. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  9622. face = this.faces[ f ];
  9623. face.normal = face.__originalFaceNormal;
  9624. face.vertexNormals = face.__originalVertexNormals;
  9625. }
  9626. },
  9627. computeBoundingBox: function () {
  9628. if ( this.boundingBox === null ) {
  9629. this.boundingBox = new Box3();
  9630. }
  9631. this.boundingBox.setFromPoints( this.vertices );
  9632. },
  9633. computeBoundingSphere: function () {
  9634. if ( this.boundingSphere === null ) {
  9635. this.boundingSphere = new Sphere();
  9636. }
  9637. this.boundingSphere.setFromPoints( this.vertices );
  9638. },
  9639. merge: function ( geometry, matrix, materialIndexOffset ) {
  9640. if ( ! ( geometry && geometry.isGeometry ) ) {
  9641. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  9642. return;
  9643. }
  9644. var normalMatrix,
  9645. vertexOffset = this.vertices.length,
  9646. vertices1 = this.vertices,
  9647. vertices2 = geometry.vertices,
  9648. faces1 = this.faces,
  9649. faces2 = geometry.faces,
  9650. uvs1 = this.faceVertexUvs[ 0 ],
  9651. uvs2 = geometry.faceVertexUvs[ 0 ],
  9652. colors1 = this.colors,
  9653. colors2 = geometry.colors;
  9654. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  9655. if ( matrix !== undefined ) {
  9656. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  9657. }
  9658. // vertices
  9659. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  9660. var vertex = vertices2[ i ];
  9661. var vertexCopy = vertex.clone();
  9662. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  9663. vertices1.push( vertexCopy );
  9664. }
  9665. // colors
  9666. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  9667. colors1.push( colors2[ i ].clone() );
  9668. }
  9669. // faces
  9670. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  9671. var face = faces2[ i ], faceCopy, normal, color,
  9672. faceVertexNormals = face.vertexNormals,
  9673. faceVertexColors = face.vertexColors;
  9674. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  9675. faceCopy.normal.copy( face.normal );
  9676. if ( normalMatrix !== undefined ) {
  9677. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  9678. }
  9679. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  9680. normal = faceVertexNormals[ j ].clone();
  9681. if ( normalMatrix !== undefined ) {
  9682. normal.applyMatrix3( normalMatrix ).normalize();
  9683. }
  9684. faceCopy.vertexNormals.push( normal );
  9685. }
  9686. faceCopy.color.copy( face.color );
  9687. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  9688. color = faceVertexColors[ j ];
  9689. faceCopy.vertexColors.push( color.clone() );
  9690. }
  9691. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  9692. faces1.push( faceCopy );
  9693. }
  9694. // uvs
  9695. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  9696. var uv = uvs2[ i ], uvCopy = [];
  9697. if ( uv === undefined ) {
  9698. continue;
  9699. }
  9700. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  9701. uvCopy.push( uv[ j ].clone() );
  9702. }
  9703. uvs1.push( uvCopy );
  9704. }
  9705. },
  9706. mergeMesh: function ( mesh ) {
  9707. if ( ! ( mesh && mesh.isMesh ) ) {
  9708. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  9709. return;
  9710. }
  9711. if ( mesh.matrixAutoUpdate ) mesh.updateMatrix();
  9712. this.merge( mesh.geometry, mesh.matrix );
  9713. },
  9714. /*
  9715. * Checks for duplicate vertices with hashmap.
  9716. * Duplicated vertices are removed
  9717. * and faces' vertices are updated.
  9718. */
  9719. mergeVertices: function () {
  9720. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  9721. var unique = [], changes = [];
  9722. var v, key;
  9723. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  9724. var precision = Math.pow( 10, precisionPoints );
  9725. var i, il, face;
  9726. var indices, j, jl;
  9727. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  9728. v = this.vertices[ i ];
  9729. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  9730. if ( verticesMap[ key ] === undefined ) {
  9731. verticesMap[ key ] = i;
  9732. unique.push( this.vertices[ i ] );
  9733. changes[ i ] = unique.length - 1;
  9734. } else {
  9735. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  9736. changes[ i ] = changes[ verticesMap[ key ] ];
  9737. }
  9738. }
  9739. // if faces are completely degenerate after merging vertices, we
  9740. // have to remove them from the geometry.
  9741. var faceIndicesToRemove = [];
  9742. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  9743. face = this.faces[ i ];
  9744. face.a = changes[ face.a ];
  9745. face.b = changes[ face.b ];
  9746. face.c = changes[ face.c ];
  9747. indices = [ face.a, face.b, face.c ];
  9748. // if any duplicate vertices are found in a Face3
  9749. // we have to remove the face as nothing can be saved
  9750. for ( var n = 0; n < 3; n ++ ) {
  9751. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  9752. faceIndicesToRemove.push( i );
  9753. break;
  9754. }
  9755. }
  9756. }
  9757. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  9758. var idx = faceIndicesToRemove[ i ];
  9759. this.faces.splice( idx, 1 );
  9760. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  9761. this.faceVertexUvs[ j ].splice( idx, 1 );
  9762. }
  9763. }
  9764. // Use unique set of vertices
  9765. var diff = this.vertices.length - unique.length;
  9766. this.vertices = unique;
  9767. return diff;
  9768. },
  9769. setFromPoints: function ( points ) {
  9770. this.vertices = [];
  9771. for ( var i = 0, l = points.length; i < l; i ++ ) {
  9772. var point = points[ i ];
  9773. this.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  9774. }
  9775. return this;
  9776. },
  9777. sortFacesByMaterialIndex: function () {
  9778. var faces = this.faces;
  9779. var length = faces.length;
  9780. // tag faces
  9781. for ( var i = 0; i < length; i ++ ) {
  9782. faces[ i ]._id = i;
  9783. }
  9784. // sort faces
  9785. function materialIndexSort( a, b ) {
  9786. return a.materialIndex - b.materialIndex;
  9787. }
  9788. faces.sort( materialIndexSort );
  9789. // sort uvs
  9790. var uvs1 = this.faceVertexUvs[ 0 ];
  9791. var uvs2 = this.faceVertexUvs[ 1 ];
  9792. var newUvs1, newUvs2;
  9793. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  9794. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  9795. for ( var i = 0; i < length; i ++ ) {
  9796. var id = faces[ i ]._id;
  9797. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  9798. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  9799. }
  9800. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  9801. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  9802. },
  9803. toJSON: function () {
  9804. var data = {
  9805. metadata: {
  9806. version: 4.5,
  9807. type: 'Geometry',
  9808. generator: 'Geometry.toJSON'
  9809. }
  9810. };
  9811. // standard Geometry serialization
  9812. data.uuid = this.uuid;
  9813. data.type = this.type;
  9814. if ( this.name !== '' ) data.name = this.name;
  9815. if ( this.parameters !== undefined ) {
  9816. var parameters = this.parameters;
  9817. for ( var key in parameters ) {
  9818. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  9819. }
  9820. return data;
  9821. }
  9822. var vertices = [];
  9823. for ( var i = 0; i < this.vertices.length; i ++ ) {
  9824. var vertex = this.vertices[ i ];
  9825. vertices.push( vertex.x, vertex.y, vertex.z );
  9826. }
  9827. var faces = [];
  9828. var normals = [];
  9829. var normalsHash = {};
  9830. var colors = [];
  9831. var colorsHash = {};
  9832. var uvs = [];
  9833. var uvsHash = {};
  9834. for ( var i = 0; i < this.faces.length; i ++ ) {
  9835. var face = this.faces[ i ];
  9836. var hasMaterial = true;
  9837. var hasFaceUv = false; // deprecated
  9838. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  9839. var hasFaceNormal = face.normal.length() > 0;
  9840. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  9841. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  9842. var hasFaceVertexColor = face.vertexColors.length > 0;
  9843. var faceType = 0;
  9844. faceType = setBit( faceType, 0, 0 ); // isQuad
  9845. faceType = setBit( faceType, 1, hasMaterial );
  9846. faceType = setBit( faceType, 2, hasFaceUv );
  9847. faceType = setBit( faceType, 3, hasFaceVertexUv );
  9848. faceType = setBit( faceType, 4, hasFaceNormal );
  9849. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  9850. faceType = setBit( faceType, 6, hasFaceColor );
  9851. faceType = setBit( faceType, 7, hasFaceVertexColor );
  9852. faces.push( faceType );
  9853. faces.push( face.a, face.b, face.c );
  9854. faces.push( face.materialIndex );
  9855. if ( hasFaceVertexUv ) {
  9856. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  9857. faces.push(
  9858. getUvIndex( faceVertexUvs[ 0 ] ),
  9859. getUvIndex( faceVertexUvs[ 1 ] ),
  9860. getUvIndex( faceVertexUvs[ 2 ] )
  9861. );
  9862. }
  9863. if ( hasFaceNormal ) {
  9864. faces.push( getNormalIndex( face.normal ) );
  9865. }
  9866. if ( hasFaceVertexNormal ) {
  9867. var vertexNormals = face.vertexNormals;
  9868. faces.push(
  9869. getNormalIndex( vertexNormals[ 0 ] ),
  9870. getNormalIndex( vertexNormals[ 1 ] ),
  9871. getNormalIndex( vertexNormals[ 2 ] )
  9872. );
  9873. }
  9874. if ( hasFaceColor ) {
  9875. faces.push( getColorIndex( face.color ) );
  9876. }
  9877. if ( hasFaceVertexColor ) {
  9878. var vertexColors = face.vertexColors;
  9879. faces.push(
  9880. getColorIndex( vertexColors[ 0 ] ),
  9881. getColorIndex( vertexColors[ 1 ] ),
  9882. getColorIndex( vertexColors[ 2 ] )
  9883. );
  9884. }
  9885. }
  9886. function setBit( value, position, enabled ) {
  9887. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  9888. }
  9889. function getNormalIndex( normal ) {
  9890. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  9891. if ( normalsHash[ hash ] !== undefined ) {
  9892. return normalsHash[ hash ];
  9893. }
  9894. normalsHash[ hash ] = normals.length / 3;
  9895. normals.push( normal.x, normal.y, normal.z );
  9896. return normalsHash[ hash ];
  9897. }
  9898. function getColorIndex( color ) {
  9899. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  9900. if ( colorsHash[ hash ] !== undefined ) {
  9901. return colorsHash[ hash ];
  9902. }
  9903. colorsHash[ hash ] = colors.length;
  9904. colors.push( color.getHex() );
  9905. return colorsHash[ hash ];
  9906. }
  9907. function getUvIndex( uv ) {
  9908. var hash = uv.x.toString() + uv.y.toString();
  9909. if ( uvsHash[ hash ] !== undefined ) {
  9910. return uvsHash[ hash ];
  9911. }
  9912. uvsHash[ hash ] = uvs.length / 2;
  9913. uvs.push( uv.x, uv.y );
  9914. return uvsHash[ hash ];
  9915. }
  9916. data.data = {};
  9917. data.data.vertices = vertices;
  9918. data.data.normals = normals;
  9919. if ( colors.length > 0 ) data.data.colors = colors;
  9920. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  9921. data.data.faces = faces;
  9922. return data;
  9923. },
  9924. clone: function () {
  9925. /*
  9926. // Handle primitives
  9927. var parameters = this.parameters;
  9928. if ( parameters !== undefined ) {
  9929. var values = [];
  9930. for ( var key in parameters ) {
  9931. values.push( parameters[ key ] );
  9932. }
  9933. var geometry = Object.create( this.constructor.prototype );
  9934. this.constructor.apply( geometry, values );
  9935. return geometry;
  9936. }
  9937. return new this.constructor().copy( this );
  9938. */
  9939. return new Geometry().copy( this );
  9940. },
  9941. copy: function ( source ) {
  9942. var i, il, j, jl, k, kl;
  9943. // reset
  9944. this.vertices = [];
  9945. this.colors = [];
  9946. this.faces = [];
  9947. this.faceVertexUvs = [[]];
  9948. this.morphTargets = [];
  9949. this.morphNormals = [];
  9950. this.skinWeights = [];
  9951. this.skinIndices = [];
  9952. this.lineDistances = [];
  9953. this.boundingBox = null;
  9954. this.boundingSphere = null;
  9955. // name
  9956. this.name = source.name;
  9957. // vertices
  9958. var vertices = source.vertices;
  9959. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  9960. this.vertices.push( vertices[ i ].clone() );
  9961. }
  9962. // colors
  9963. var colors = source.colors;
  9964. for ( i = 0, il = colors.length; i < il; i ++ ) {
  9965. this.colors.push( colors[ i ].clone() );
  9966. }
  9967. // faces
  9968. var faces = source.faces;
  9969. for ( i = 0, il = faces.length; i < il; i ++ ) {
  9970. this.faces.push( faces[ i ].clone() );
  9971. }
  9972. // face vertex uvs
  9973. for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  9974. var faceVertexUvs = source.faceVertexUvs[ i ];
  9975. if ( this.faceVertexUvs[ i ] === undefined ) {
  9976. this.faceVertexUvs[ i ] = [];
  9977. }
  9978. for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  9979. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  9980. for ( k = 0, kl = uvs.length; k < kl; k ++ ) {
  9981. var uv = uvs[ k ];
  9982. uvsCopy.push( uv.clone() );
  9983. }
  9984. this.faceVertexUvs[ i ].push( uvsCopy );
  9985. }
  9986. }
  9987. // morph targets
  9988. var morphTargets = source.morphTargets;
  9989. for ( i = 0, il = morphTargets.length; i < il; i ++ ) {
  9990. var morphTarget = {};
  9991. morphTarget.name = morphTargets[ i ].name;
  9992. // vertices
  9993. if ( morphTargets[ i ].vertices !== undefined ) {
  9994. morphTarget.vertices = [];
  9995. for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  9996. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  9997. }
  9998. }
  9999. // normals
  10000. if ( morphTargets[ i ].normals !== undefined ) {
  10001. morphTarget.normals = [];
  10002. for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  10003. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  10004. }
  10005. }
  10006. this.morphTargets.push( morphTarget );
  10007. }
  10008. // morph normals
  10009. var morphNormals = source.morphNormals;
  10010. for ( i = 0, il = morphNormals.length; i < il; i ++ ) {
  10011. var morphNormal = {};
  10012. // vertex normals
  10013. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  10014. morphNormal.vertexNormals = [];
  10015. for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  10016. var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  10017. var destVertexNormal = {};
  10018. destVertexNormal.a = srcVertexNormal.a.clone();
  10019. destVertexNormal.b = srcVertexNormal.b.clone();
  10020. destVertexNormal.c = srcVertexNormal.c.clone();
  10021. morphNormal.vertexNormals.push( destVertexNormal );
  10022. }
  10023. }
  10024. // face normals
  10025. if ( morphNormals[ i ].faceNormals !== undefined ) {
  10026. morphNormal.faceNormals = [];
  10027. for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  10028. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  10029. }
  10030. }
  10031. this.morphNormals.push( morphNormal );
  10032. }
  10033. // skin weights
  10034. var skinWeights = source.skinWeights;
  10035. for ( i = 0, il = skinWeights.length; i < il; i ++ ) {
  10036. this.skinWeights.push( skinWeights[ i ].clone() );
  10037. }
  10038. // skin indices
  10039. var skinIndices = source.skinIndices;
  10040. for ( i = 0, il = skinIndices.length; i < il; i ++ ) {
  10041. this.skinIndices.push( skinIndices[ i ].clone() );
  10042. }
  10043. // line distances
  10044. var lineDistances = source.lineDistances;
  10045. for ( i = 0, il = lineDistances.length; i < il; i ++ ) {
  10046. this.lineDistances.push( lineDistances[ i ] );
  10047. }
  10048. // bounding box
  10049. var boundingBox = source.boundingBox;
  10050. if ( boundingBox !== null ) {
  10051. this.boundingBox = boundingBox.clone();
  10052. }
  10053. // bounding sphere
  10054. var boundingSphere = source.boundingSphere;
  10055. if ( boundingSphere !== null ) {
  10056. this.boundingSphere = boundingSphere.clone();
  10057. }
  10058. // update flags
  10059. this.elementsNeedUpdate = source.elementsNeedUpdate;
  10060. this.verticesNeedUpdate = source.verticesNeedUpdate;
  10061. this.uvsNeedUpdate = source.uvsNeedUpdate;
  10062. this.normalsNeedUpdate = source.normalsNeedUpdate;
  10063. this.colorsNeedUpdate = source.colorsNeedUpdate;
  10064. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  10065. this.groupsNeedUpdate = source.groupsNeedUpdate;
  10066. return this;
  10067. },
  10068. dispose: function () {
  10069. this.dispatchEvent( { type: 'dispose' } );
  10070. }
  10071. } );
  10072. /**
  10073. * @author mrdoob / http://mrdoob.com/
  10074. */
  10075. function BufferAttribute( array, itemSize, normalized ) {
  10076. if ( Array.isArray( array ) ) {
  10077. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  10078. }
  10079. this.name = '';
  10080. this.array = array;
  10081. this.itemSize = itemSize;
  10082. this.count = array !== undefined ? array.length / itemSize : 0;
  10083. this.normalized = normalized === true;
  10084. this.dynamic = false;
  10085. this.updateRange = { offset: 0, count: - 1 };
  10086. this.version = 0;
  10087. }
  10088. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  10089. set: function ( value ) {
  10090. if ( value === true ) this.version ++;
  10091. }
  10092. } );
  10093. Object.assign( BufferAttribute.prototype, {
  10094. isBufferAttribute: true,
  10095. onUploadCallback: function () {},
  10096. setArray: function ( array ) {
  10097. if ( Array.isArray( array ) ) {
  10098. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  10099. }
  10100. this.count = array !== undefined ? array.length / this.itemSize : 0;
  10101. this.array = array;
  10102. return this;
  10103. },
  10104. setDynamic: function ( value ) {
  10105. this.dynamic = value;
  10106. return this;
  10107. },
  10108. copy: function ( source ) {
  10109. this.name = source.name;
  10110. this.array = new source.array.constructor( source.array );
  10111. this.itemSize = source.itemSize;
  10112. this.count = source.count;
  10113. this.normalized = source.normalized;
  10114. this.dynamic = source.dynamic;
  10115. return this;
  10116. },
  10117. copyAt: function ( index1, attribute, index2 ) {
  10118. index1 *= this.itemSize;
  10119. index2 *= attribute.itemSize;
  10120. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  10121. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  10122. }
  10123. return this;
  10124. },
  10125. copyArray: function ( array ) {
  10126. this.array.set( array );
  10127. return this;
  10128. },
  10129. copyColorsArray: function ( colors ) {
  10130. var array = this.array, offset = 0;
  10131. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  10132. var color = colors[ i ];
  10133. if ( color === undefined ) {
  10134. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  10135. color = new Color();
  10136. }
  10137. array[ offset ++ ] = color.r;
  10138. array[ offset ++ ] = color.g;
  10139. array[ offset ++ ] = color.b;
  10140. }
  10141. return this;
  10142. },
  10143. copyVector2sArray: function ( vectors ) {
  10144. var array = this.array, offset = 0;
  10145. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  10146. var vector = vectors[ i ];
  10147. if ( vector === undefined ) {
  10148. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  10149. vector = new Vector2();
  10150. }
  10151. array[ offset ++ ] = vector.x;
  10152. array[ offset ++ ] = vector.y;
  10153. }
  10154. return this;
  10155. },
  10156. copyVector3sArray: function ( vectors ) {
  10157. var array = this.array, offset = 0;
  10158. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  10159. var vector = vectors[ i ];
  10160. if ( vector === undefined ) {
  10161. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  10162. vector = new Vector3();
  10163. }
  10164. array[ offset ++ ] = vector.x;
  10165. array[ offset ++ ] = vector.y;
  10166. array[ offset ++ ] = vector.z;
  10167. }
  10168. return this;
  10169. },
  10170. copyVector4sArray: function ( vectors ) {
  10171. var array = this.array, offset = 0;
  10172. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  10173. var vector = vectors[ i ];
  10174. if ( vector === undefined ) {
  10175. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  10176. vector = new Vector4();
  10177. }
  10178. array[ offset ++ ] = vector.x;
  10179. array[ offset ++ ] = vector.y;
  10180. array[ offset ++ ] = vector.z;
  10181. array[ offset ++ ] = vector.w;
  10182. }
  10183. return this;
  10184. },
  10185. set: function ( value, offset ) {
  10186. if ( offset === undefined ) offset = 0;
  10187. this.array.set( value, offset );
  10188. return this;
  10189. },
  10190. getX: function ( index ) {
  10191. return this.array[ index * this.itemSize ];
  10192. },
  10193. setX: function ( index, x ) {
  10194. this.array[ index * this.itemSize ] = x;
  10195. return this;
  10196. },
  10197. getY: function ( index ) {
  10198. return this.array[ index * this.itemSize + 1 ];
  10199. },
  10200. setY: function ( index, y ) {
  10201. this.array[ index * this.itemSize + 1 ] = y;
  10202. return this;
  10203. },
  10204. getZ: function ( index ) {
  10205. return this.array[ index * this.itemSize + 2 ];
  10206. },
  10207. setZ: function ( index, z ) {
  10208. this.array[ index * this.itemSize + 2 ] = z;
  10209. return this;
  10210. },
  10211. getW: function ( index ) {
  10212. return this.array[ index * this.itemSize + 3 ];
  10213. },
  10214. setW: function ( index, w ) {
  10215. this.array[ index * this.itemSize + 3 ] = w;
  10216. return this;
  10217. },
  10218. setXY: function ( index, x, y ) {
  10219. index *= this.itemSize;
  10220. this.array[ index + 0 ] = x;
  10221. this.array[ index + 1 ] = y;
  10222. return this;
  10223. },
  10224. setXYZ: function ( index, x, y, z ) {
  10225. index *= this.itemSize;
  10226. this.array[ index + 0 ] = x;
  10227. this.array[ index + 1 ] = y;
  10228. this.array[ index + 2 ] = z;
  10229. return this;
  10230. },
  10231. setXYZW: function ( index, x, y, z, w ) {
  10232. index *= this.itemSize;
  10233. this.array[ index + 0 ] = x;
  10234. this.array[ index + 1 ] = y;
  10235. this.array[ index + 2 ] = z;
  10236. this.array[ index + 3 ] = w;
  10237. return this;
  10238. },
  10239. onUpload: function ( callback ) {
  10240. this.onUploadCallback = callback;
  10241. return this;
  10242. },
  10243. clone: function () {
  10244. return new this.constructor( this.array, this.itemSize ).copy( this );
  10245. }
  10246. } );
  10247. //
  10248. function Int8BufferAttribute( array, itemSize, normalized ) {
  10249. BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized );
  10250. }
  10251. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10252. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  10253. function Uint8BufferAttribute( array, itemSize, normalized ) {
  10254. BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized );
  10255. }
  10256. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10257. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  10258. function Uint8ClampedBufferAttribute( array, itemSize, normalized ) {
  10259. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized );
  10260. }
  10261. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10262. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  10263. function Int16BufferAttribute( array, itemSize, normalized ) {
  10264. BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized );
  10265. }
  10266. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10267. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  10268. function Uint16BufferAttribute( array, itemSize, normalized ) {
  10269. BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );
  10270. }
  10271. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10272. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  10273. function Int32BufferAttribute( array, itemSize, normalized ) {
  10274. BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized );
  10275. }
  10276. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10277. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  10278. function Uint32BufferAttribute( array, itemSize, normalized ) {
  10279. BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized );
  10280. }
  10281. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10282. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  10283. function Float32BufferAttribute( array, itemSize, normalized ) {
  10284. BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized );
  10285. }
  10286. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10287. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  10288. function Float64BufferAttribute( array, itemSize, normalized ) {
  10289. BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized );
  10290. }
  10291. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  10292. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  10293. /**
  10294. * @author mrdoob / http://mrdoob.com/
  10295. */
  10296. function DirectGeometry() {
  10297. this.vertices = [];
  10298. this.normals = [];
  10299. this.colors = [];
  10300. this.uvs = [];
  10301. this.uvs2 = [];
  10302. this.groups = [];
  10303. this.morphTargets = {};
  10304. this.skinWeights = [];
  10305. this.skinIndices = [];
  10306. // this.lineDistances = [];
  10307. this.boundingBox = null;
  10308. this.boundingSphere = null;
  10309. // update flags
  10310. this.verticesNeedUpdate = false;
  10311. this.normalsNeedUpdate = false;
  10312. this.colorsNeedUpdate = false;
  10313. this.uvsNeedUpdate = false;
  10314. this.groupsNeedUpdate = false;
  10315. }
  10316. Object.assign( DirectGeometry.prototype, {
  10317. computeGroups: function ( geometry ) {
  10318. var group;
  10319. var groups = [];
  10320. var materialIndex = undefined;
  10321. var faces = geometry.faces;
  10322. for ( var i = 0; i < faces.length; i ++ ) {
  10323. var face = faces[ i ];
  10324. // materials
  10325. if ( face.materialIndex !== materialIndex ) {
  10326. materialIndex = face.materialIndex;
  10327. if ( group !== undefined ) {
  10328. group.count = ( i * 3 ) - group.start;
  10329. groups.push( group );
  10330. }
  10331. group = {
  10332. start: i * 3,
  10333. materialIndex: materialIndex
  10334. };
  10335. }
  10336. }
  10337. if ( group !== undefined ) {
  10338. group.count = ( i * 3 ) - group.start;
  10339. groups.push( group );
  10340. }
  10341. this.groups = groups;
  10342. },
  10343. fromGeometry: function ( geometry ) {
  10344. var faces = geometry.faces;
  10345. var vertices = geometry.vertices;
  10346. var faceVertexUvs = geometry.faceVertexUvs;
  10347. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  10348. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  10349. // morphs
  10350. var morphTargets = geometry.morphTargets;
  10351. var morphTargetsLength = morphTargets.length;
  10352. var morphTargetsPosition;
  10353. if ( morphTargetsLength > 0 ) {
  10354. morphTargetsPosition = [];
  10355. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  10356. morphTargetsPosition[ i ] = {
  10357. name: morphTargets[ i ].name,
  10358. data: []
  10359. };
  10360. }
  10361. this.morphTargets.position = morphTargetsPosition;
  10362. }
  10363. var morphNormals = geometry.morphNormals;
  10364. var morphNormalsLength = morphNormals.length;
  10365. var morphTargetsNormal;
  10366. if ( morphNormalsLength > 0 ) {
  10367. morphTargetsNormal = [];
  10368. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  10369. morphTargetsNormal[ i ] = {
  10370. name: morphNormals[ i ].name,
  10371. data: []
  10372. };
  10373. }
  10374. this.morphTargets.normal = morphTargetsNormal;
  10375. }
  10376. // skins
  10377. var skinIndices = geometry.skinIndices;
  10378. var skinWeights = geometry.skinWeights;
  10379. var hasSkinIndices = skinIndices.length === vertices.length;
  10380. var hasSkinWeights = skinWeights.length === vertices.length;
  10381. //
  10382. if ( vertices.length > 0 && faces.length === 0 ) {
  10383. console.error( 'THREE.DirectGeometry: Faceless geometries are not supported.' );
  10384. }
  10385. for ( var i = 0; i < faces.length; i ++ ) {
  10386. var face = faces[ i ];
  10387. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  10388. var vertexNormals = face.vertexNormals;
  10389. if ( vertexNormals.length === 3 ) {
  10390. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  10391. } else {
  10392. var normal = face.normal;
  10393. this.normals.push( normal, normal, normal );
  10394. }
  10395. var vertexColors = face.vertexColors;
  10396. if ( vertexColors.length === 3 ) {
  10397. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  10398. } else {
  10399. var color = face.color;
  10400. this.colors.push( color, color, color );
  10401. }
  10402. if ( hasFaceVertexUv === true ) {
  10403. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  10404. if ( vertexUvs !== undefined ) {
  10405. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  10406. } else {
  10407. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  10408. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  10409. }
  10410. }
  10411. if ( hasFaceVertexUv2 === true ) {
  10412. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  10413. if ( vertexUvs !== undefined ) {
  10414. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  10415. } else {
  10416. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  10417. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  10418. }
  10419. }
  10420. // morphs
  10421. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  10422. var morphTarget = morphTargets[ j ].vertices;
  10423. morphTargetsPosition[ j ].data.push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  10424. }
  10425. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  10426. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  10427. morphTargetsNormal[ j ].data.push( morphNormal.a, morphNormal.b, morphNormal.c );
  10428. }
  10429. // skins
  10430. if ( hasSkinIndices ) {
  10431. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  10432. }
  10433. if ( hasSkinWeights ) {
  10434. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  10435. }
  10436. }
  10437. this.computeGroups( geometry );
  10438. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  10439. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  10440. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  10441. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  10442. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  10443. return this;
  10444. }
  10445. } );
  10446. /**
  10447. * @author mrdoob / http://mrdoob.com/
  10448. */
  10449. function arrayMax( array ) {
  10450. if ( array.length === 0 ) return - Infinity;
  10451. var max = array[ 0 ];
  10452. for ( var i = 1, l = array.length; i < l; ++ i ) {
  10453. if ( array[ i ] > max ) max = array[ i ];
  10454. }
  10455. return max;
  10456. }
  10457. /**
  10458. * @author alteredq / http://alteredqualia.com/
  10459. * @author mrdoob / http://mrdoob.com/
  10460. */
  10461. var bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  10462. function BufferGeometry() {
  10463. Object.defineProperty( this, 'id', { value: bufferGeometryId += 2 } );
  10464. this.uuid = _Math.generateUUID();
  10465. this.name = '';
  10466. this.type = 'BufferGeometry';
  10467. this.index = null;
  10468. this.attributes = {};
  10469. this.morphAttributes = {};
  10470. this.groups = [];
  10471. this.boundingBox = null;
  10472. this.boundingSphere = null;
  10473. this.drawRange = { start: 0, count: Infinity };
  10474. this.userData = {};
  10475. }
  10476. BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  10477. constructor: BufferGeometry,
  10478. isBufferGeometry: true,
  10479. getIndex: function () {
  10480. return this.index;
  10481. },
  10482. setIndex: function ( index ) {
  10483. if ( Array.isArray( index ) ) {
  10484. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  10485. } else {
  10486. this.index = index;
  10487. }
  10488. },
  10489. addAttribute: function ( name, attribute ) {
  10490. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  10491. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  10492. return this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  10493. }
  10494. if ( name === 'index' ) {
  10495. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  10496. this.setIndex( attribute );
  10497. return this;
  10498. }
  10499. this.attributes[ name ] = attribute;
  10500. return this;
  10501. },
  10502. getAttribute: function ( name ) {
  10503. return this.attributes[ name ];
  10504. },
  10505. removeAttribute: function ( name ) {
  10506. delete this.attributes[ name ];
  10507. return this;
  10508. },
  10509. addGroup: function ( start, count, materialIndex ) {
  10510. this.groups.push( {
  10511. start: start,
  10512. count: count,
  10513. materialIndex: materialIndex !== undefined ? materialIndex : 0
  10514. } );
  10515. },
  10516. clearGroups: function () {
  10517. this.groups = [];
  10518. },
  10519. setDrawRange: function ( start, count ) {
  10520. this.drawRange.start = start;
  10521. this.drawRange.count = count;
  10522. },
  10523. applyMatrix: function ( matrix ) {
  10524. var position = this.attributes.position;
  10525. if ( position !== undefined ) {
  10526. matrix.applyToBufferAttribute( position );
  10527. position.needsUpdate = true;
  10528. }
  10529. var normal = this.attributes.normal;
  10530. if ( normal !== undefined ) {
  10531. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  10532. normalMatrix.applyToBufferAttribute( normal );
  10533. normal.needsUpdate = true;
  10534. }
  10535. if ( this.boundingBox !== null ) {
  10536. this.computeBoundingBox();
  10537. }
  10538. if ( this.boundingSphere !== null ) {
  10539. this.computeBoundingSphere();
  10540. }
  10541. return this;
  10542. },
  10543. rotateX: function () {
  10544. // rotate geometry around world x-axis
  10545. var m1 = new Matrix4();
  10546. return function rotateX( angle ) {
  10547. m1.makeRotationX( angle );
  10548. this.applyMatrix( m1 );
  10549. return this;
  10550. };
  10551. }(),
  10552. rotateY: function () {
  10553. // rotate geometry around world y-axis
  10554. var m1 = new Matrix4();
  10555. return function rotateY( angle ) {
  10556. m1.makeRotationY( angle );
  10557. this.applyMatrix( m1 );
  10558. return this;
  10559. };
  10560. }(),
  10561. rotateZ: function () {
  10562. // rotate geometry around world z-axis
  10563. var m1 = new Matrix4();
  10564. return function rotateZ( angle ) {
  10565. m1.makeRotationZ( angle );
  10566. this.applyMatrix( m1 );
  10567. return this;
  10568. };
  10569. }(),
  10570. translate: function () {
  10571. // translate geometry
  10572. var m1 = new Matrix4();
  10573. return function translate( x, y, z ) {
  10574. m1.makeTranslation( x, y, z );
  10575. this.applyMatrix( m1 );
  10576. return this;
  10577. };
  10578. }(),
  10579. scale: function () {
  10580. // scale geometry
  10581. var m1 = new Matrix4();
  10582. return function scale( x, y, z ) {
  10583. m1.makeScale( x, y, z );
  10584. this.applyMatrix( m1 );
  10585. return this;
  10586. };
  10587. }(),
  10588. lookAt: function () {
  10589. var obj = new Object3D();
  10590. return function lookAt( vector ) {
  10591. obj.lookAt( vector );
  10592. obj.updateMatrix();
  10593. this.applyMatrix( obj.matrix );
  10594. };
  10595. }(),
  10596. center: function () {
  10597. var offset = new Vector3();
  10598. return function center() {
  10599. this.computeBoundingBox();
  10600. this.boundingBox.getCenter( offset ).negate();
  10601. this.translate( offset.x, offset.y, offset.z );
  10602. return this;
  10603. };
  10604. }(),
  10605. setFromObject: function ( object ) {
  10606. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  10607. var geometry = object.geometry;
  10608. if ( object.isPoints || object.isLine ) {
  10609. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  10610. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  10611. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  10612. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  10613. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  10614. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  10615. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  10616. }
  10617. if ( geometry.boundingSphere !== null ) {
  10618. this.boundingSphere = geometry.boundingSphere.clone();
  10619. }
  10620. if ( geometry.boundingBox !== null ) {
  10621. this.boundingBox = geometry.boundingBox.clone();
  10622. }
  10623. } else if ( object.isMesh ) {
  10624. if ( geometry && geometry.isGeometry ) {
  10625. this.fromGeometry( geometry );
  10626. }
  10627. }
  10628. return this;
  10629. },
  10630. setFromPoints: function ( points ) {
  10631. var position = [];
  10632. for ( var i = 0, l = points.length; i < l; i ++ ) {
  10633. var point = points[ i ];
  10634. position.push( point.x, point.y, point.z || 0 );
  10635. }
  10636. this.addAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  10637. return this;
  10638. },
  10639. updateFromObject: function ( object ) {
  10640. var geometry = object.geometry;
  10641. if ( object.isMesh ) {
  10642. var direct = geometry.__directGeometry;
  10643. if ( geometry.elementsNeedUpdate === true ) {
  10644. direct = undefined;
  10645. geometry.elementsNeedUpdate = false;
  10646. }
  10647. if ( direct === undefined ) {
  10648. return this.fromGeometry( geometry );
  10649. }
  10650. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  10651. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  10652. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  10653. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  10654. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  10655. geometry.verticesNeedUpdate = false;
  10656. geometry.normalsNeedUpdate = false;
  10657. geometry.colorsNeedUpdate = false;
  10658. geometry.uvsNeedUpdate = false;
  10659. geometry.groupsNeedUpdate = false;
  10660. geometry = direct;
  10661. }
  10662. var attribute;
  10663. if ( geometry.verticesNeedUpdate === true ) {
  10664. attribute = this.attributes.position;
  10665. if ( attribute !== undefined ) {
  10666. attribute.copyVector3sArray( geometry.vertices );
  10667. attribute.needsUpdate = true;
  10668. }
  10669. geometry.verticesNeedUpdate = false;
  10670. }
  10671. if ( geometry.normalsNeedUpdate === true ) {
  10672. attribute = this.attributes.normal;
  10673. if ( attribute !== undefined ) {
  10674. attribute.copyVector3sArray( geometry.normals );
  10675. attribute.needsUpdate = true;
  10676. }
  10677. geometry.normalsNeedUpdate = false;
  10678. }
  10679. if ( geometry.colorsNeedUpdate === true ) {
  10680. attribute = this.attributes.color;
  10681. if ( attribute !== undefined ) {
  10682. attribute.copyColorsArray( geometry.colors );
  10683. attribute.needsUpdate = true;
  10684. }
  10685. geometry.colorsNeedUpdate = false;
  10686. }
  10687. if ( geometry.uvsNeedUpdate ) {
  10688. attribute = this.attributes.uv;
  10689. if ( attribute !== undefined ) {
  10690. attribute.copyVector2sArray( geometry.uvs );
  10691. attribute.needsUpdate = true;
  10692. }
  10693. geometry.uvsNeedUpdate = false;
  10694. }
  10695. if ( geometry.lineDistancesNeedUpdate ) {
  10696. attribute = this.attributes.lineDistance;
  10697. if ( attribute !== undefined ) {
  10698. attribute.copyArray( geometry.lineDistances );
  10699. attribute.needsUpdate = true;
  10700. }
  10701. geometry.lineDistancesNeedUpdate = false;
  10702. }
  10703. if ( geometry.groupsNeedUpdate ) {
  10704. geometry.computeGroups( object.geometry );
  10705. this.groups = geometry.groups;
  10706. geometry.groupsNeedUpdate = false;
  10707. }
  10708. return this;
  10709. },
  10710. fromGeometry: function ( geometry ) {
  10711. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  10712. return this.fromDirectGeometry( geometry.__directGeometry );
  10713. },
  10714. fromDirectGeometry: function ( geometry ) {
  10715. var positions = new Float32Array( geometry.vertices.length * 3 );
  10716. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  10717. if ( geometry.normals.length > 0 ) {
  10718. var normals = new Float32Array( geometry.normals.length * 3 );
  10719. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  10720. }
  10721. if ( geometry.colors.length > 0 ) {
  10722. var colors = new Float32Array( geometry.colors.length * 3 );
  10723. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  10724. }
  10725. if ( geometry.uvs.length > 0 ) {
  10726. var uvs = new Float32Array( geometry.uvs.length * 2 );
  10727. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  10728. }
  10729. if ( geometry.uvs2.length > 0 ) {
  10730. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  10731. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  10732. }
  10733. // groups
  10734. this.groups = geometry.groups;
  10735. // morphs
  10736. for ( var name in geometry.morphTargets ) {
  10737. var array = [];
  10738. var morphTargets = geometry.morphTargets[ name ];
  10739. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  10740. var morphTarget = morphTargets[ i ];
  10741. var attribute = new Float32BufferAttribute( morphTarget.data.length * 3, 3 );
  10742. attribute.name = morphTarget.name;
  10743. array.push( attribute.copyVector3sArray( morphTarget.data ) );
  10744. }
  10745. this.morphAttributes[ name ] = array;
  10746. }
  10747. // skinning
  10748. if ( geometry.skinIndices.length > 0 ) {
  10749. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  10750. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  10751. }
  10752. if ( geometry.skinWeights.length > 0 ) {
  10753. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  10754. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  10755. }
  10756. //
  10757. if ( geometry.boundingSphere !== null ) {
  10758. this.boundingSphere = geometry.boundingSphere.clone();
  10759. }
  10760. if ( geometry.boundingBox !== null ) {
  10761. this.boundingBox = geometry.boundingBox.clone();
  10762. }
  10763. return this;
  10764. },
  10765. computeBoundingBox: function () {
  10766. if ( this.boundingBox === null ) {
  10767. this.boundingBox = new Box3();
  10768. }
  10769. var position = this.attributes.position;
  10770. if ( position !== undefined ) {
  10771. this.boundingBox.setFromBufferAttribute( position );
  10772. } else {
  10773. this.boundingBox.makeEmpty();
  10774. }
  10775. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  10776. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  10777. }
  10778. },
  10779. computeBoundingSphere: function () {
  10780. var box = new Box3();
  10781. var vector = new Vector3();
  10782. return function computeBoundingSphere() {
  10783. if ( this.boundingSphere === null ) {
  10784. this.boundingSphere = new Sphere();
  10785. }
  10786. var position = this.attributes.position;
  10787. if ( position ) {
  10788. var center = this.boundingSphere.center;
  10789. box.setFromBufferAttribute( position );
  10790. box.getCenter( center );
  10791. // hoping to find a boundingSphere with a radius smaller than the
  10792. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  10793. var maxRadiusSq = 0;
  10794. for ( var i = 0, il = position.count; i < il; i ++ ) {
  10795. vector.x = position.getX( i );
  10796. vector.y = position.getY( i );
  10797. vector.z = position.getZ( i );
  10798. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  10799. }
  10800. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  10801. if ( isNaN( this.boundingSphere.radius ) ) {
  10802. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  10803. }
  10804. }
  10805. };
  10806. }(),
  10807. computeFaceNormals: function () {
  10808. // backwards compatibility
  10809. },
  10810. computeVertexNormals: function () {
  10811. var index = this.index;
  10812. var attributes = this.attributes;
  10813. if ( attributes.position ) {
  10814. var positions = attributes.position.array;
  10815. if ( attributes.normal === undefined ) {
  10816. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  10817. } else {
  10818. // reset existing normals to zero
  10819. var array = attributes.normal.array;
  10820. for ( var i = 0, il = array.length; i < il; i ++ ) {
  10821. array[ i ] = 0;
  10822. }
  10823. }
  10824. var normals = attributes.normal.array;
  10825. var vA, vB, vC;
  10826. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  10827. var cb = new Vector3(), ab = new Vector3();
  10828. // indexed elements
  10829. if ( index ) {
  10830. var indices = index.array;
  10831. for ( var i = 0, il = index.count; i < il; i += 3 ) {
  10832. vA = indices[ i + 0 ] * 3;
  10833. vB = indices[ i + 1 ] * 3;
  10834. vC = indices[ i + 2 ] * 3;
  10835. pA.fromArray( positions, vA );
  10836. pB.fromArray( positions, vB );
  10837. pC.fromArray( positions, vC );
  10838. cb.subVectors( pC, pB );
  10839. ab.subVectors( pA, pB );
  10840. cb.cross( ab );
  10841. normals[ vA ] += cb.x;
  10842. normals[ vA + 1 ] += cb.y;
  10843. normals[ vA + 2 ] += cb.z;
  10844. normals[ vB ] += cb.x;
  10845. normals[ vB + 1 ] += cb.y;
  10846. normals[ vB + 2 ] += cb.z;
  10847. normals[ vC ] += cb.x;
  10848. normals[ vC + 1 ] += cb.y;
  10849. normals[ vC + 2 ] += cb.z;
  10850. }
  10851. } else {
  10852. // non-indexed elements (unconnected triangle soup)
  10853. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  10854. pA.fromArray( positions, i );
  10855. pB.fromArray( positions, i + 3 );
  10856. pC.fromArray( positions, i + 6 );
  10857. cb.subVectors( pC, pB );
  10858. ab.subVectors( pA, pB );
  10859. cb.cross( ab );
  10860. normals[ i ] = cb.x;
  10861. normals[ i + 1 ] = cb.y;
  10862. normals[ i + 2 ] = cb.z;
  10863. normals[ i + 3 ] = cb.x;
  10864. normals[ i + 4 ] = cb.y;
  10865. normals[ i + 5 ] = cb.z;
  10866. normals[ i + 6 ] = cb.x;
  10867. normals[ i + 7 ] = cb.y;
  10868. normals[ i + 8 ] = cb.z;
  10869. }
  10870. }
  10871. this.normalizeNormals();
  10872. attributes.normal.needsUpdate = true;
  10873. }
  10874. },
  10875. merge: function ( geometry, offset ) {
  10876. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  10877. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  10878. return;
  10879. }
  10880. if ( offset === undefined ) {
  10881. offset = 0;
  10882. console.warn(
  10883. 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
  10884. + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
  10885. );
  10886. }
  10887. var attributes = this.attributes;
  10888. for ( var key in attributes ) {
  10889. if ( geometry.attributes[ key ] === undefined ) continue;
  10890. var attribute1 = attributes[ key ];
  10891. var attributeArray1 = attribute1.array;
  10892. var attribute2 = geometry.attributes[ key ];
  10893. var attributeArray2 = attribute2.array;
  10894. var attributeSize = attribute2.itemSize;
  10895. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  10896. attributeArray1[ j ] = attributeArray2[ i ];
  10897. }
  10898. }
  10899. return this;
  10900. },
  10901. normalizeNormals: function () {
  10902. var vector = new Vector3();
  10903. return function normalizeNormals() {
  10904. var normals = this.attributes.normal;
  10905. for ( var i = 0, il = normals.count; i < il; i ++ ) {
  10906. vector.x = normals.getX( i );
  10907. vector.y = normals.getY( i );
  10908. vector.z = normals.getZ( i );
  10909. vector.normalize();
  10910. normals.setXYZ( i, vector.x, vector.y, vector.z );
  10911. }
  10912. };
  10913. }(),
  10914. toNonIndexed: function () {
  10915. if ( this.index === null ) {
  10916. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  10917. return this;
  10918. }
  10919. var geometry2 = new BufferGeometry();
  10920. var indices = this.index.array;
  10921. var attributes = this.attributes;
  10922. for ( var name in attributes ) {
  10923. var attribute = attributes[ name ];
  10924. var array = attribute.array;
  10925. var itemSize = attribute.itemSize;
  10926. var array2 = new array.constructor( indices.length * itemSize );
  10927. var index = 0, index2 = 0;
  10928. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  10929. index = indices[ i ] * itemSize;
  10930. for ( var j = 0; j < itemSize; j ++ ) {
  10931. array2[ index2 ++ ] = array[ index ++ ];
  10932. }
  10933. }
  10934. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  10935. }
  10936. var groups = this.groups;
  10937. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  10938. var group = groups[ i ];
  10939. geometry2.addGroup( group.start, group.count, group.materialIndex );
  10940. }
  10941. return geometry2;
  10942. },
  10943. toJSON: function () {
  10944. var data = {
  10945. metadata: {
  10946. version: 4.5,
  10947. type: 'BufferGeometry',
  10948. generator: 'BufferGeometry.toJSON'
  10949. }
  10950. };
  10951. // standard BufferGeometry serialization
  10952. data.uuid = this.uuid;
  10953. data.type = this.type;
  10954. if ( this.name !== '' ) data.name = this.name;
  10955. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  10956. if ( this.parameters !== undefined ) {
  10957. var parameters = this.parameters;
  10958. for ( var key in parameters ) {
  10959. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  10960. }
  10961. return data;
  10962. }
  10963. data.data = { attributes: {} };
  10964. var index = this.index;
  10965. if ( index !== null ) {
  10966. var array = Array.prototype.slice.call( index.array );
  10967. data.data.index = {
  10968. type: index.array.constructor.name,
  10969. array: array
  10970. };
  10971. }
  10972. var attributes = this.attributes;
  10973. for ( var key in attributes ) {
  10974. var attribute = attributes[ key ];
  10975. var array = Array.prototype.slice.call( attribute.array );
  10976. data.data.attributes[ key ] = {
  10977. itemSize: attribute.itemSize,
  10978. type: attribute.array.constructor.name,
  10979. array: array,
  10980. normalized: attribute.normalized
  10981. };
  10982. }
  10983. var groups = this.groups;
  10984. if ( groups.length > 0 ) {
  10985. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  10986. }
  10987. var boundingSphere = this.boundingSphere;
  10988. if ( boundingSphere !== null ) {
  10989. data.data.boundingSphere = {
  10990. center: boundingSphere.center.toArray(),
  10991. radius: boundingSphere.radius
  10992. };
  10993. }
  10994. return data;
  10995. },
  10996. clone: function () {
  10997. /*
  10998. // Handle primitives
  10999. var parameters = this.parameters;
  11000. if ( parameters !== undefined ) {
  11001. var values = [];
  11002. for ( var key in parameters ) {
  11003. values.push( parameters[ key ] );
  11004. }
  11005. var geometry = Object.create( this.constructor.prototype );
  11006. this.constructor.apply( geometry, values );
  11007. return geometry;
  11008. }
  11009. return new this.constructor().copy( this );
  11010. */
  11011. return new BufferGeometry().copy( this );
  11012. },
  11013. copy: function ( source ) {
  11014. var name, i, l;
  11015. // reset
  11016. this.index = null;
  11017. this.attributes = {};
  11018. this.morphAttributes = {};
  11019. this.groups = [];
  11020. this.boundingBox = null;
  11021. this.boundingSphere = null;
  11022. // name
  11023. this.name = source.name;
  11024. // index
  11025. var index = source.index;
  11026. if ( index !== null ) {
  11027. this.setIndex( index.clone() );
  11028. }
  11029. // attributes
  11030. var attributes = source.attributes;
  11031. for ( name in attributes ) {
  11032. var attribute = attributes[ name ];
  11033. this.addAttribute( name, attribute.clone() );
  11034. }
  11035. // morph attributes
  11036. var morphAttributes = source.morphAttributes;
  11037. for ( name in morphAttributes ) {
  11038. var array = [];
  11039. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  11040. for ( i = 0, l = morphAttribute.length; i < l; i ++ ) {
  11041. array.push( morphAttribute[ i ].clone() );
  11042. }
  11043. this.morphAttributes[ name ] = array;
  11044. }
  11045. // groups
  11046. var groups = source.groups;
  11047. for ( i = 0, l = groups.length; i < l; i ++ ) {
  11048. var group = groups[ i ];
  11049. this.addGroup( group.start, group.count, group.materialIndex );
  11050. }
  11051. // bounding box
  11052. var boundingBox = source.boundingBox;
  11053. if ( boundingBox !== null ) {
  11054. this.boundingBox = boundingBox.clone();
  11055. }
  11056. // bounding sphere
  11057. var boundingSphere = source.boundingSphere;
  11058. if ( boundingSphere !== null ) {
  11059. this.boundingSphere = boundingSphere.clone();
  11060. }
  11061. // draw range
  11062. this.drawRange.start = source.drawRange.start;
  11063. this.drawRange.count = source.drawRange.count;
  11064. // user data
  11065. this.userData = source.userData;
  11066. return this;
  11067. },
  11068. dispose: function () {
  11069. this.dispatchEvent( { type: 'dispose' } );
  11070. }
  11071. } );
  11072. /**
  11073. * @author mrdoob / http://mrdoob.com/
  11074. * @author Mugen87 / https://github.com/Mugen87
  11075. */
  11076. // BoxGeometry
  11077. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  11078. Geometry.call( this );
  11079. this.type = 'BoxGeometry';
  11080. this.parameters = {
  11081. width: width,
  11082. height: height,
  11083. depth: depth,
  11084. widthSegments: widthSegments,
  11085. heightSegments: heightSegments,
  11086. depthSegments: depthSegments
  11087. };
  11088. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  11089. this.mergeVertices();
  11090. }
  11091. BoxGeometry.prototype = Object.create( Geometry.prototype );
  11092. BoxGeometry.prototype.constructor = BoxGeometry;
  11093. // BoxBufferGeometry
  11094. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  11095. BufferGeometry.call( this );
  11096. this.type = 'BoxBufferGeometry';
  11097. this.parameters = {
  11098. width: width,
  11099. height: height,
  11100. depth: depth,
  11101. widthSegments: widthSegments,
  11102. heightSegments: heightSegments,
  11103. depthSegments: depthSegments
  11104. };
  11105. var scope = this;
  11106. width = width || 1;
  11107. height = height || 1;
  11108. depth = depth || 1;
  11109. // segments
  11110. widthSegments = Math.floor( widthSegments ) || 1;
  11111. heightSegments = Math.floor( heightSegments ) || 1;
  11112. depthSegments = Math.floor( depthSegments ) || 1;
  11113. // buffers
  11114. var indices = [];
  11115. var vertices = [];
  11116. var normals = [];
  11117. var uvs = [];
  11118. // helper variables
  11119. var numberOfVertices = 0;
  11120. var groupStart = 0;
  11121. // build each side of the box geometry
  11122. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  11123. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  11124. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  11125. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  11126. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  11127. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  11128. // build geometry
  11129. this.setIndex( indices );
  11130. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11131. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11132. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11133. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  11134. var segmentWidth = width / gridX;
  11135. var segmentHeight = height / gridY;
  11136. var widthHalf = width / 2;
  11137. var heightHalf = height / 2;
  11138. var depthHalf = depth / 2;
  11139. var gridX1 = gridX + 1;
  11140. var gridY1 = gridY + 1;
  11141. var vertexCounter = 0;
  11142. var groupCount = 0;
  11143. var ix, iy;
  11144. var vector = new Vector3();
  11145. // generate vertices, normals and uvs
  11146. for ( iy = 0; iy < gridY1; iy ++ ) {
  11147. var y = iy * segmentHeight - heightHalf;
  11148. for ( ix = 0; ix < gridX1; ix ++ ) {
  11149. var x = ix * segmentWidth - widthHalf;
  11150. // set values to correct vector component
  11151. vector[ u ] = x * udir;
  11152. vector[ v ] = y * vdir;
  11153. vector[ w ] = depthHalf;
  11154. // now apply vector to vertex buffer
  11155. vertices.push( vector.x, vector.y, vector.z );
  11156. // set values to correct vector component
  11157. vector[ u ] = 0;
  11158. vector[ v ] = 0;
  11159. vector[ w ] = depth > 0 ? 1 : - 1;
  11160. // now apply vector to normal buffer
  11161. normals.push( vector.x, vector.y, vector.z );
  11162. // uvs
  11163. uvs.push( ix / gridX );
  11164. uvs.push( 1 - ( iy / gridY ) );
  11165. // counters
  11166. vertexCounter += 1;
  11167. }
  11168. }
  11169. // indices
  11170. // 1. you need three indices to draw a single face
  11171. // 2. a single segment consists of two faces
  11172. // 3. so we need to generate six (2*3) indices per segment
  11173. for ( iy = 0; iy < gridY; iy ++ ) {
  11174. for ( ix = 0; ix < gridX; ix ++ ) {
  11175. var a = numberOfVertices + ix + gridX1 * iy;
  11176. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  11177. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  11178. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  11179. // faces
  11180. indices.push( a, b, d );
  11181. indices.push( b, c, d );
  11182. // increase counter
  11183. groupCount += 6;
  11184. }
  11185. }
  11186. // add a group to the geometry. this will ensure multi material support
  11187. scope.addGroup( groupStart, groupCount, materialIndex );
  11188. // calculate new start value for groups
  11189. groupStart += groupCount;
  11190. // update total number of vertices
  11191. numberOfVertices += vertexCounter;
  11192. }
  11193. }
  11194. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  11195. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  11196. /**
  11197. * @author mrdoob / http://mrdoob.com/
  11198. * @author Mugen87 / https://github.com/Mugen87
  11199. */
  11200. // PlaneGeometry
  11201. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  11202. Geometry.call( this );
  11203. this.type = 'PlaneGeometry';
  11204. this.parameters = {
  11205. width: width,
  11206. height: height,
  11207. widthSegments: widthSegments,
  11208. heightSegments: heightSegments
  11209. };
  11210. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  11211. this.mergeVertices();
  11212. }
  11213. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  11214. PlaneGeometry.prototype.constructor = PlaneGeometry;
  11215. // PlaneBufferGeometry
  11216. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  11217. BufferGeometry.call( this );
  11218. this.type = 'PlaneBufferGeometry';
  11219. this.parameters = {
  11220. width: width,
  11221. height: height,
  11222. widthSegments: widthSegments,
  11223. heightSegments: heightSegments
  11224. };
  11225. width = width || 1;
  11226. height = height || 1;
  11227. var width_half = width / 2;
  11228. var height_half = height / 2;
  11229. var gridX = Math.floor( widthSegments ) || 1;
  11230. var gridY = Math.floor( heightSegments ) || 1;
  11231. var gridX1 = gridX + 1;
  11232. var gridY1 = gridY + 1;
  11233. var segment_width = width / gridX;
  11234. var segment_height = height / gridY;
  11235. var ix, iy;
  11236. // buffers
  11237. var indices = [];
  11238. var vertices = [];
  11239. var normals = [];
  11240. var uvs = [];
  11241. // generate vertices, normals and uvs
  11242. for ( iy = 0; iy < gridY1; iy ++ ) {
  11243. var y = iy * segment_height - height_half;
  11244. for ( ix = 0; ix < gridX1; ix ++ ) {
  11245. var x = ix * segment_width - width_half;
  11246. vertices.push( x, - y, 0 );
  11247. normals.push( 0, 0, 1 );
  11248. uvs.push( ix / gridX );
  11249. uvs.push( 1 - ( iy / gridY ) );
  11250. }
  11251. }
  11252. // indices
  11253. for ( iy = 0; iy < gridY; iy ++ ) {
  11254. for ( ix = 0; ix < gridX; ix ++ ) {
  11255. var a = ix + gridX1 * iy;
  11256. var b = ix + gridX1 * ( iy + 1 );
  11257. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  11258. var d = ( ix + 1 ) + gridX1 * iy;
  11259. // faces
  11260. indices.push( a, b, d );
  11261. indices.push( b, c, d );
  11262. }
  11263. }
  11264. // build geometry
  11265. this.setIndex( indices );
  11266. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11267. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11268. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11269. }
  11270. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  11271. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  11272. /**
  11273. * @author mrdoob / http://mrdoob.com/
  11274. * @author alteredq / http://alteredqualia.com/
  11275. */
  11276. var materialId = 0;
  11277. function Material() {
  11278. Object.defineProperty( this, 'id', { value: materialId ++ } );
  11279. this.uuid = _Math.generateUUID();
  11280. this.name = '';
  11281. this.type = 'Material';
  11282. this.fog = true;
  11283. this.lights = true;
  11284. this.blending = NormalBlending;
  11285. this.side = FrontSide;
  11286. this.flatShading = false;
  11287. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  11288. this.opacity = 1;
  11289. this.transparent = false;
  11290. this.blendSrc = SrcAlphaFactor;
  11291. this.blendDst = OneMinusSrcAlphaFactor;
  11292. this.blendEquation = AddEquation;
  11293. this.blendSrcAlpha = null;
  11294. this.blendDstAlpha = null;
  11295. this.blendEquationAlpha = null;
  11296. this.depthFunc = LessEqualDepth;
  11297. this.depthTest = true;
  11298. this.depthWrite = true;
  11299. this.clippingPlanes = null;
  11300. this.clipIntersection = false;
  11301. this.clipShadows = false;
  11302. this.shadowSide = null;
  11303. this.colorWrite = true;
  11304. this.precision = null; // override the renderer's default precision for this material
  11305. this.polygonOffset = false;
  11306. this.polygonOffsetFactor = 0;
  11307. this.polygonOffsetUnits = 0;
  11308. this.dithering = false;
  11309. this.alphaTest = 0;
  11310. this.premultipliedAlpha = false;
  11311. this.visible = true;
  11312. this.userData = {};
  11313. this.needsUpdate = true;
  11314. }
  11315. Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  11316. constructor: Material,
  11317. isMaterial: true,
  11318. onBeforeCompile: function () {},
  11319. setValues: function ( values ) {
  11320. if ( values === undefined ) return;
  11321. for ( var key in values ) {
  11322. var newValue = values[ key ];
  11323. if ( newValue === undefined ) {
  11324. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  11325. continue;
  11326. }
  11327. // for backward compatability if shading is set in the constructor
  11328. if ( key === 'shading' ) {
  11329. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  11330. this.flatShading = ( newValue === FlatShading ) ? true : false;
  11331. continue;
  11332. }
  11333. var currentValue = this[ key ];
  11334. if ( currentValue === undefined ) {
  11335. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  11336. continue;
  11337. }
  11338. if ( currentValue && currentValue.isColor ) {
  11339. currentValue.set( newValue );
  11340. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  11341. currentValue.copy( newValue );
  11342. } else {
  11343. this[ key ] = newValue;
  11344. }
  11345. }
  11346. },
  11347. toJSON: function ( meta ) {
  11348. var isRoot = ( meta === undefined || typeof meta === 'string' );
  11349. if ( isRoot ) {
  11350. meta = {
  11351. textures: {},
  11352. images: {}
  11353. };
  11354. }
  11355. var data = {
  11356. metadata: {
  11357. version: 4.5,
  11358. type: 'Material',
  11359. generator: 'Material.toJSON'
  11360. }
  11361. };
  11362. // standard Material serialization
  11363. data.uuid = this.uuid;
  11364. data.type = this.type;
  11365. if ( this.name !== '' ) data.name = this.name;
  11366. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  11367. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  11368. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  11369. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  11370. if ( this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  11371. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  11372. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  11373. if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat;
  11374. if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness;
  11375. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  11376. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  11377. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  11378. if ( this.aoMap && this.aoMap.isTexture ) {
  11379. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  11380. data.aoMapIntensity = this.aoMapIntensity;
  11381. }
  11382. if ( this.bumpMap && this.bumpMap.isTexture ) {
  11383. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  11384. data.bumpScale = this.bumpScale;
  11385. }
  11386. if ( this.normalMap && this.normalMap.isTexture ) {
  11387. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  11388. data.normalMapType = this.normalMapType;
  11389. data.normalScale = this.normalScale.toArray();
  11390. }
  11391. if ( this.displacementMap && this.displacementMap.isTexture ) {
  11392. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  11393. data.displacementScale = this.displacementScale;
  11394. data.displacementBias = this.displacementBias;
  11395. }
  11396. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  11397. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  11398. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  11399. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  11400. if ( this.envMap && this.envMap.isTexture ) {
  11401. data.envMap = this.envMap.toJSON( meta ).uuid;
  11402. data.reflectivity = this.reflectivity; // Scale behind envMap
  11403. if ( this.combine !== undefined ) data.combine = this.combine;
  11404. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  11405. }
  11406. if ( this.gradientMap && this.gradientMap.isTexture ) {
  11407. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  11408. }
  11409. if ( this.size !== undefined ) data.size = this.size;
  11410. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  11411. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  11412. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  11413. if ( this.side !== FrontSide ) data.side = this.side;
  11414. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  11415. if ( this.opacity < 1 ) data.opacity = this.opacity;
  11416. if ( this.transparent === true ) data.transparent = this.transparent;
  11417. data.depthFunc = this.depthFunc;
  11418. data.depthTest = this.depthTest;
  11419. data.depthWrite = this.depthWrite;
  11420. // rotation (SpriteMaterial)
  11421. if ( this.rotation !== 0 ) data.rotation = this.rotation;
  11422. if ( this.polygonOffset === true ) data.polygonOffset = true;
  11423. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  11424. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  11425. if ( this.linewidth !== 1 ) data.linewidth = this.linewidth;
  11426. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  11427. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  11428. if ( this.scale !== undefined ) data.scale = this.scale;
  11429. if ( this.dithering === true ) data.dithering = true;
  11430. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  11431. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  11432. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  11433. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  11434. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  11435. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  11436. if ( this.morphTargets === true ) data.morphTargets = true;
  11437. if ( this.skinning === true ) data.skinning = true;
  11438. if ( this.visible === false ) data.visible = false;
  11439. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  11440. // TODO: Copied from Object3D.toJSON
  11441. function extractFromCache( cache ) {
  11442. var values = [];
  11443. for ( var key in cache ) {
  11444. var data = cache[ key ];
  11445. delete data.metadata;
  11446. values.push( data );
  11447. }
  11448. return values;
  11449. }
  11450. if ( isRoot ) {
  11451. var textures = extractFromCache( meta.textures );
  11452. var images = extractFromCache( meta.images );
  11453. if ( textures.length > 0 ) data.textures = textures;
  11454. if ( images.length > 0 ) data.images = images;
  11455. }
  11456. return data;
  11457. },
  11458. clone: function () {
  11459. return new this.constructor().copy( this );
  11460. },
  11461. copy: function ( source ) {
  11462. this.name = source.name;
  11463. this.fog = source.fog;
  11464. this.lights = source.lights;
  11465. this.blending = source.blending;
  11466. this.side = source.side;
  11467. this.flatShading = source.flatShading;
  11468. this.vertexColors = source.vertexColors;
  11469. this.opacity = source.opacity;
  11470. this.transparent = source.transparent;
  11471. this.blendSrc = source.blendSrc;
  11472. this.blendDst = source.blendDst;
  11473. this.blendEquation = source.blendEquation;
  11474. this.blendSrcAlpha = source.blendSrcAlpha;
  11475. this.blendDstAlpha = source.blendDstAlpha;
  11476. this.blendEquationAlpha = source.blendEquationAlpha;
  11477. this.depthFunc = source.depthFunc;
  11478. this.depthTest = source.depthTest;
  11479. this.depthWrite = source.depthWrite;
  11480. this.colorWrite = source.colorWrite;
  11481. this.precision = source.precision;
  11482. this.polygonOffset = source.polygonOffset;
  11483. this.polygonOffsetFactor = source.polygonOffsetFactor;
  11484. this.polygonOffsetUnits = source.polygonOffsetUnits;
  11485. this.dithering = source.dithering;
  11486. this.alphaTest = source.alphaTest;
  11487. this.premultipliedAlpha = source.premultipliedAlpha;
  11488. this.visible = source.visible;
  11489. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11490. this.clipShadows = source.clipShadows;
  11491. this.clipIntersection = source.clipIntersection;
  11492. var srcPlanes = source.clippingPlanes,
  11493. dstPlanes = null;
  11494. if ( srcPlanes !== null ) {
  11495. var n = srcPlanes.length;
  11496. dstPlanes = new Array( n );
  11497. for ( var i = 0; i !== n; ++ i )
  11498. dstPlanes[ i ] = srcPlanes[ i ].clone();
  11499. }
  11500. this.clippingPlanes = dstPlanes;
  11501. this.shadowSide = source.shadowSide;
  11502. return this;
  11503. },
  11504. dispose: function () {
  11505. this.dispatchEvent( { type: 'dispose' } );
  11506. }
  11507. } );
  11508. /**
  11509. * @author alteredq / http://alteredqualia.com/
  11510. *
  11511. * parameters = {
  11512. * defines: { "label" : "value" },
  11513. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  11514. *
  11515. * fragmentShader: <string>,
  11516. * vertexShader: <string>,
  11517. *
  11518. * wireframe: <boolean>,
  11519. * wireframeLinewidth: <float>,
  11520. *
  11521. * lights: <bool>,
  11522. *
  11523. * skinning: <bool>,
  11524. * morphTargets: <bool>,
  11525. * morphNormals: <bool>
  11526. * }
  11527. */
  11528. function ShaderMaterial( parameters ) {
  11529. Material.call( this );
  11530. this.type = 'ShaderMaterial';
  11531. this.defines = {};
  11532. this.uniforms = {};
  11533. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  11534. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  11535. this.linewidth = 1;
  11536. this.wireframe = false;
  11537. this.wireframeLinewidth = 1;
  11538. this.fog = false; // set to use scene fog
  11539. this.lights = false; // set to use scene lights
  11540. this.clipping = false; // set to use user-defined clipping planes
  11541. this.skinning = false; // set to use skinning attribute streams
  11542. this.morphTargets = false; // set to use morph targets
  11543. this.morphNormals = false; // set to use morph normals
  11544. this.extensions = {
  11545. derivatives: false, // set to use derivatives
  11546. fragDepth: false, // set to use fragment depth values
  11547. drawBuffers: false, // set to use draw buffers
  11548. shaderTextureLOD: false // set to use shader texture LOD
  11549. };
  11550. // When rendered geometry doesn't include these attributes but the material does,
  11551. // use these default values in WebGL. This avoids errors when buffer data is missing.
  11552. this.defaultAttributeValues = {
  11553. 'color': [ 1, 1, 1 ],
  11554. 'uv': [ 0, 0 ],
  11555. 'uv2': [ 0, 0 ]
  11556. };
  11557. this.index0AttributeName = undefined;
  11558. this.uniformsNeedUpdate = false;
  11559. if ( parameters !== undefined ) {
  11560. if ( parameters.attributes !== undefined ) {
  11561. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  11562. }
  11563. this.setValues( parameters );
  11564. }
  11565. }
  11566. ShaderMaterial.prototype = Object.create( Material.prototype );
  11567. ShaderMaterial.prototype.constructor = ShaderMaterial;
  11568. ShaderMaterial.prototype.isShaderMaterial = true;
  11569. ShaderMaterial.prototype.copy = function ( source ) {
  11570. Material.prototype.copy.call( this, source );
  11571. this.fragmentShader = source.fragmentShader;
  11572. this.vertexShader = source.vertexShader;
  11573. this.uniforms = UniformsUtils.clone( source.uniforms );
  11574. this.defines = Object.assign( {}, source.defines );
  11575. this.wireframe = source.wireframe;
  11576. this.wireframeLinewidth = source.wireframeLinewidth;
  11577. this.lights = source.lights;
  11578. this.clipping = source.clipping;
  11579. this.skinning = source.skinning;
  11580. this.morphTargets = source.morphTargets;
  11581. this.morphNormals = source.morphNormals;
  11582. this.extensions = source.extensions;
  11583. return this;
  11584. };
  11585. ShaderMaterial.prototype.toJSON = function ( meta ) {
  11586. var data = Material.prototype.toJSON.call( this, meta );
  11587. data.uniforms = {};
  11588. for ( var name in this.uniforms ) {
  11589. var uniform = this.uniforms[ name ];
  11590. var value = uniform.value;
  11591. if ( value.isTexture ) {
  11592. data.uniforms[ name ] = {
  11593. type: 't',
  11594. value: value.toJSON( meta ).uuid
  11595. };
  11596. } else if ( value.isColor ) {
  11597. data.uniforms[ name ] = {
  11598. type: 'c',
  11599. value: value.getHex()
  11600. };
  11601. } else if ( value.isVector2 ) {
  11602. data.uniforms[ name ] = {
  11603. type: 'v2',
  11604. value: value.toArray()
  11605. };
  11606. } else if ( value.isVector3 ) {
  11607. data.uniforms[ name ] = {
  11608. type: 'v3',
  11609. value: value.toArray()
  11610. };
  11611. } else if ( value.isVector4 ) {
  11612. data.uniforms[ name ] = {
  11613. type: 'v4',
  11614. value: value.toArray()
  11615. };
  11616. } else if ( value.isMatrix4 ) {
  11617. data.uniforms[ name ] = {
  11618. type: 'm4',
  11619. value: value.toArray()
  11620. };
  11621. } else {
  11622. data.uniforms[ name ] = {
  11623. value: value
  11624. };
  11625. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  11626. }
  11627. }
  11628. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  11629. data.vertexShader = this.vertexShader;
  11630. data.fragmentShader = this.fragmentShader;
  11631. return data;
  11632. };
  11633. /**
  11634. * @author bhouston / http://clara.io
  11635. */
  11636. function Ray( origin, direction ) {
  11637. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  11638. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  11639. }
  11640. Object.assign( Ray.prototype, {
  11641. set: function ( origin, direction ) {
  11642. this.origin.copy( origin );
  11643. this.direction.copy( direction );
  11644. return this;
  11645. },
  11646. clone: function () {
  11647. return new this.constructor().copy( this );
  11648. },
  11649. copy: function ( ray ) {
  11650. this.origin.copy( ray.origin );
  11651. this.direction.copy( ray.direction );
  11652. return this;
  11653. },
  11654. at: function ( t, target ) {
  11655. if ( target === undefined ) {
  11656. console.warn( 'THREE.Ray: .at() target is now required' );
  11657. target = new Vector3();
  11658. }
  11659. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  11660. },
  11661. lookAt: function ( v ) {
  11662. this.direction.copy( v ).sub( this.origin ).normalize();
  11663. return this;
  11664. },
  11665. recast: function () {
  11666. var v1 = new Vector3();
  11667. return function recast( t ) {
  11668. this.origin.copy( this.at( t, v1 ) );
  11669. return this;
  11670. };
  11671. }(),
  11672. closestPointToPoint: function ( point, target ) {
  11673. if ( target === undefined ) {
  11674. console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' );
  11675. target = new Vector3();
  11676. }
  11677. target.subVectors( point, this.origin );
  11678. var directionDistance = target.dot( this.direction );
  11679. if ( directionDistance < 0 ) {
  11680. return target.copy( this.origin );
  11681. }
  11682. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  11683. },
  11684. distanceToPoint: function ( point ) {
  11685. return Math.sqrt( this.distanceSqToPoint( point ) );
  11686. },
  11687. distanceSqToPoint: function () {
  11688. var v1 = new Vector3();
  11689. return function distanceSqToPoint( point ) {
  11690. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  11691. // point behind the ray
  11692. if ( directionDistance < 0 ) {
  11693. return this.origin.distanceToSquared( point );
  11694. }
  11695. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  11696. return v1.distanceToSquared( point );
  11697. };
  11698. }(),
  11699. distanceSqToSegment: function () {
  11700. var segCenter = new Vector3();
  11701. var segDir = new Vector3();
  11702. var diff = new Vector3();
  11703. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  11704. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  11705. // It returns the min distance between the ray and the segment
  11706. // defined by v0 and v1
  11707. // It can also set two optional targets :
  11708. // - The closest point on the ray
  11709. // - The closest point on the segment
  11710. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  11711. segDir.copy( v1 ).sub( v0 ).normalize();
  11712. diff.copy( this.origin ).sub( segCenter );
  11713. var segExtent = v0.distanceTo( v1 ) * 0.5;
  11714. var a01 = - this.direction.dot( segDir );
  11715. var b0 = diff.dot( this.direction );
  11716. var b1 = - diff.dot( segDir );
  11717. var c = diff.lengthSq();
  11718. var det = Math.abs( 1 - a01 * a01 );
  11719. var s0, s1, sqrDist, extDet;
  11720. if ( det > 0 ) {
  11721. // The ray and segment are not parallel.
  11722. s0 = a01 * b1 - b0;
  11723. s1 = a01 * b0 - b1;
  11724. extDet = segExtent * det;
  11725. if ( s0 >= 0 ) {
  11726. if ( s1 >= - extDet ) {
  11727. if ( s1 <= extDet ) {
  11728. // region 0
  11729. // Minimum at interior points of ray and segment.
  11730. var invDet = 1 / det;
  11731. s0 *= invDet;
  11732. s1 *= invDet;
  11733. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  11734. } else {
  11735. // region 1
  11736. s1 = segExtent;
  11737. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  11738. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  11739. }
  11740. } else {
  11741. // region 5
  11742. s1 = - segExtent;
  11743. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  11744. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  11745. }
  11746. } else {
  11747. if ( s1 <= - extDet ) {
  11748. // region 4
  11749. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  11750. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  11751. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  11752. } else if ( s1 <= extDet ) {
  11753. // region 3
  11754. s0 = 0;
  11755. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  11756. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  11757. } else {
  11758. // region 2
  11759. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  11760. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  11761. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  11762. }
  11763. }
  11764. } else {
  11765. // Ray and segment are parallel.
  11766. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  11767. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  11768. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  11769. }
  11770. if ( optionalPointOnRay ) {
  11771. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  11772. }
  11773. if ( optionalPointOnSegment ) {
  11774. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  11775. }
  11776. return sqrDist;
  11777. };
  11778. }(),
  11779. intersectSphere: function () {
  11780. var v1 = new Vector3();
  11781. return function intersectSphere( sphere, target ) {
  11782. v1.subVectors( sphere.center, this.origin );
  11783. var tca = v1.dot( this.direction );
  11784. var d2 = v1.dot( v1 ) - tca * tca;
  11785. var radius2 = sphere.radius * sphere.radius;
  11786. if ( d2 > radius2 ) return null;
  11787. var thc = Math.sqrt( radius2 - d2 );
  11788. // t0 = first intersect point - entrance on front of sphere
  11789. var t0 = tca - thc;
  11790. // t1 = second intersect point - exit point on back of sphere
  11791. var t1 = tca + thc;
  11792. // test to see if both t0 and t1 are behind the ray - if so, return null
  11793. if ( t0 < 0 && t1 < 0 ) return null;
  11794. // test to see if t0 is behind the ray:
  11795. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  11796. // in order to always return an intersect point that is in front of the ray.
  11797. if ( t0 < 0 ) return this.at( t1, target );
  11798. // else t0 is in front of the ray, so return the first collision point scaled by t0
  11799. return this.at( t0, target );
  11800. };
  11801. }(),
  11802. intersectsSphere: function ( sphere ) {
  11803. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  11804. },
  11805. distanceToPlane: function ( plane ) {
  11806. var denominator = plane.normal.dot( this.direction );
  11807. if ( denominator === 0 ) {
  11808. // line is coplanar, return origin
  11809. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  11810. return 0;
  11811. }
  11812. // Null is preferable to undefined since undefined means.... it is undefined
  11813. return null;
  11814. }
  11815. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  11816. // Return if the ray never intersects the plane
  11817. return t >= 0 ? t : null;
  11818. },
  11819. intersectPlane: function ( plane, target ) {
  11820. var t = this.distanceToPlane( plane );
  11821. if ( t === null ) {
  11822. return null;
  11823. }
  11824. return this.at( t, target );
  11825. },
  11826. intersectsPlane: function ( plane ) {
  11827. // check if the ray lies on the plane first
  11828. var distToPoint = plane.distanceToPoint( this.origin );
  11829. if ( distToPoint === 0 ) {
  11830. return true;
  11831. }
  11832. var denominator = plane.normal.dot( this.direction );
  11833. if ( denominator * distToPoint < 0 ) {
  11834. return true;
  11835. }
  11836. // ray origin is behind the plane (and is pointing behind it)
  11837. return false;
  11838. },
  11839. intersectBox: function ( box, target ) {
  11840. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  11841. var invdirx = 1 / this.direction.x,
  11842. invdiry = 1 / this.direction.y,
  11843. invdirz = 1 / this.direction.z;
  11844. var origin = this.origin;
  11845. if ( invdirx >= 0 ) {
  11846. tmin = ( box.min.x - origin.x ) * invdirx;
  11847. tmax = ( box.max.x - origin.x ) * invdirx;
  11848. } else {
  11849. tmin = ( box.max.x - origin.x ) * invdirx;
  11850. tmax = ( box.min.x - origin.x ) * invdirx;
  11851. }
  11852. if ( invdiry >= 0 ) {
  11853. tymin = ( box.min.y - origin.y ) * invdiry;
  11854. tymax = ( box.max.y - origin.y ) * invdiry;
  11855. } else {
  11856. tymin = ( box.max.y - origin.y ) * invdiry;
  11857. tymax = ( box.min.y - origin.y ) * invdiry;
  11858. }
  11859. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  11860. // These lines also handle the case where tmin or tmax is NaN
  11861. // (result of 0 * Infinity). x !== x returns true if x is NaN
  11862. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  11863. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  11864. if ( invdirz >= 0 ) {
  11865. tzmin = ( box.min.z - origin.z ) * invdirz;
  11866. tzmax = ( box.max.z - origin.z ) * invdirz;
  11867. } else {
  11868. tzmin = ( box.max.z - origin.z ) * invdirz;
  11869. tzmax = ( box.min.z - origin.z ) * invdirz;
  11870. }
  11871. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  11872. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  11873. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  11874. //return point closest to the ray (positive side)
  11875. if ( tmax < 0 ) return null;
  11876. return this.at( tmin >= 0 ? tmin : tmax, target );
  11877. },
  11878. intersectsBox: ( function () {
  11879. var v = new Vector3();
  11880. return function intersectsBox( box ) {
  11881. return this.intersectBox( box, v ) !== null;
  11882. };
  11883. } )(),
  11884. intersectTriangle: function () {
  11885. // Compute the offset origin, edges, and normal.
  11886. var diff = new Vector3();
  11887. var edge1 = new Vector3();
  11888. var edge2 = new Vector3();
  11889. var normal = new Vector3();
  11890. return function intersectTriangle( a, b, c, backfaceCulling, target ) {
  11891. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  11892. edge1.subVectors( b, a );
  11893. edge2.subVectors( c, a );
  11894. normal.crossVectors( edge1, edge2 );
  11895. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  11896. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  11897. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  11898. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  11899. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  11900. var DdN = this.direction.dot( normal );
  11901. var sign;
  11902. if ( DdN > 0 ) {
  11903. if ( backfaceCulling ) return null;
  11904. sign = 1;
  11905. } else if ( DdN < 0 ) {
  11906. sign = - 1;
  11907. DdN = - DdN;
  11908. } else {
  11909. return null;
  11910. }
  11911. diff.subVectors( this.origin, a );
  11912. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  11913. // b1 < 0, no intersection
  11914. if ( DdQxE2 < 0 ) {
  11915. return null;
  11916. }
  11917. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  11918. // b2 < 0, no intersection
  11919. if ( DdE1xQ < 0 ) {
  11920. return null;
  11921. }
  11922. // b1+b2 > 1, no intersection
  11923. if ( DdQxE2 + DdE1xQ > DdN ) {
  11924. return null;
  11925. }
  11926. // Line intersects triangle, check if ray does.
  11927. var QdN = - sign * diff.dot( normal );
  11928. // t < 0, no intersection
  11929. if ( QdN < 0 ) {
  11930. return null;
  11931. }
  11932. // Ray intersects triangle.
  11933. return this.at( QdN / DdN, target );
  11934. };
  11935. }(),
  11936. applyMatrix4: function ( matrix4 ) {
  11937. this.origin.applyMatrix4( matrix4 );
  11938. this.direction.transformDirection( matrix4 );
  11939. return this;
  11940. },
  11941. equals: function ( ray ) {
  11942. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  11943. }
  11944. } );
  11945. /**
  11946. * @author bhouston / http://clara.io
  11947. * @author mrdoob / http://mrdoob.com/
  11948. */
  11949. function Triangle( a, b, c ) {
  11950. this.a = ( a !== undefined ) ? a : new Vector3();
  11951. this.b = ( b !== undefined ) ? b : new Vector3();
  11952. this.c = ( c !== undefined ) ? c : new Vector3();
  11953. }
  11954. Object.assign( Triangle, {
  11955. getNormal: function () {
  11956. var v0 = new Vector3();
  11957. return function getNormal( a, b, c, target ) {
  11958. if ( target === undefined ) {
  11959. console.warn( 'THREE.Triangle: .getNormal() target is now required' );
  11960. target = new Vector3();
  11961. }
  11962. target.subVectors( c, b );
  11963. v0.subVectors( a, b );
  11964. target.cross( v0 );
  11965. var targetLengthSq = target.lengthSq();
  11966. if ( targetLengthSq > 0 ) {
  11967. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11968. }
  11969. return target.set( 0, 0, 0 );
  11970. };
  11971. }(),
  11972. // static/instance method to calculate barycentric coordinates
  11973. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11974. getBarycoord: function () {
  11975. var v0 = new Vector3();
  11976. var v1 = new Vector3();
  11977. var v2 = new Vector3();
  11978. return function getBarycoord( point, a, b, c, target ) {
  11979. v0.subVectors( c, a );
  11980. v1.subVectors( b, a );
  11981. v2.subVectors( point, a );
  11982. var dot00 = v0.dot( v0 );
  11983. var dot01 = v0.dot( v1 );
  11984. var dot02 = v0.dot( v2 );
  11985. var dot11 = v1.dot( v1 );
  11986. var dot12 = v1.dot( v2 );
  11987. var denom = ( dot00 * dot11 - dot01 * dot01 );
  11988. if ( target === undefined ) {
  11989. console.warn( 'THREE.Triangle: .getBarycoord() target is now required' );
  11990. target = new Vector3();
  11991. }
  11992. // collinear or singular triangle
  11993. if ( denom === 0 ) {
  11994. // arbitrary location outside of triangle?
  11995. // not sure if this is the best idea, maybe should be returning undefined
  11996. return target.set( - 2, - 1, - 1 );
  11997. }
  11998. var invDenom = 1 / denom;
  11999. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  12000. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  12001. // barycentric coordinates must always sum to 1
  12002. return target.set( 1 - u - v, v, u );
  12003. };
  12004. }(),
  12005. containsPoint: function () {
  12006. var v1 = new Vector3();
  12007. return function containsPoint( point, a, b, c ) {
  12008. Triangle.getBarycoord( point, a, b, c, v1 );
  12009. return ( v1.x >= 0 ) && ( v1.y >= 0 ) && ( ( v1.x + v1.y ) <= 1 );
  12010. };
  12011. }(),
  12012. getUV: function () {
  12013. var barycoord = new Vector3();
  12014. return function getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  12015. this.getBarycoord( point, p1, p2, p3, barycoord );
  12016. target.set( 0, 0 );
  12017. target.addScaledVector( uv1, barycoord.x );
  12018. target.addScaledVector( uv2, barycoord.y );
  12019. target.addScaledVector( uv3, barycoord.z );
  12020. return target;
  12021. };
  12022. }()
  12023. } );
  12024. Object.assign( Triangle.prototype, {
  12025. set: function ( a, b, c ) {
  12026. this.a.copy( a );
  12027. this.b.copy( b );
  12028. this.c.copy( c );
  12029. return this;
  12030. },
  12031. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  12032. this.a.copy( points[ i0 ] );
  12033. this.b.copy( points[ i1 ] );
  12034. this.c.copy( points[ i2 ] );
  12035. return this;
  12036. },
  12037. clone: function () {
  12038. return new this.constructor().copy( this );
  12039. },
  12040. copy: function ( triangle ) {
  12041. this.a.copy( triangle.a );
  12042. this.b.copy( triangle.b );
  12043. this.c.copy( triangle.c );
  12044. return this;
  12045. },
  12046. getArea: function () {
  12047. var v0 = new Vector3();
  12048. var v1 = new Vector3();
  12049. return function getArea() {
  12050. v0.subVectors( this.c, this.b );
  12051. v1.subVectors( this.a, this.b );
  12052. return v0.cross( v1 ).length() * 0.5;
  12053. };
  12054. }(),
  12055. getMidpoint: function ( target ) {
  12056. if ( target === undefined ) {
  12057. console.warn( 'THREE.Triangle: .getMidpoint() target is now required' );
  12058. target = new Vector3();
  12059. }
  12060. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  12061. },
  12062. getNormal: function ( target ) {
  12063. return Triangle.getNormal( this.a, this.b, this.c, target );
  12064. },
  12065. getPlane: function ( target ) {
  12066. if ( target === undefined ) {
  12067. console.warn( 'THREE.Triangle: .getPlane() target is now required' );
  12068. target = new Vector3();
  12069. }
  12070. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  12071. },
  12072. getBarycoord: function ( point, target ) {
  12073. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  12074. },
  12075. containsPoint: function ( point ) {
  12076. return Triangle.containsPoint( point, this.a, this.b, this.c );
  12077. },
  12078. getUV: function ( point, uv1, uv2, uv3, result ) {
  12079. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, result );
  12080. },
  12081. intersectsBox: function ( box ) {
  12082. return box.intersectsTriangle( this );
  12083. },
  12084. closestPointToPoint: function () {
  12085. var vab = new Vector3();
  12086. var vac = new Vector3();
  12087. var vbc = new Vector3();
  12088. var vap = new Vector3();
  12089. var vbp = new Vector3();
  12090. var vcp = new Vector3();
  12091. return function closestPointToPoint( p, target ) {
  12092. if ( target === undefined ) {
  12093. console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' );
  12094. target = new Vector3();
  12095. }
  12096. var a = this.a, b = this.b, c = this.c;
  12097. var v, w;
  12098. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  12099. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  12100. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  12101. // basically, we're distinguishing which of the voronoi regions of the triangle
  12102. // the point lies in with the minimum amount of redundant computation.
  12103. vab.subVectors( b, a );
  12104. vac.subVectors( c, a );
  12105. vap.subVectors( p, a );
  12106. var d1 = vab.dot( vap );
  12107. var d2 = vac.dot( vap );
  12108. if ( d1 <= 0 && d2 <= 0 ) {
  12109. // vertex region of A; barycentric coords (1, 0, 0)
  12110. return target.copy( a );
  12111. }
  12112. vbp.subVectors( p, b );
  12113. var d3 = vab.dot( vbp );
  12114. var d4 = vac.dot( vbp );
  12115. if ( d3 >= 0 && d4 <= d3 ) {
  12116. // vertex region of B; barycentric coords (0, 1, 0)
  12117. return target.copy( b );
  12118. }
  12119. var vc = d1 * d4 - d3 * d2;
  12120. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  12121. v = d1 / ( d1 - d3 );
  12122. // edge region of AB; barycentric coords (1-v, v, 0)
  12123. return target.copy( a ).addScaledVector( vab, v );
  12124. }
  12125. vcp.subVectors( p, c );
  12126. var d5 = vab.dot( vcp );
  12127. var d6 = vac.dot( vcp );
  12128. if ( d6 >= 0 && d5 <= d6 ) {
  12129. // vertex region of C; barycentric coords (0, 0, 1)
  12130. return target.copy( c );
  12131. }
  12132. var vb = d5 * d2 - d1 * d6;
  12133. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  12134. w = d2 / ( d2 - d6 );
  12135. // edge region of AC; barycentric coords (1-w, 0, w)
  12136. return target.copy( a ).addScaledVector( vac, w );
  12137. }
  12138. var va = d3 * d6 - d5 * d4;
  12139. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  12140. vbc.subVectors( c, b );
  12141. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  12142. // edge region of BC; barycentric coords (0, 1-w, w)
  12143. return target.copy( b ).addScaledVector( vbc, w ); // edge region of BC
  12144. }
  12145. // face region
  12146. var denom = 1 / ( va + vb + vc );
  12147. // u = va * denom
  12148. v = vb * denom;
  12149. w = vc * denom;
  12150. return target.copy( a ).addScaledVector( vab, v ).addScaledVector( vac, w );
  12151. };
  12152. }(),
  12153. equals: function ( triangle ) {
  12154. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  12155. }
  12156. } );
  12157. /**
  12158. * @author mrdoob / http://mrdoob.com/
  12159. * @author alteredq / http://alteredqualia.com/
  12160. *
  12161. * parameters = {
  12162. * color: <hex>,
  12163. * opacity: <float>,
  12164. * map: new THREE.Texture( <Image> ),
  12165. *
  12166. * lightMap: new THREE.Texture( <Image> ),
  12167. * lightMapIntensity: <float>
  12168. *
  12169. * aoMap: new THREE.Texture( <Image> ),
  12170. * aoMapIntensity: <float>
  12171. *
  12172. * specularMap: new THREE.Texture( <Image> ),
  12173. *
  12174. * alphaMap: new THREE.Texture( <Image> ),
  12175. *
  12176. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  12177. * combine: THREE.Multiply,
  12178. * reflectivity: <float>,
  12179. * refractionRatio: <float>,
  12180. *
  12181. * depthTest: <bool>,
  12182. * depthWrite: <bool>,
  12183. *
  12184. * wireframe: <boolean>,
  12185. * wireframeLinewidth: <float>,
  12186. *
  12187. * skinning: <bool>,
  12188. * morphTargets: <bool>
  12189. * }
  12190. */
  12191. function MeshBasicMaterial( parameters ) {
  12192. Material.call( this );
  12193. this.type = 'MeshBasicMaterial';
  12194. this.color = new Color( 0xffffff ); // emissive
  12195. this.map = null;
  12196. this.lightMap = null;
  12197. this.lightMapIntensity = 1.0;
  12198. this.aoMap = null;
  12199. this.aoMapIntensity = 1.0;
  12200. this.specularMap = null;
  12201. this.alphaMap = null;
  12202. this.envMap = null;
  12203. this.combine = MultiplyOperation;
  12204. this.reflectivity = 1;
  12205. this.refractionRatio = 0.98;
  12206. this.wireframe = false;
  12207. this.wireframeLinewidth = 1;
  12208. this.wireframeLinecap = 'round';
  12209. this.wireframeLinejoin = 'round';
  12210. this.skinning = false;
  12211. this.morphTargets = false;
  12212. this.lights = false;
  12213. this.setValues( parameters );
  12214. }
  12215. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  12216. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  12217. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  12218. MeshBasicMaterial.prototype.copy = function ( source ) {
  12219. Material.prototype.copy.call( this, source );
  12220. this.color.copy( source.color );
  12221. this.map = source.map;
  12222. this.lightMap = source.lightMap;
  12223. this.lightMapIntensity = source.lightMapIntensity;
  12224. this.aoMap = source.aoMap;
  12225. this.aoMapIntensity = source.aoMapIntensity;
  12226. this.specularMap = source.specularMap;
  12227. this.alphaMap = source.alphaMap;
  12228. this.envMap = source.envMap;
  12229. this.combine = source.combine;
  12230. this.reflectivity = source.reflectivity;
  12231. this.refractionRatio = source.refractionRatio;
  12232. this.wireframe = source.wireframe;
  12233. this.wireframeLinewidth = source.wireframeLinewidth;
  12234. this.wireframeLinecap = source.wireframeLinecap;
  12235. this.wireframeLinejoin = source.wireframeLinejoin;
  12236. this.skinning = source.skinning;
  12237. this.morphTargets = source.morphTargets;
  12238. return this;
  12239. };
  12240. /**
  12241. * @author mrdoob / http://mrdoob.com/
  12242. * @author alteredq / http://alteredqualia.com/
  12243. * @author mikael emtinger / http://gomo.se/
  12244. * @author jonobr1 / http://jonobr1.com/
  12245. */
  12246. function Mesh( geometry, material ) {
  12247. Object3D.call( this );
  12248. this.type = 'Mesh';
  12249. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  12250. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  12251. this.drawMode = TrianglesDrawMode;
  12252. this.updateMorphTargets();
  12253. }
  12254. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  12255. constructor: Mesh,
  12256. isMesh: true,
  12257. setDrawMode: function ( value ) {
  12258. this.drawMode = value;
  12259. },
  12260. copy: function ( source ) {
  12261. Object3D.prototype.copy.call( this, source );
  12262. this.drawMode = source.drawMode;
  12263. if ( source.morphTargetInfluences !== undefined ) {
  12264. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  12265. }
  12266. if ( source.morphTargetDictionary !== undefined ) {
  12267. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  12268. }
  12269. return this;
  12270. },
  12271. updateMorphTargets: function () {
  12272. var geometry = this.geometry;
  12273. var m, ml, name;
  12274. if ( geometry.isBufferGeometry ) {
  12275. var morphAttributes = geometry.morphAttributes;
  12276. var keys = Object.keys( morphAttributes );
  12277. if ( keys.length > 0 ) {
  12278. var morphAttribute = morphAttributes[ keys[ 0 ] ];
  12279. if ( morphAttribute !== undefined ) {
  12280. this.morphTargetInfluences = [];
  12281. this.morphTargetDictionary = {};
  12282. for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  12283. name = morphAttribute[ m ].name || String( m );
  12284. this.morphTargetInfluences.push( 0 );
  12285. this.morphTargetDictionary[ name ] = m;
  12286. }
  12287. }
  12288. }
  12289. } else {
  12290. var morphTargets = geometry.morphTargets;
  12291. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  12292. this.morphTargetInfluences = [];
  12293. this.morphTargetDictionary = {};
  12294. for ( m = 0, ml = morphTargets.length; m < ml; m ++ ) {
  12295. name = morphTargets[ m ].name || String( m );
  12296. this.morphTargetInfluences.push( 0 );
  12297. this.morphTargetDictionary[ name ] = m;
  12298. }
  12299. }
  12300. }
  12301. },
  12302. raycast: ( function () {
  12303. var inverseMatrix = new Matrix4();
  12304. var ray = new Ray();
  12305. var sphere = new Sphere();
  12306. var vA = new Vector3();
  12307. var vB = new Vector3();
  12308. var vC = new Vector3();
  12309. var tempA = new Vector3();
  12310. var tempB = new Vector3();
  12311. var tempC = new Vector3();
  12312. var uvA = new Vector2();
  12313. var uvB = new Vector2();
  12314. var uvC = new Vector2();
  12315. var intersectionPoint = new Vector3();
  12316. var intersectionPointWorld = new Vector3();
  12317. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  12318. var intersect;
  12319. if ( material.side === BackSide ) {
  12320. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  12321. } else {
  12322. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  12323. }
  12324. if ( intersect === null ) return null;
  12325. intersectionPointWorld.copy( point );
  12326. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  12327. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  12328. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  12329. return {
  12330. distance: distance,
  12331. point: intersectionPointWorld.clone(),
  12332. object: object
  12333. };
  12334. }
  12335. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, uv, a, b, c ) {
  12336. vA.fromBufferAttribute( position, a );
  12337. vB.fromBufferAttribute( position, b );
  12338. vC.fromBufferAttribute( position, c );
  12339. var intersection = checkIntersection( object, material, raycaster, ray, vA, vB, vC, intersectionPoint );
  12340. if ( intersection ) {
  12341. if ( uv ) {
  12342. uvA.fromBufferAttribute( uv, a );
  12343. uvB.fromBufferAttribute( uv, b );
  12344. uvC.fromBufferAttribute( uv, c );
  12345. intersection.uv = Triangle.getUV( intersectionPoint, vA, vB, vC, uvA, uvB, uvC, new Vector2() );
  12346. }
  12347. var face = new Face3( a, b, c );
  12348. Triangle.getNormal( vA, vB, vC, face.normal );
  12349. intersection.face = face;
  12350. }
  12351. return intersection;
  12352. }
  12353. return function raycast( raycaster, intersects ) {
  12354. var geometry = this.geometry;
  12355. var material = this.material;
  12356. var matrixWorld = this.matrixWorld;
  12357. if ( material === undefined ) return;
  12358. // Checking boundingSphere distance to ray
  12359. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  12360. sphere.copy( geometry.boundingSphere );
  12361. sphere.applyMatrix4( matrixWorld );
  12362. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  12363. //
  12364. inverseMatrix.getInverse( matrixWorld );
  12365. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  12366. // Check boundingBox before continuing
  12367. if ( geometry.boundingBox !== null ) {
  12368. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  12369. }
  12370. var intersection;
  12371. if ( geometry.isBufferGeometry ) {
  12372. var a, b, c;
  12373. var index = geometry.index;
  12374. var position = geometry.attributes.position;
  12375. var uv = geometry.attributes.uv;
  12376. var groups = geometry.groups;
  12377. var drawRange = geometry.drawRange;
  12378. var i, j, il, jl;
  12379. var group, groupMaterial;
  12380. var start, end;
  12381. if ( index !== null ) {
  12382. // indexed buffer geometry
  12383. if ( Array.isArray( material ) ) {
  12384. for ( i = 0, il = groups.length; i < il; i ++ ) {
  12385. group = groups[ i ];
  12386. groupMaterial = material[ group.materialIndex ];
  12387. start = Math.max( group.start, drawRange.start );
  12388. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  12389. for ( j = start, jl = end; j < jl; j += 3 ) {
  12390. a = index.getX( j );
  12391. b = index.getX( j + 1 );
  12392. c = index.getX( j + 2 );
  12393. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, ray, position, uv, a, b, c );
  12394. if ( intersection ) {
  12395. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  12396. intersects.push( intersection );
  12397. }
  12398. }
  12399. }
  12400. } else {
  12401. start = Math.max( 0, drawRange.start );
  12402. end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  12403. for ( i = start, il = end; i < il; i += 3 ) {
  12404. a = index.getX( i );
  12405. b = index.getX( i + 1 );
  12406. c = index.getX( i + 2 );
  12407. intersection = checkBufferGeometryIntersection( this, material, raycaster, ray, position, uv, a, b, c );
  12408. if ( intersection ) {
  12409. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  12410. intersects.push( intersection );
  12411. }
  12412. }
  12413. }
  12414. } else if ( position !== undefined ) {
  12415. // non-indexed buffer geometry
  12416. if ( Array.isArray( material ) ) {
  12417. for ( i = 0, il = groups.length; i < il; i ++ ) {
  12418. group = groups[ i ];
  12419. groupMaterial = material[ group.materialIndex ];
  12420. start = Math.max( group.start, drawRange.start );
  12421. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  12422. for ( j = start, jl = end; j < jl; j += 3 ) {
  12423. a = j;
  12424. b = j + 1;
  12425. c = j + 2;
  12426. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, ray, position, uv, a, b, c );
  12427. if ( intersection ) {
  12428. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  12429. intersects.push( intersection );
  12430. }
  12431. }
  12432. }
  12433. } else {
  12434. start = Math.max( 0, drawRange.start );
  12435. end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  12436. for ( i = start, il = end; i < il; i += 3 ) {
  12437. a = i;
  12438. b = i + 1;
  12439. c = i + 2;
  12440. intersection = checkBufferGeometryIntersection( this, material, raycaster, ray, position, uv, a, b, c );
  12441. if ( intersection ) {
  12442. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  12443. intersects.push( intersection );
  12444. }
  12445. }
  12446. }
  12447. }
  12448. } else if ( geometry.isGeometry ) {
  12449. var fvA, fvB, fvC;
  12450. var isMultiMaterial = Array.isArray( material );
  12451. var vertices = geometry.vertices;
  12452. var faces = geometry.faces;
  12453. var uvs;
  12454. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  12455. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  12456. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  12457. var face = faces[ f ];
  12458. var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
  12459. if ( faceMaterial === undefined ) continue;
  12460. fvA = vertices[ face.a ];
  12461. fvB = vertices[ face.b ];
  12462. fvC = vertices[ face.c ];
  12463. if ( faceMaterial.morphTargets === true ) {
  12464. var morphTargets = geometry.morphTargets;
  12465. var morphInfluences = this.morphTargetInfluences;
  12466. vA.set( 0, 0, 0 );
  12467. vB.set( 0, 0, 0 );
  12468. vC.set( 0, 0, 0 );
  12469. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  12470. var influence = morphInfluences[ t ];
  12471. if ( influence === 0 ) continue;
  12472. var targets = morphTargets[ t ].vertices;
  12473. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  12474. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  12475. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  12476. }
  12477. vA.add( fvA );
  12478. vB.add( fvB );
  12479. vC.add( fvC );
  12480. fvA = vA;
  12481. fvB = vB;
  12482. fvC = vC;
  12483. }
  12484. intersection = checkIntersection( this, faceMaterial, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  12485. if ( intersection ) {
  12486. if ( uvs && uvs[ f ] ) {
  12487. var uvs_f = uvs[ f ];
  12488. uvA.copy( uvs_f[ 0 ] );
  12489. uvB.copy( uvs_f[ 1 ] );
  12490. uvC.copy( uvs_f[ 2 ] );
  12491. intersection.uv = Triangle.getUV( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC, new Vector2() );
  12492. }
  12493. intersection.face = face;
  12494. intersection.faceIndex = f;
  12495. intersects.push( intersection );
  12496. }
  12497. }
  12498. }
  12499. };
  12500. }() ),
  12501. clone: function () {
  12502. return new this.constructor( this.geometry, this.material ).copy( this );
  12503. }
  12504. } );
  12505. /**
  12506. * @author mrdoob / http://mrdoob.com/
  12507. */
  12508. function WebGLBackground( renderer, state, objects, premultipliedAlpha ) {
  12509. var clearColor = new Color( 0x000000 );
  12510. var clearAlpha = 0;
  12511. var planeMesh;
  12512. var boxMesh;
  12513. function render( renderList, scene, camera, forceClear ) {
  12514. var background = scene.background;
  12515. if ( background === null ) {
  12516. setClear( clearColor, clearAlpha );
  12517. } else if ( background && background.isColor ) {
  12518. setClear( background, 1 );
  12519. forceClear = true;
  12520. }
  12521. if ( renderer.autoClear || forceClear ) {
  12522. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  12523. }
  12524. if ( background && ( background.isCubeTexture || background.isWebGLRenderTargetCube ) ) {
  12525. if ( boxMesh === undefined ) {
  12526. boxMesh = new Mesh(
  12527. new BoxBufferGeometry( 1, 1, 1 ),
  12528. new ShaderMaterial( {
  12529. type: 'BackgroundCubeMaterial',
  12530. uniforms: UniformsUtils.clone( ShaderLib.cube.uniforms ),
  12531. vertexShader: ShaderLib.cube.vertexShader,
  12532. fragmentShader: ShaderLib.cube.fragmentShader,
  12533. side: BackSide,
  12534. depthTest: true,
  12535. depthWrite: false,
  12536. fog: false
  12537. } )
  12538. );
  12539. boxMesh.geometry.removeAttribute( 'normal' );
  12540. boxMesh.geometry.removeAttribute( 'uv' );
  12541. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  12542. this.matrixWorld.copyPosition( camera.matrixWorld );
  12543. };
  12544. // enable code injection for non-built-in material
  12545. Object.defineProperty( boxMesh.material, 'map', {
  12546. get: function () {
  12547. return this.uniforms.tCube.value;
  12548. }
  12549. } );
  12550. objects.update( boxMesh );
  12551. }
  12552. boxMesh.material.uniforms.tCube.value = ( background.isWebGLRenderTargetCube ) ? background.texture : background;
  12553. boxMesh.material.uniforms.tFlip.value = ( background.isWebGLRenderTargetCube ) ? 1 : - 1;
  12554. // push to the pre-sorted opaque render list
  12555. renderList.push( boxMesh, boxMesh.geometry, boxMesh.material, 0, null );
  12556. } else if ( background && background.isTexture ) {
  12557. if ( planeMesh === undefined ) {
  12558. planeMesh = new Mesh(
  12559. new PlaneBufferGeometry( 2, 2 ),
  12560. new ShaderMaterial( {
  12561. type: 'BackgroundMaterial',
  12562. uniforms: UniformsUtils.clone( ShaderLib.background.uniforms ),
  12563. vertexShader: ShaderLib.background.vertexShader,
  12564. fragmentShader: ShaderLib.background.fragmentShader,
  12565. side: FrontSide,
  12566. depthTest: true,
  12567. depthWrite: false,
  12568. fog: false
  12569. } )
  12570. );
  12571. planeMesh.geometry.removeAttribute( 'normal' );
  12572. // enable code injection for non-built-in material
  12573. Object.defineProperty( planeMesh.material, 'map', {
  12574. get: function () {
  12575. return this.uniforms.t2D.value;
  12576. }
  12577. } );
  12578. objects.update( planeMesh );
  12579. }
  12580. planeMesh.material.uniforms.t2D.value = background;
  12581. if ( background.matrixAutoUpdate === true ) {
  12582. background.updateMatrix();
  12583. }
  12584. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  12585. // push to the pre-sorted opaque render list
  12586. renderList.push( planeMesh, planeMesh.geometry, planeMesh.material, 0, null );
  12587. }
  12588. }
  12589. function setClear( color, alpha ) {
  12590. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  12591. }
  12592. return {
  12593. getClearColor: function () {
  12594. return clearColor;
  12595. },
  12596. setClearColor: function ( color, alpha ) {
  12597. clearColor.set( color );
  12598. clearAlpha = alpha !== undefined ? alpha : 1;
  12599. setClear( clearColor, clearAlpha );
  12600. },
  12601. getClearAlpha: function () {
  12602. return clearAlpha;
  12603. },
  12604. setClearAlpha: function ( alpha ) {
  12605. clearAlpha = alpha;
  12606. setClear( clearColor, clearAlpha );
  12607. },
  12608. render: render
  12609. };
  12610. }
  12611. /**
  12612. * @author mrdoob / http://mrdoob.com/
  12613. */
  12614. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  12615. var mode;
  12616. function setMode( value ) {
  12617. mode = value;
  12618. }
  12619. function render( start, count ) {
  12620. gl.drawArrays( mode, start, count );
  12621. info.update( count, mode );
  12622. }
  12623. function renderInstances( geometry, start, count ) {
  12624. var extension;
  12625. if ( capabilities.isWebGL2 ) {
  12626. extension = gl;
  12627. } else {
  12628. extension = extensions.get( 'ANGLE_instanced_arrays' );
  12629. if ( extension === null ) {
  12630. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  12631. return;
  12632. }
  12633. }
  12634. extension[ capabilities.isWebGL2 ? 'drawArraysInstanced' : 'drawArraysInstancedANGLE' ]( mode, start, count, geometry.maxInstancedCount );
  12635. info.update( count, mode, geometry.maxInstancedCount );
  12636. }
  12637. //
  12638. this.setMode = setMode;
  12639. this.render = render;
  12640. this.renderInstances = renderInstances;
  12641. }
  12642. /**
  12643. * @author mrdoob / http://mrdoob.com/
  12644. */
  12645. function WebGLCapabilities( gl, extensions, parameters ) {
  12646. var maxAnisotropy;
  12647. function getMaxAnisotropy() {
  12648. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  12649. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  12650. if ( extension !== null ) {
  12651. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  12652. } else {
  12653. maxAnisotropy = 0;
  12654. }
  12655. return maxAnisotropy;
  12656. }
  12657. function getMaxPrecision( precision ) {
  12658. if ( precision === 'highp' ) {
  12659. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  12660. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  12661. return 'highp';
  12662. }
  12663. precision = 'mediump';
  12664. }
  12665. if ( precision === 'mediump' ) {
  12666. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  12667. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  12668. return 'mediump';
  12669. }
  12670. }
  12671. return 'lowp';
  12672. }
  12673. var isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;
  12674. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  12675. var maxPrecision = getMaxPrecision( precision );
  12676. if ( maxPrecision !== precision ) {
  12677. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  12678. precision = maxPrecision;
  12679. }
  12680. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  12681. var maxTextures = gl.getParameter( 34930 );
  12682. var maxVertexTextures = gl.getParameter( 35660 );
  12683. var maxTextureSize = gl.getParameter( 3379 );
  12684. var maxCubemapSize = gl.getParameter( 34076 );
  12685. var maxAttributes = gl.getParameter( 34921 );
  12686. var maxVertexUniforms = gl.getParameter( 36347 );
  12687. var maxVaryings = gl.getParameter( 36348 );
  12688. var maxFragmentUniforms = gl.getParameter( 36349 );
  12689. var vertexTextures = maxVertexTextures > 0;
  12690. var floatFragmentTextures = isWebGL2 || !! extensions.get( 'OES_texture_float' );
  12691. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  12692. return {
  12693. isWebGL2: isWebGL2,
  12694. getMaxAnisotropy: getMaxAnisotropy,
  12695. getMaxPrecision: getMaxPrecision,
  12696. precision: precision,
  12697. logarithmicDepthBuffer: logarithmicDepthBuffer,
  12698. maxTextures: maxTextures,
  12699. maxVertexTextures: maxVertexTextures,
  12700. maxTextureSize: maxTextureSize,
  12701. maxCubemapSize: maxCubemapSize,
  12702. maxAttributes: maxAttributes,
  12703. maxVertexUniforms: maxVertexUniforms,
  12704. maxVaryings: maxVaryings,
  12705. maxFragmentUniforms: maxFragmentUniforms,
  12706. vertexTextures: vertexTextures,
  12707. floatFragmentTextures: floatFragmentTextures,
  12708. floatVertexTextures: floatVertexTextures
  12709. };
  12710. }
  12711. /**
  12712. * @author tschw
  12713. */
  12714. function WebGLClipping() {
  12715. var scope = this,
  12716. globalState = null,
  12717. numGlobalPlanes = 0,
  12718. localClippingEnabled = false,
  12719. renderingShadows = false,
  12720. plane = new Plane(),
  12721. viewNormalMatrix = new Matrix3(),
  12722. uniform = { value: null, needsUpdate: false };
  12723. this.uniform = uniform;
  12724. this.numPlanes = 0;
  12725. this.numIntersection = 0;
  12726. this.init = function ( planes, enableLocalClipping, camera ) {
  12727. var enabled =
  12728. planes.length !== 0 ||
  12729. enableLocalClipping ||
  12730. // enable state of previous frame - the clipping code has to
  12731. // run another frame in order to reset the state:
  12732. numGlobalPlanes !== 0 ||
  12733. localClippingEnabled;
  12734. localClippingEnabled = enableLocalClipping;
  12735. globalState = projectPlanes( planes, camera, 0 );
  12736. numGlobalPlanes = planes.length;
  12737. return enabled;
  12738. };
  12739. this.beginShadows = function () {
  12740. renderingShadows = true;
  12741. projectPlanes( null );
  12742. };
  12743. this.endShadows = function () {
  12744. renderingShadows = false;
  12745. resetGlobalState();
  12746. };
  12747. this.setState = function ( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  12748. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  12749. // there's no local clipping
  12750. if ( renderingShadows ) {
  12751. // there's no global clipping
  12752. projectPlanes( null );
  12753. } else {
  12754. resetGlobalState();
  12755. }
  12756. } else {
  12757. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  12758. lGlobal = nGlobal * 4,
  12759. dstArray = cache.clippingState || null;
  12760. uniform.value = dstArray; // ensure unique state
  12761. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  12762. for ( var i = 0; i !== lGlobal; ++ i ) {
  12763. dstArray[ i ] = globalState[ i ];
  12764. }
  12765. cache.clippingState = dstArray;
  12766. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  12767. this.numPlanes += nGlobal;
  12768. }
  12769. };
  12770. function resetGlobalState() {
  12771. if ( uniform.value !== globalState ) {
  12772. uniform.value = globalState;
  12773. uniform.needsUpdate = numGlobalPlanes > 0;
  12774. }
  12775. scope.numPlanes = numGlobalPlanes;
  12776. scope.numIntersection = 0;
  12777. }
  12778. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  12779. var nPlanes = planes !== null ? planes.length : 0,
  12780. dstArray = null;
  12781. if ( nPlanes !== 0 ) {
  12782. dstArray = uniform.value;
  12783. if ( skipTransform !== true || dstArray === null ) {
  12784. var flatSize = dstOffset + nPlanes * 4,
  12785. viewMatrix = camera.matrixWorldInverse;
  12786. viewNormalMatrix.getNormalMatrix( viewMatrix );
  12787. if ( dstArray === null || dstArray.length < flatSize ) {
  12788. dstArray = new Float32Array( flatSize );
  12789. }
  12790. for ( var i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  12791. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  12792. plane.normal.toArray( dstArray, i4 );
  12793. dstArray[ i4 + 3 ] = plane.constant;
  12794. }
  12795. }
  12796. uniform.value = dstArray;
  12797. uniform.needsUpdate = true;
  12798. }
  12799. scope.numPlanes = nPlanes;
  12800. return dstArray;
  12801. }
  12802. }
  12803. /**
  12804. * @author mrdoob / http://mrdoob.com/
  12805. */
  12806. function WebGLExtensions( gl ) {
  12807. var extensions = {};
  12808. return {
  12809. get: function ( name ) {
  12810. if ( extensions[ name ] !== undefined ) {
  12811. return extensions[ name ];
  12812. }
  12813. var extension;
  12814. switch ( name ) {
  12815. case 'WEBGL_depth_texture':
  12816. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  12817. break;
  12818. case 'EXT_texture_filter_anisotropic':
  12819. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  12820. break;
  12821. case 'WEBGL_compressed_texture_s3tc':
  12822. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  12823. break;
  12824. case 'WEBGL_compressed_texture_pvrtc':
  12825. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  12826. break;
  12827. default:
  12828. extension = gl.getExtension( name );
  12829. }
  12830. if ( extension === null ) {
  12831. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  12832. }
  12833. extensions[ name ] = extension;
  12834. return extension;
  12835. }
  12836. };
  12837. }
  12838. /**
  12839. * @author mrdoob / http://mrdoob.com/
  12840. */
  12841. function WebGLGeometries( gl, attributes, info ) {
  12842. var geometries = {};
  12843. var wireframeAttributes = {};
  12844. function onGeometryDispose( event ) {
  12845. var geometry = event.target;
  12846. var buffergeometry = geometries[ geometry.id ];
  12847. if ( buffergeometry.index !== null ) {
  12848. attributes.remove( buffergeometry.index );
  12849. }
  12850. for ( var name in buffergeometry.attributes ) {
  12851. attributes.remove( buffergeometry.attributes[ name ] );
  12852. }
  12853. geometry.removeEventListener( 'dispose', onGeometryDispose );
  12854. delete geometries[ geometry.id ];
  12855. var attribute = wireframeAttributes[ buffergeometry.id ];
  12856. if ( attribute ) {
  12857. attributes.remove( attribute );
  12858. delete wireframeAttributes[ buffergeometry.id ];
  12859. }
  12860. //
  12861. info.memory.geometries --;
  12862. }
  12863. function get( object, geometry ) {
  12864. var buffergeometry = geometries[ geometry.id ];
  12865. if ( buffergeometry ) return buffergeometry;
  12866. geometry.addEventListener( 'dispose', onGeometryDispose );
  12867. if ( geometry.isBufferGeometry ) {
  12868. buffergeometry = geometry;
  12869. } else if ( geometry.isGeometry ) {
  12870. if ( geometry._bufferGeometry === undefined ) {
  12871. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  12872. }
  12873. buffergeometry = geometry._bufferGeometry;
  12874. }
  12875. geometries[ geometry.id ] = buffergeometry;
  12876. info.memory.geometries ++;
  12877. return buffergeometry;
  12878. }
  12879. function update( geometry ) {
  12880. var index = geometry.index;
  12881. var geometryAttributes = geometry.attributes;
  12882. if ( index !== null ) {
  12883. attributes.update( index, 34963 );
  12884. }
  12885. for ( var name in geometryAttributes ) {
  12886. attributes.update( geometryAttributes[ name ], 34962 );
  12887. }
  12888. // morph targets
  12889. var morphAttributes = geometry.morphAttributes;
  12890. for ( var name in morphAttributes ) {
  12891. var array = morphAttributes[ name ];
  12892. for ( var i = 0, l = array.length; i < l; i ++ ) {
  12893. attributes.update( array[ i ], 34962 );
  12894. }
  12895. }
  12896. }
  12897. function getWireframeAttribute( geometry ) {
  12898. var attribute = wireframeAttributes[ geometry.id ];
  12899. if ( attribute ) return attribute;
  12900. var indices = [];
  12901. var geometryIndex = geometry.index;
  12902. var geometryAttributes = geometry.attributes;
  12903. // console.time( 'wireframe' );
  12904. if ( geometryIndex !== null ) {
  12905. var array = geometryIndex.array;
  12906. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  12907. var a = array[ i + 0 ];
  12908. var b = array[ i + 1 ];
  12909. var c = array[ i + 2 ];
  12910. indices.push( a, b, b, c, c, a );
  12911. }
  12912. } else {
  12913. var array = geometryAttributes.position.array;
  12914. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  12915. var a = i + 0;
  12916. var b = i + 1;
  12917. var c = i + 2;
  12918. indices.push( a, b, b, c, c, a );
  12919. }
  12920. }
  12921. // console.timeEnd( 'wireframe' );
  12922. attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  12923. attributes.update( attribute, 34963 );
  12924. wireframeAttributes[ geometry.id ] = attribute;
  12925. return attribute;
  12926. }
  12927. return {
  12928. get: get,
  12929. update: update,
  12930. getWireframeAttribute: getWireframeAttribute
  12931. };
  12932. }
  12933. /**
  12934. * @author mrdoob / http://mrdoob.com/
  12935. */
  12936. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  12937. var mode;
  12938. function setMode( value ) {
  12939. mode = value;
  12940. }
  12941. var type, bytesPerElement;
  12942. function setIndex( value ) {
  12943. type = value.type;
  12944. bytesPerElement = value.bytesPerElement;
  12945. }
  12946. function render( start, count ) {
  12947. gl.drawElements( mode, count, type, start * bytesPerElement );
  12948. info.update( count, mode );
  12949. }
  12950. function renderInstances( geometry, start, count ) {
  12951. var extension;
  12952. if ( capabilities.isWebGL2 ) {
  12953. extension = gl;
  12954. } else {
  12955. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  12956. if ( extension === null ) {
  12957. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  12958. return;
  12959. }
  12960. }
  12961. extension[ capabilities.isWebGL2 ? 'drawElementsInstanced' : 'drawElementsInstancedANGLE' ]( mode, count, type, start * bytesPerElement, geometry.maxInstancedCount );
  12962. info.update( count, mode, geometry.maxInstancedCount );
  12963. }
  12964. //
  12965. this.setMode = setMode;
  12966. this.setIndex = setIndex;
  12967. this.render = render;
  12968. this.renderInstances = renderInstances;
  12969. }
  12970. /**
  12971. * @author Mugen87 / https://github.com/Mugen87
  12972. */
  12973. function WebGLInfo( gl ) {
  12974. var memory = {
  12975. geometries: 0,
  12976. textures: 0
  12977. };
  12978. var render = {
  12979. frame: 0,
  12980. calls: 0,
  12981. triangles: 0,
  12982. points: 0,
  12983. lines: 0
  12984. };
  12985. function update( count, mode, instanceCount ) {
  12986. instanceCount = instanceCount || 1;
  12987. render.calls ++;
  12988. switch ( mode ) {
  12989. case 4:
  12990. render.triangles += instanceCount * ( count / 3 );
  12991. break;
  12992. case 5:
  12993. case 6:
  12994. render.triangles += instanceCount * ( count - 2 );
  12995. break;
  12996. case 1:
  12997. render.lines += instanceCount * ( count / 2 );
  12998. break;
  12999. case 3:
  13000. render.lines += instanceCount * ( count - 1 );
  13001. break;
  13002. case 2:
  13003. render.lines += instanceCount * count;
  13004. break;
  13005. case 0:
  13006. render.points += instanceCount * count;
  13007. break;
  13008. default:
  13009. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  13010. break;
  13011. }
  13012. }
  13013. function reset() {
  13014. render.frame ++;
  13015. render.calls = 0;
  13016. render.triangles = 0;
  13017. render.points = 0;
  13018. render.lines = 0;
  13019. }
  13020. return {
  13021. memory: memory,
  13022. render: render,
  13023. programs: null,
  13024. autoReset: true,
  13025. reset: reset,
  13026. update: update
  13027. };
  13028. }
  13029. /**
  13030. * @author mrdoob / http://mrdoob.com/
  13031. */
  13032. function absNumericalSort( a, b ) {
  13033. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  13034. }
  13035. function WebGLMorphtargets( gl ) {
  13036. var influencesList = {};
  13037. var morphInfluences = new Float32Array( 8 );
  13038. function update( object, geometry, material, program ) {
  13039. var objectInfluences = object.morphTargetInfluences;
  13040. var length = objectInfluences.length;
  13041. var influences = influencesList[ geometry.id ];
  13042. if ( influences === undefined ) {
  13043. // initialise list
  13044. influences = [];
  13045. for ( var i = 0; i < length; i ++ ) {
  13046. influences[ i ] = [ i, 0 ];
  13047. }
  13048. influencesList[ geometry.id ] = influences;
  13049. }
  13050. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  13051. var morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  13052. // Remove current morphAttributes
  13053. for ( var i = 0; i < length; i ++ ) {
  13054. var influence = influences[ i ];
  13055. if ( influence[ 1 ] !== 0 ) {
  13056. if ( morphTargets ) geometry.removeAttribute( 'morphTarget' + i );
  13057. if ( morphNormals ) geometry.removeAttribute( 'morphNormal' + i );
  13058. }
  13059. }
  13060. // Collect influences
  13061. for ( var i = 0; i < length; i ++ ) {
  13062. var influence = influences[ i ];
  13063. influence[ 0 ] = i;
  13064. influence[ 1 ] = objectInfluences[ i ];
  13065. }
  13066. influences.sort( absNumericalSort );
  13067. // Add morphAttributes
  13068. for ( var i = 0; i < 8; i ++ ) {
  13069. var influence = influences[ i ];
  13070. if ( influence ) {
  13071. var index = influence[ 0 ];
  13072. var value = influence[ 1 ];
  13073. if ( value ) {
  13074. if ( morphTargets ) geometry.addAttribute( 'morphTarget' + i, morphTargets[ index ] );
  13075. if ( morphNormals ) geometry.addAttribute( 'morphNormal' + i, morphNormals[ index ] );
  13076. morphInfluences[ i ] = value;
  13077. continue;
  13078. }
  13079. }
  13080. morphInfluences[ i ] = 0;
  13081. }
  13082. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  13083. }
  13084. return {
  13085. update: update
  13086. };
  13087. }
  13088. /**
  13089. * @author mrdoob / http://mrdoob.com/
  13090. */
  13091. function WebGLObjects( geometries, info ) {
  13092. var updateList = {};
  13093. function update( object ) {
  13094. var frame = info.render.frame;
  13095. var geometry = object.geometry;
  13096. var buffergeometry = geometries.get( object, geometry );
  13097. // Update once per frame
  13098. if ( updateList[ buffergeometry.id ] !== frame ) {
  13099. if ( geometry.isGeometry ) {
  13100. buffergeometry.updateFromObject( object );
  13101. }
  13102. geometries.update( buffergeometry );
  13103. updateList[ buffergeometry.id ] = frame;
  13104. }
  13105. return buffergeometry;
  13106. }
  13107. function dispose() {
  13108. updateList = {};
  13109. }
  13110. return {
  13111. update: update,
  13112. dispose: dispose
  13113. };
  13114. }
  13115. /**
  13116. * @author mrdoob / http://mrdoob.com/
  13117. */
  13118. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  13119. images = images !== undefined ? images : [];
  13120. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  13121. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  13122. this.flipY = false;
  13123. }
  13124. CubeTexture.prototype = Object.create( Texture.prototype );
  13125. CubeTexture.prototype.constructor = CubeTexture;
  13126. CubeTexture.prototype.isCubeTexture = true;
  13127. Object.defineProperty( CubeTexture.prototype, 'images', {
  13128. get: function () {
  13129. return this.image;
  13130. },
  13131. set: function ( value ) {
  13132. this.image = value;
  13133. }
  13134. } );
  13135. /**
  13136. * @author Artur Trzesiok
  13137. */
  13138. function DataTexture3D( data, width, height, depth ) {
  13139. // We're going to add .setXXX() methods for setting properties later.
  13140. // Users can still set in DataTexture3D directly.
  13141. //
  13142. // var texture = new THREE.DataTexture3D( data, width, height, depth );
  13143. // texture.anisotropy = 16;
  13144. //
  13145. // See #14839
  13146. Texture.call( this, null );
  13147. this.image = { data: data, width: width, height: height, depth: depth };
  13148. this.magFilter = NearestFilter;
  13149. this.minFilter = NearestFilter;
  13150. this.generateMipmaps = false;
  13151. this.flipY = false;
  13152. }
  13153. DataTexture3D.prototype = Object.create( Texture.prototype );
  13154. DataTexture3D.prototype.constructor = DataTexture3D;
  13155. DataTexture3D.prototype.isDataTexture3D = true;
  13156. /**
  13157. * @author tschw
  13158. * @author Mugen87 / https://github.com/Mugen87
  13159. * @author mrdoob / http://mrdoob.com/
  13160. *
  13161. * Uniforms of a program.
  13162. * Those form a tree structure with a special top-level container for the root,
  13163. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  13164. *
  13165. *
  13166. * Properties of inner nodes including the top-level container:
  13167. *
  13168. * .seq - array of nested uniforms
  13169. * .map - nested uniforms by name
  13170. *
  13171. *
  13172. * Methods of all nodes except the top-level container:
  13173. *
  13174. * .setValue( gl, value, [renderer] )
  13175. *
  13176. * uploads a uniform value(s)
  13177. * the 'renderer' parameter is needed for sampler uniforms
  13178. *
  13179. *
  13180. * Static methods of the top-level container (renderer factorizations):
  13181. *
  13182. * .upload( gl, seq, values, renderer )
  13183. *
  13184. * sets uniforms in 'seq' to 'values[id].value'
  13185. *
  13186. * .seqWithValue( seq, values ) : filteredSeq
  13187. *
  13188. * filters 'seq' entries with corresponding entry in values
  13189. *
  13190. *
  13191. * Methods of the top-level container (renderer factorizations):
  13192. *
  13193. * .setValue( gl, name, value )
  13194. *
  13195. * sets uniform with name 'name' to 'value'
  13196. *
  13197. * .set( gl, obj, prop )
  13198. *
  13199. * sets uniform from object and property with same name than uniform
  13200. *
  13201. * .setOptional( gl, obj, prop )
  13202. *
  13203. * like .set for an optional property of the object
  13204. *
  13205. */
  13206. var emptyTexture = new Texture();
  13207. var emptyTexture3d = new DataTexture3D();
  13208. var emptyCubeTexture = new CubeTexture();
  13209. // --- Base for inner nodes (including the root) ---
  13210. function UniformContainer() {
  13211. this.seq = [];
  13212. this.map = {};
  13213. }
  13214. // --- Utilities ---
  13215. // Array Caches (provide typed arrays for temporary by size)
  13216. var arrayCacheF32 = [];
  13217. var arrayCacheI32 = [];
  13218. // Float32Array caches used for uploading Matrix uniforms
  13219. var mat4array = new Float32Array( 16 );
  13220. var mat3array = new Float32Array( 9 );
  13221. var mat2array = new Float32Array( 4 );
  13222. // Flattening for arrays of vectors and matrices
  13223. function flatten( array, nBlocks, blockSize ) {
  13224. var firstElem = array[ 0 ];
  13225. if ( firstElem <= 0 || firstElem > 0 ) return array;
  13226. // unoptimized: ! isNaN( firstElem )
  13227. // see http://jacksondunstan.com/articles/983
  13228. var n = nBlocks * blockSize,
  13229. r = arrayCacheF32[ n ];
  13230. if ( r === undefined ) {
  13231. r = new Float32Array( n );
  13232. arrayCacheF32[ n ] = r;
  13233. }
  13234. if ( nBlocks !== 0 ) {
  13235. firstElem.toArray( r, 0 );
  13236. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  13237. offset += blockSize;
  13238. array[ i ].toArray( r, offset );
  13239. }
  13240. }
  13241. return r;
  13242. }
  13243. function arraysEqual( a, b ) {
  13244. if ( a.length !== b.length ) return false;
  13245. for ( var i = 0, l = a.length; i < l; i ++ ) {
  13246. if ( a[ i ] !== b[ i ] ) return false;
  13247. }
  13248. return true;
  13249. }
  13250. function copyArray( a, b ) {
  13251. for ( var i = 0, l = b.length; i < l; i ++ ) {
  13252. a[ i ] = b[ i ];
  13253. }
  13254. }
  13255. // Texture unit allocation
  13256. function allocTexUnits( renderer, n ) {
  13257. var r = arrayCacheI32[ n ];
  13258. if ( r === undefined ) {
  13259. r = new Int32Array( n );
  13260. arrayCacheI32[ n ] = r;
  13261. }
  13262. for ( var i = 0; i !== n; ++ i )
  13263. r[ i ] = renderer.allocTextureUnit();
  13264. return r;
  13265. }
  13266. // --- Setters ---
  13267. // Note: Defining these methods externally, because they come in a bunch
  13268. // and this way their names minify.
  13269. // Single scalar
  13270. function setValue1f( gl, v ) {
  13271. var cache = this.cache;
  13272. if ( cache[ 0 ] === v ) return;
  13273. gl.uniform1f( this.addr, v );
  13274. cache[ 0 ] = v;
  13275. }
  13276. function setValue1i( gl, v ) {
  13277. var cache = this.cache;
  13278. if ( cache[ 0 ] === v ) return;
  13279. gl.uniform1i( this.addr, v );
  13280. cache[ 0 ] = v;
  13281. }
  13282. // Single float vector (from flat array or THREE.VectorN)
  13283. function setValue2fv( gl, v ) {
  13284. var cache = this.cache;
  13285. if ( v.x !== undefined ) {
  13286. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  13287. gl.uniform2f( this.addr, v.x, v.y );
  13288. cache[ 0 ] = v.x;
  13289. cache[ 1 ] = v.y;
  13290. }
  13291. } else {
  13292. if ( arraysEqual( cache, v ) ) return;
  13293. gl.uniform2fv( this.addr, v );
  13294. copyArray( cache, v );
  13295. }
  13296. }
  13297. function setValue3fv( gl, v ) {
  13298. var cache = this.cache;
  13299. if ( v.x !== undefined ) {
  13300. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  13301. gl.uniform3f( this.addr, v.x, v.y, v.z );
  13302. cache[ 0 ] = v.x;
  13303. cache[ 1 ] = v.y;
  13304. cache[ 2 ] = v.z;
  13305. }
  13306. } else if ( v.r !== undefined ) {
  13307. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  13308. gl.uniform3f( this.addr, v.r, v.g, v.b );
  13309. cache[ 0 ] = v.r;
  13310. cache[ 1 ] = v.g;
  13311. cache[ 2 ] = v.b;
  13312. }
  13313. } else {
  13314. if ( arraysEqual( cache, v ) ) return;
  13315. gl.uniform3fv( this.addr, v );
  13316. copyArray( cache, v );
  13317. }
  13318. }
  13319. function setValue4fv( gl, v ) {
  13320. var cache = this.cache;
  13321. if ( v.x !== undefined ) {
  13322. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  13323. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  13324. cache[ 0 ] = v.x;
  13325. cache[ 1 ] = v.y;
  13326. cache[ 2 ] = v.z;
  13327. cache[ 3 ] = v.w;
  13328. }
  13329. } else {
  13330. if ( arraysEqual( cache, v ) ) return;
  13331. gl.uniform4fv( this.addr, v );
  13332. copyArray( cache, v );
  13333. }
  13334. }
  13335. // Single matrix (from flat array or MatrixN)
  13336. function setValue2fm( gl, v ) {
  13337. var cache = this.cache;
  13338. var elements = v.elements;
  13339. if ( elements === undefined ) {
  13340. if ( arraysEqual( cache, v ) ) return;
  13341. gl.uniformMatrix2fv( this.addr, false, v );
  13342. copyArray( cache, v );
  13343. } else {
  13344. if ( arraysEqual( cache, elements ) ) return;
  13345. mat2array.set( elements );
  13346. gl.uniformMatrix2fv( this.addr, false, mat2array );
  13347. copyArray( cache, elements );
  13348. }
  13349. }
  13350. function setValue3fm( gl, v ) {
  13351. var cache = this.cache;
  13352. var elements = v.elements;
  13353. if ( elements === undefined ) {
  13354. if ( arraysEqual( cache, v ) ) return;
  13355. gl.uniformMatrix3fv( this.addr, false, v );
  13356. copyArray( cache, v );
  13357. } else {
  13358. if ( arraysEqual( cache, elements ) ) return;
  13359. mat3array.set( elements );
  13360. gl.uniformMatrix3fv( this.addr, false, mat3array );
  13361. copyArray( cache, elements );
  13362. }
  13363. }
  13364. function setValue4fm( gl, v ) {
  13365. var cache = this.cache;
  13366. var elements = v.elements;
  13367. if ( elements === undefined ) {
  13368. if ( arraysEqual( cache, v ) ) return;
  13369. gl.uniformMatrix4fv( this.addr, false, v );
  13370. copyArray( cache, v );
  13371. } else {
  13372. if ( arraysEqual( cache, elements ) ) return;
  13373. mat4array.set( elements );
  13374. gl.uniformMatrix4fv( this.addr, false, mat4array );
  13375. copyArray( cache, elements );
  13376. }
  13377. }
  13378. // Single texture (2D / Cube)
  13379. function setValueT1( gl, v, renderer ) {
  13380. var cache = this.cache;
  13381. var unit = renderer.allocTextureUnit();
  13382. if ( cache[ 0 ] !== unit ) {
  13383. gl.uniform1i( this.addr, unit );
  13384. cache[ 0 ] = unit;
  13385. }
  13386. renderer.setTexture2D( v || emptyTexture, unit );
  13387. }
  13388. function setValueT3D1( gl, v, renderer ) {
  13389. var cache = this.cache;
  13390. var unit = renderer.allocTextureUnit();
  13391. if ( cache[ 0 ] !== unit ) {
  13392. gl.uniform1i( this.addr, unit );
  13393. cache[ 0 ] = unit;
  13394. }
  13395. renderer.setTexture3D( v || emptyTexture3d, unit );
  13396. }
  13397. function setValueT6( gl, v, renderer ) {
  13398. var cache = this.cache;
  13399. var unit = renderer.allocTextureUnit();
  13400. if ( cache[ 0 ] !== unit ) {
  13401. gl.uniform1i( this.addr, unit );
  13402. cache[ 0 ] = unit;
  13403. }
  13404. renderer.setTextureCube( v || emptyCubeTexture, unit );
  13405. }
  13406. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  13407. function setValue2iv( gl, v ) {
  13408. var cache = this.cache;
  13409. if ( arraysEqual( cache, v ) ) return;
  13410. gl.uniform2iv( this.addr, v );
  13411. copyArray( cache, v );
  13412. }
  13413. function setValue3iv( gl, v ) {
  13414. var cache = this.cache;
  13415. if ( arraysEqual( cache, v ) ) return;
  13416. gl.uniform3iv( this.addr, v );
  13417. copyArray( cache, v );
  13418. }
  13419. function setValue4iv( gl, v ) {
  13420. var cache = this.cache;
  13421. if ( arraysEqual( cache, v ) ) return;
  13422. gl.uniform4iv( this.addr, v );
  13423. copyArray( cache, v );
  13424. }
  13425. // Helper to pick the right setter for the singular case
  13426. function getSingularSetter( type ) {
  13427. switch ( type ) {
  13428. case 0x1406: return setValue1f; // FLOAT
  13429. case 0x8b50: return setValue2fv; // _VEC2
  13430. case 0x8b51: return setValue3fv; // _VEC3
  13431. case 0x8b52: return setValue4fv; // _VEC4
  13432. case 0x8b5a: return setValue2fm; // _MAT2
  13433. case 0x8b5b: return setValue3fm; // _MAT3
  13434. case 0x8b5c: return setValue4fm; // _MAT4
  13435. case 0x8b5e: case 0x8d66: return setValueT1; // SAMPLER_2D, SAMPLER_EXTERNAL_OES
  13436. case 0x8B5F: return setValueT3D1; // SAMPLER_3D
  13437. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  13438. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  13439. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  13440. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  13441. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  13442. }
  13443. }
  13444. // Array of scalars
  13445. function setValue1fv( gl, v ) {
  13446. var cache = this.cache;
  13447. if ( arraysEqual( cache, v ) ) return;
  13448. gl.uniform1fv( this.addr, v );
  13449. copyArray( cache, v );
  13450. }
  13451. function setValue1iv( gl, v ) {
  13452. var cache = this.cache;
  13453. if ( arraysEqual( cache, v ) ) return;
  13454. gl.uniform1iv( this.addr, v );
  13455. copyArray( cache, v );
  13456. }
  13457. // Array of vectors (flat or from THREE classes)
  13458. function setValueV2a( gl, v ) {
  13459. var cache = this.cache;
  13460. var data = flatten( v, this.size, 2 );
  13461. if ( arraysEqual( cache, data ) ) return;
  13462. gl.uniform2fv( this.addr, data );
  13463. this.updateCache( data );
  13464. }
  13465. function setValueV3a( gl, v ) {
  13466. var cache = this.cache;
  13467. var data = flatten( v, this.size, 3 );
  13468. if ( arraysEqual( cache, data ) ) return;
  13469. gl.uniform3fv( this.addr, data );
  13470. this.updateCache( data );
  13471. }
  13472. function setValueV4a( gl, v ) {
  13473. var cache = this.cache;
  13474. var data = flatten( v, this.size, 4 );
  13475. if ( arraysEqual( cache, data ) ) return;
  13476. gl.uniform4fv( this.addr, data );
  13477. this.updateCache( data );
  13478. }
  13479. // Array of matrices (flat or from THREE clases)
  13480. function setValueM2a( gl, v ) {
  13481. var cache = this.cache;
  13482. var data = flatten( v, this.size, 4 );
  13483. if ( arraysEqual( cache, data ) ) return;
  13484. gl.uniformMatrix2fv( this.addr, false, data );
  13485. this.updateCache( data );
  13486. }
  13487. function setValueM3a( gl, v ) {
  13488. var cache = this.cache;
  13489. var data = flatten( v, this.size, 9 );
  13490. if ( arraysEqual( cache, data ) ) return;
  13491. gl.uniformMatrix3fv( this.addr, false, data );
  13492. this.updateCache( data );
  13493. }
  13494. function setValueM4a( gl, v ) {
  13495. var cache = this.cache;
  13496. var data = flatten( v, this.size, 16 );
  13497. if ( arraysEqual( cache, data ) ) return;
  13498. gl.uniformMatrix4fv( this.addr, false, data );
  13499. this.updateCache( data );
  13500. }
  13501. // Array of textures (2D / Cube)
  13502. function setValueT1a( gl, v, renderer ) {
  13503. var cache = this.cache;
  13504. var n = v.length;
  13505. var units = allocTexUnits( renderer, n );
  13506. if ( arraysEqual( cache, units ) === false ) {
  13507. gl.uniform1iv( this.addr, units );
  13508. copyArray( cache, units );
  13509. }
  13510. for ( var i = 0; i !== n; ++ i ) {
  13511. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  13512. }
  13513. }
  13514. function setValueT6a( gl, v, renderer ) {
  13515. var cache = this.cache;
  13516. var n = v.length;
  13517. var units = allocTexUnits( renderer, n );
  13518. if ( arraysEqual( cache, units ) === false ) {
  13519. gl.uniform1iv( this.addr, units );
  13520. copyArray( cache, units );
  13521. }
  13522. for ( var i = 0; i !== n; ++ i ) {
  13523. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  13524. }
  13525. }
  13526. // Helper to pick the right setter for a pure (bottom-level) array
  13527. function getPureArraySetter( type ) {
  13528. switch ( type ) {
  13529. case 0x1406: return setValue1fv; // FLOAT
  13530. case 0x8b50: return setValueV2a; // _VEC2
  13531. case 0x8b51: return setValueV3a; // _VEC3
  13532. case 0x8b52: return setValueV4a; // _VEC4
  13533. case 0x8b5a: return setValueM2a; // _MAT2
  13534. case 0x8b5b: return setValueM3a; // _MAT3
  13535. case 0x8b5c: return setValueM4a; // _MAT4
  13536. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  13537. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  13538. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  13539. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  13540. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  13541. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  13542. }
  13543. }
  13544. // --- Uniform Classes ---
  13545. function SingleUniform( id, activeInfo, addr ) {
  13546. this.id = id;
  13547. this.addr = addr;
  13548. this.cache = [];
  13549. this.setValue = getSingularSetter( activeInfo.type );
  13550. // this.path = activeInfo.name; // DEBUG
  13551. }
  13552. function PureArrayUniform( id, activeInfo, addr ) {
  13553. this.id = id;
  13554. this.addr = addr;
  13555. this.cache = [];
  13556. this.size = activeInfo.size;
  13557. this.setValue = getPureArraySetter( activeInfo.type );
  13558. // this.path = activeInfo.name; // DEBUG
  13559. }
  13560. PureArrayUniform.prototype.updateCache = function ( data ) {
  13561. var cache = this.cache;
  13562. if ( data instanceof Float32Array && cache.length !== data.length ) {
  13563. this.cache = new Float32Array( data.length );
  13564. }
  13565. copyArray( cache, data );
  13566. };
  13567. function StructuredUniform( id ) {
  13568. this.id = id;
  13569. UniformContainer.call( this ); // mix-in
  13570. }
  13571. StructuredUniform.prototype.setValue = function ( gl, value, renderer ) {
  13572. var seq = this.seq;
  13573. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  13574. var u = seq[ i ];
  13575. u.setValue( gl, value[ u.id ], renderer );
  13576. }
  13577. };
  13578. // --- Top-level ---
  13579. // Parser - builds up the property tree from the path strings
  13580. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  13581. // extracts
  13582. // - the identifier (member name or array index)
  13583. // - followed by an optional right bracket (found when array index)
  13584. // - followed by an optional left bracket or dot (type of subscript)
  13585. //
  13586. // Note: These portions can be read in a non-overlapping fashion and
  13587. // allow straightforward parsing of the hierarchy that WebGL encodes
  13588. // in the uniform names.
  13589. function addUniform( container, uniformObject ) {
  13590. container.seq.push( uniformObject );
  13591. container.map[ uniformObject.id ] = uniformObject;
  13592. }
  13593. function parseUniform( activeInfo, addr, container ) {
  13594. var path = activeInfo.name,
  13595. pathLength = path.length;
  13596. // reset RegExp object, because of the early exit of a previous run
  13597. RePathPart.lastIndex = 0;
  13598. while ( true ) {
  13599. var match = RePathPart.exec( path ),
  13600. matchEnd = RePathPart.lastIndex,
  13601. id = match[ 1 ],
  13602. idIsIndex = match[ 2 ] === ']',
  13603. subscript = match[ 3 ];
  13604. if ( idIsIndex ) id = id | 0; // convert to integer
  13605. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  13606. // bare name or "pure" bottom-level array "[0]" suffix
  13607. addUniform( container, subscript === undefined ?
  13608. new SingleUniform( id, activeInfo, addr ) :
  13609. new PureArrayUniform( id, activeInfo, addr ) );
  13610. break;
  13611. } else {
  13612. // step into inner node / create it in case it doesn't exist
  13613. var map = container.map, next = map[ id ];
  13614. if ( next === undefined ) {
  13615. next = new StructuredUniform( id );
  13616. addUniform( container, next );
  13617. }
  13618. container = next;
  13619. }
  13620. }
  13621. }
  13622. // Root Container
  13623. function WebGLUniforms( gl, program, renderer ) {
  13624. UniformContainer.call( this );
  13625. this.renderer = renderer;
  13626. var n = gl.getProgramParameter( program, 35718 );
  13627. for ( var i = 0; i < n; ++ i ) {
  13628. var info = gl.getActiveUniform( program, i ),
  13629. addr = gl.getUniformLocation( program, info.name );
  13630. parseUniform( info, addr, this );
  13631. }
  13632. }
  13633. WebGLUniforms.prototype.setValue = function ( gl, name, value ) {
  13634. var u = this.map[ name ];
  13635. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  13636. };
  13637. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  13638. var v = object[ name ];
  13639. if ( v !== undefined ) this.setValue( gl, name, v );
  13640. };
  13641. // Static interface
  13642. WebGLUniforms.upload = function ( gl, seq, values, renderer ) {
  13643. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  13644. var u = seq[ i ],
  13645. v = values[ u.id ];
  13646. if ( v.needsUpdate !== false ) {
  13647. // note: always updating when .needsUpdate is undefined
  13648. u.setValue( gl, v.value, renderer );
  13649. }
  13650. }
  13651. };
  13652. WebGLUniforms.seqWithValue = function ( seq, values ) {
  13653. var r = [];
  13654. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  13655. var u = seq[ i ];
  13656. if ( u.id in values ) r.push( u );
  13657. }
  13658. return r;
  13659. };
  13660. /**
  13661. * @author mrdoob / http://mrdoob.com/
  13662. */
  13663. function addLineNumbers( string ) {
  13664. var lines = string.split( '\n' );
  13665. for ( var i = 0; i < lines.length; i ++ ) {
  13666. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  13667. }
  13668. return lines.join( '\n' );
  13669. }
  13670. function WebGLShader( gl, type, string ) {
  13671. var shader = gl.createShader( type );
  13672. gl.shaderSource( shader, string );
  13673. gl.compileShader( shader );
  13674. if ( gl.getShaderParameter( shader, 35713 ) === false ) {
  13675. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  13676. }
  13677. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  13678. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === 35633 ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  13679. }
  13680. // --enable-privileged-webgl-extension
  13681. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  13682. return shader;
  13683. }
  13684. /**
  13685. * @author mrdoob / http://mrdoob.com/
  13686. */
  13687. var programIdCount = 0;
  13688. function getEncodingComponents( encoding ) {
  13689. switch ( encoding ) {
  13690. case LinearEncoding:
  13691. return [ 'Linear', '( value )' ];
  13692. case sRGBEncoding:
  13693. return [ 'sRGB', '( value )' ];
  13694. case RGBEEncoding:
  13695. return [ 'RGBE', '( value )' ];
  13696. case RGBM7Encoding:
  13697. return [ 'RGBM', '( value, 7.0 )' ];
  13698. case RGBM16Encoding:
  13699. return [ 'RGBM', '( value, 16.0 )' ];
  13700. case RGBDEncoding:
  13701. return [ 'RGBD', '( value, 256.0 )' ];
  13702. case GammaEncoding:
  13703. return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
  13704. default:
  13705. throw new Error( 'unsupported encoding: ' + encoding );
  13706. }
  13707. }
  13708. function getTexelDecodingFunction( functionName, encoding ) {
  13709. var components = getEncodingComponents( encoding );
  13710. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
  13711. }
  13712. function getTexelEncodingFunction( functionName, encoding ) {
  13713. var components = getEncodingComponents( encoding );
  13714. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  13715. }
  13716. function getToneMappingFunction( functionName, toneMapping ) {
  13717. var toneMappingName;
  13718. switch ( toneMapping ) {
  13719. case LinearToneMapping:
  13720. toneMappingName = 'Linear';
  13721. break;
  13722. case ReinhardToneMapping:
  13723. toneMappingName = 'Reinhard';
  13724. break;
  13725. case Uncharted2ToneMapping:
  13726. toneMappingName = 'Uncharted2';
  13727. break;
  13728. case CineonToneMapping:
  13729. toneMappingName = 'OptimizedCineon';
  13730. break;
  13731. default:
  13732. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  13733. }
  13734. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  13735. }
  13736. function generateExtensions( extensions, parameters, rendererExtensions ) {
  13737. extensions = extensions || {};
  13738. var chunks = [
  13739. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || ( parameters.normalMap && ! parameters.objectSpaceNormalMap ) || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  13740. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  13741. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  13742. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  13743. ];
  13744. return chunks.filter( filterEmptyLine ).join( '\n' );
  13745. }
  13746. function generateDefines( defines ) {
  13747. var chunks = [];
  13748. for ( var name in defines ) {
  13749. var value = defines[ name ];
  13750. if ( value === false ) continue;
  13751. chunks.push( '#define ' + name + ' ' + value );
  13752. }
  13753. return chunks.join( '\n' );
  13754. }
  13755. function fetchAttributeLocations( gl, program ) {
  13756. var attributes = {};
  13757. var n = gl.getProgramParameter( program, 35721 );
  13758. for ( var i = 0; i < n; i ++ ) {
  13759. var info = gl.getActiveAttrib( program, i );
  13760. var name = info.name;
  13761. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  13762. attributes[ name ] = gl.getAttribLocation( program, name );
  13763. }
  13764. return attributes;
  13765. }
  13766. function filterEmptyLine( string ) {
  13767. return string !== '';
  13768. }
  13769. function replaceLightNums( string, parameters ) {
  13770. return string
  13771. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  13772. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  13773. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  13774. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  13775. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  13776. }
  13777. function replaceClippingPlaneNums( string, parameters ) {
  13778. return string
  13779. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  13780. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  13781. }
  13782. function parseIncludes( string ) {
  13783. var pattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  13784. function replace( match, include ) {
  13785. var replace = ShaderChunk[ include ];
  13786. if ( replace === undefined ) {
  13787. throw new Error( 'Can not resolve #include <' + include + '>' );
  13788. }
  13789. return parseIncludes( replace );
  13790. }
  13791. return string.replace( pattern, replace );
  13792. }
  13793. function unrollLoops( string ) {
  13794. var pattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  13795. function replace( match, start, end, snippet ) {
  13796. var unroll = '';
  13797. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  13798. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  13799. }
  13800. return unroll;
  13801. }
  13802. return string.replace( pattern, replace );
  13803. }
  13804. function WebGLProgram( renderer, extensions, code, material, shader, parameters, capabilities ) {
  13805. var gl = renderer.context;
  13806. var defines = material.defines;
  13807. var vertexShader = shader.vertexShader;
  13808. var fragmentShader = shader.fragmentShader;
  13809. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  13810. if ( parameters.shadowMapType === PCFShadowMap ) {
  13811. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  13812. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  13813. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  13814. }
  13815. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  13816. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  13817. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  13818. if ( parameters.envMap ) {
  13819. switch ( material.envMap.mapping ) {
  13820. case CubeReflectionMapping:
  13821. case CubeRefractionMapping:
  13822. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  13823. break;
  13824. case CubeUVReflectionMapping:
  13825. case CubeUVRefractionMapping:
  13826. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  13827. break;
  13828. case EquirectangularReflectionMapping:
  13829. case EquirectangularRefractionMapping:
  13830. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  13831. break;
  13832. case SphericalReflectionMapping:
  13833. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  13834. break;
  13835. }
  13836. switch ( material.envMap.mapping ) {
  13837. case CubeRefractionMapping:
  13838. case EquirectangularRefractionMapping:
  13839. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  13840. break;
  13841. }
  13842. switch ( material.combine ) {
  13843. case MultiplyOperation:
  13844. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  13845. break;
  13846. case MixOperation:
  13847. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  13848. break;
  13849. case AddOperation:
  13850. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  13851. break;
  13852. }
  13853. }
  13854. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  13855. // console.log( 'building new program ' );
  13856. //
  13857. var customExtensions = capabilities.isWebGL2 ? '' : generateExtensions( material.extensions, parameters, extensions );
  13858. var customDefines = generateDefines( defines );
  13859. //
  13860. var program = gl.createProgram();
  13861. var prefixVertex, prefixFragment;
  13862. if ( material.isRawShaderMaterial ) {
  13863. prefixVertex = [
  13864. customDefines
  13865. ].filter( filterEmptyLine ).join( '\n' );
  13866. if ( prefixVertex.length > 0 ) {
  13867. prefixVertex += '\n';
  13868. }
  13869. prefixFragment = [
  13870. customExtensions,
  13871. customDefines
  13872. ].filter( filterEmptyLine ).join( '\n' );
  13873. if ( prefixFragment.length > 0 ) {
  13874. prefixFragment += '\n';
  13875. }
  13876. } else {
  13877. prefixVertex = [
  13878. 'precision ' + parameters.precision + ' float;',
  13879. 'precision ' + parameters.precision + ' int;',
  13880. '#define SHADER_NAME ' + shader.name,
  13881. customDefines,
  13882. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  13883. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  13884. '#define MAX_BONES ' + parameters.maxBones,
  13885. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  13886. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  13887. parameters.map ? '#define USE_MAP' : '',
  13888. parameters.envMap ? '#define USE_ENVMAP' : '',
  13889. parameters.envMap ? '#define ' + envMapModeDefine : '',
  13890. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  13891. parameters.aoMap ? '#define USE_AOMAP' : '',
  13892. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  13893. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  13894. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  13895. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  13896. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  13897. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  13898. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  13899. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  13900. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  13901. parameters.vertexColors ? '#define USE_COLOR' : '',
  13902. parameters.flatShading ? '#define FLAT_SHADED' : '',
  13903. parameters.skinning ? '#define USE_SKINNING' : '',
  13904. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  13905. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  13906. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  13907. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  13908. parameters.flipSided ? '#define FLIP_SIDED' : '',
  13909. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  13910. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  13911. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  13912. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  13913. parameters.logarithmicDepthBuffer && ( capabilities.isWebGL2 || extensions.get( 'EXT_frag_depth' ) ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  13914. 'uniform mat4 modelMatrix;',
  13915. 'uniform mat4 modelViewMatrix;',
  13916. 'uniform mat4 projectionMatrix;',
  13917. 'uniform mat4 viewMatrix;',
  13918. 'uniform mat3 normalMatrix;',
  13919. 'uniform vec3 cameraPosition;',
  13920. 'attribute vec3 position;',
  13921. 'attribute vec3 normal;',
  13922. 'attribute vec2 uv;',
  13923. '#ifdef USE_COLOR',
  13924. ' attribute vec3 color;',
  13925. '#endif',
  13926. '#ifdef USE_MORPHTARGETS',
  13927. ' attribute vec3 morphTarget0;',
  13928. ' attribute vec3 morphTarget1;',
  13929. ' attribute vec3 morphTarget2;',
  13930. ' attribute vec3 morphTarget3;',
  13931. ' #ifdef USE_MORPHNORMALS',
  13932. ' attribute vec3 morphNormal0;',
  13933. ' attribute vec3 morphNormal1;',
  13934. ' attribute vec3 morphNormal2;',
  13935. ' attribute vec3 morphNormal3;',
  13936. ' #else',
  13937. ' attribute vec3 morphTarget4;',
  13938. ' attribute vec3 morphTarget5;',
  13939. ' attribute vec3 morphTarget6;',
  13940. ' attribute vec3 morphTarget7;',
  13941. ' #endif',
  13942. '#endif',
  13943. '#ifdef USE_SKINNING',
  13944. ' attribute vec4 skinIndex;',
  13945. ' attribute vec4 skinWeight;',
  13946. '#endif',
  13947. '\n'
  13948. ].filter( filterEmptyLine ).join( '\n' );
  13949. prefixFragment = [
  13950. customExtensions,
  13951. 'precision ' + parameters.precision + ' float;',
  13952. 'precision ' + parameters.precision + ' int;',
  13953. '#define SHADER_NAME ' + shader.name,
  13954. customDefines,
  13955. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + ( parameters.alphaTest % 1 ? '' : '.0' ) : '', // add '.0' if integer
  13956. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  13957. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  13958. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  13959. parameters.map ? '#define USE_MAP' : '',
  13960. parameters.envMap ? '#define USE_ENVMAP' : '',
  13961. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  13962. parameters.envMap ? '#define ' + envMapModeDefine : '',
  13963. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  13964. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  13965. parameters.aoMap ? '#define USE_AOMAP' : '',
  13966. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  13967. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  13968. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  13969. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  13970. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  13971. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  13972. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  13973. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  13974. parameters.vertexColors ? '#define USE_COLOR' : '',
  13975. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  13976. parameters.flatShading ? '#define FLAT_SHADED' : '',
  13977. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  13978. parameters.flipSided ? '#define FLIP_SIDED' : '',
  13979. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  13980. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  13981. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  13982. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  13983. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  13984. parameters.logarithmicDepthBuffer && ( capabilities.isWebGL2 || extensions.get( 'EXT_frag_depth' ) ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  13985. parameters.envMap && ( capabilities.isWebGL2 || extensions.get( 'EXT_shader_texture_lod' ) ) ? '#define TEXTURE_LOD_EXT' : '',
  13986. 'uniform mat4 viewMatrix;',
  13987. 'uniform vec3 cameraPosition;',
  13988. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  13989. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  13990. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  13991. parameters.dithering ? '#define DITHERING' : '',
  13992. ( parameters.outputEncoding || parameters.mapEncoding || parameters.matcapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ?
  13993. ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below
  13994. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  13995. parameters.matcapEncoding ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
  13996. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  13997. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  13998. parameters.outputEncoding ? getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ) : '',
  13999. parameters.depthPacking ? '#define DEPTH_PACKING ' + material.depthPacking : '',
  14000. '\n'
  14001. ].filter( filterEmptyLine ).join( '\n' );
  14002. }
  14003. vertexShader = parseIncludes( vertexShader );
  14004. vertexShader = replaceLightNums( vertexShader, parameters );
  14005. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  14006. fragmentShader = parseIncludes( fragmentShader );
  14007. fragmentShader = replaceLightNums( fragmentShader, parameters );
  14008. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  14009. vertexShader = unrollLoops( vertexShader );
  14010. fragmentShader = unrollLoops( fragmentShader );
  14011. if ( capabilities.isWebGL2 && ! material.isRawShaderMaterial ) {
  14012. var isGLSL3ShaderMaterial = false;
  14013. var versionRegex = /^\s*#version\s+300\s+es\s*\n/;
  14014. if ( material.isShaderMaterial &&
  14015. vertexShader.match( versionRegex ) !== null &&
  14016. fragmentShader.match( versionRegex ) !== null ) {
  14017. isGLSL3ShaderMaterial = true;
  14018. vertexShader = vertexShader.replace( versionRegex, '' );
  14019. fragmentShader = fragmentShader.replace( versionRegex, '' );
  14020. }
  14021. // GLSL 3.0 conversion
  14022. prefixVertex = [
  14023. '#version 300 es\n',
  14024. '#define attribute in',
  14025. '#define varying out',
  14026. '#define texture2D texture'
  14027. ].join( '\n' ) + '\n' + prefixVertex;
  14028. prefixFragment = [
  14029. '#version 300 es\n',
  14030. '#define varying in',
  14031. isGLSL3ShaderMaterial ? '' : 'out highp vec4 pc_fragColor;',
  14032. isGLSL3ShaderMaterial ? '' : '#define gl_FragColor pc_fragColor',
  14033. '#define gl_FragDepthEXT gl_FragDepth',
  14034. '#define texture2D texture',
  14035. '#define textureCube texture',
  14036. '#define texture2DProj textureProj',
  14037. '#define texture2DLodEXT textureLod',
  14038. '#define texture2DProjLodEXT textureProjLod',
  14039. '#define textureCubeLodEXT textureLod',
  14040. '#define texture2DGradEXT textureGrad',
  14041. '#define texture2DProjGradEXT textureProjGrad',
  14042. '#define textureCubeGradEXT textureGrad'
  14043. ].join( '\n' ) + '\n' + prefixFragment;
  14044. }
  14045. var vertexGlsl = prefixVertex + vertexShader;
  14046. var fragmentGlsl = prefixFragment + fragmentShader;
  14047. // console.log( '*VERTEX*', vertexGlsl );
  14048. // console.log( '*FRAGMENT*', fragmentGlsl );
  14049. var glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  14050. var glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  14051. gl.attachShader( program, glVertexShader );
  14052. gl.attachShader( program, glFragmentShader );
  14053. // Force a particular attribute to index 0.
  14054. if ( material.index0AttributeName !== undefined ) {
  14055. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  14056. } else if ( parameters.morphTargets === true ) {
  14057. // programs with morphTargets displace position out of attribute 0
  14058. gl.bindAttribLocation( program, 0, 'position' );
  14059. }
  14060. gl.linkProgram( program );
  14061. var programLog = gl.getProgramInfoLog( program ).trim();
  14062. var vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  14063. var fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  14064. var runnable = true;
  14065. var haveDiagnostics = true;
  14066. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  14067. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  14068. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  14069. runnable = false;
  14070. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter( program, 35715 ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  14071. } else if ( programLog !== '' ) {
  14072. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  14073. } else if ( vertexLog === '' || fragmentLog === '' ) {
  14074. haveDiagnostics = false;
  14075. }
  14076. if ( haveDiagnostics ) {
  14077. this.diagnostics = {
  14078. runnable: runnable,
  14079. material: material,
  14080. programLog: programLog,
  14081. vertexShader: {
  14082. log: vertexLog,
  14083. prefix: prefixVertex
  14084. },
  14085. fragmentShader: {
  14086. log: fragmentLog,
  14087. prefix: prefixFragment
  14088. }
  14089. };
  14090. }
  14091. // clean up
  14092. gl.deleteShader( glVertexShader );
  14093. gl.deleteShader( glFragmentShader );
  14094. // set up caching for uniform locations
  14095. var cachedUniforms;
  14096. this.getUniforms = function () {
  14097. if ( cachedUniforms === undefined ) {
  14098. cachedUniforms = new WebGLUniforms( gl, program, renderer );
  14099. }
  14100. return cachedUniforms;
  14101. };
  14102. // set up caching for attribute locations
  14103. var cachedAttributes;
  14104. this.getAttributes = function () {
  14105. if ( cachedAttributes === undefined ) {
  14106. cachedAttributes = fetchAttributeLocations( gl, program );
  14107. }
  14108. return cachedAttributes;
  14109. };
  14110. // free resource
  14111. this.destroy = function () {
  14112. gl.deleteProgram( program );
  14113. this.program = undefined;
  14114. };
  14115. // DEPRECATED
  14116. Object.defineProperties( this, {
  14117. uniforms: {
  14118. get: function () {
  14119. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  14120. return this.getUniforms();
  14121. }
  14122. },
  14123. attributes: {
  14124. get: function () {
  14125. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  14126. return this.getAttributes();
  14127. }
  14128. }
  14129. } );
  14130. //
  14131. this.name = shader.name;
  14132. this.id = programIdCount ++;
  14133. this.code = code;
  14134. this.usedTimes = 1;
  14135. this.program = program;
  14136. this.vertexShader = glVertexShader;
  14137. this.fragmentShader = glFragmentShader;
  14138. return this;
  14139. }
  14140. /**
  14141. * @author mrdoob / http://mrdoob.com/
  14142. */
  14143. function WebGLPrograms( renderer, extensions, capabilities ) {
  14144. var programs = [];
  14145. var shaderIDs = {
  14146. MeshDepthMaterial: 'depth',
  14147. MeshDistanceMaterial: 'distanceRGBA',
  14148. MeshNormalMaterial: 'normal',
  14149. MeshBasicMaterial: 'basic',
  14150. MeshLambertMaterial: 'lambert',
  14151. MeshPhongMaterial: 'phong',
  14152. MeshToonMaterial: 'phong',
  14153. MeshStandardMaterial: 'physical',
  14154. MeshPhysicalMaterial: 'physical',
  14155. MeshMatcapMaterial: 'matcap',
  14156. LineBasicMaterial: 'basic',
  14157. LineDashedMaterial: 'dashed',
  14158. PointsMaterial: 'points',
  14159. ShadowMaterial: 'shadow',
  14160. SpriteMaterial: 'sprite'
  14161. };
  14162. var parameterNames = [
  14163. "precision", "supportsVertexTextures", "map", "mapEncoding", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding",
  14164. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "displacementMap", "specularMap",
  14165. "roughnessMap", "metalnessMap", "gradientMap",
  14166. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  14167. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  14168. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  14169. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  14170. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  14171. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  14172. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering"
  14173. ];
  14174. function allocateBones( object ) {
  14175. var skeleton = object.skeleton;
  14176. var bones = skeleton.bones;
  14177. if ( capabilities.floatVertexTextures ) {
  14178. return 1024;
  14179. } else {
  14180. // default for when object is not specified
  14181. // ( for example when prebuilding shader to be used with multiple objects )
  14182. //
  14183. // - leave some extra space for other uniforms
  14184. // - limit here is ANGLE's 254 max uniform vectors
  14185. // (up to 54 should be safe)
  14186. var nVertexUniforms = capabilities.maxVertexUniforms;
  14187. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  14188. var maxBones = Math.min( nVertexMatrices, bones.length );
  14189. if ( maxBones < bones.length ) {
  14190. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  14191. return 0;
  14192. }
  14193. return maxBones;
  14194. }
  14195. }
  14196. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  14197. var encoding;
  14198. if ( ! map ) {
  14199. encoding = LinearEncoding;
  14200. } else if ( map.isTexture ) {
  14201. encoding = map.encoding;
  14202. } else if ( map.isWebGLRenderTarget ) {
  14203. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  14204. encoding = map.texture.encoding;
  14205. }
  14206. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  14207. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  14208. encoding = GammaEncoding;
  14209. }
  14210. return encoding;
  14211. }
  14212. this.getParameters = function ( material, lights, shadows, fog, nClipPlanes, nClipIntersection, object ) {
  14213. var shaderID = shaderIDs[ material.type ];
  14214. // heuristics to create shader parameters according to lights in the scene
  14215. // (not to blow over maxLights budget)
  14216. var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0;
  14217. var precision = capabilities.precision;
  14218. if ( material.precision !== null ) {
  14219. precision = capabilities.getMaxPrecision( material.precision );
  14220. if ( precision !== material.precision ) {
  14221. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  14222. }
  14223. }
  14224. var currentRenderTarget = renderer.getRenderTarget();
  14225. var parameters = {
  14226. shaderID: shaderID,
  14227. precision: precision,
  14228. supportsVertexTextures: capabilities.vertexTextures,
  14229. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  14230. map: !! material.map,
  14231. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  14232. matcap: !! material.matcap,
  14233. matcapEncoding: getTextureEncodingFromMap( material.matcap, renderer.gammaInput ),
  14234. envMap: !! material.envMap,
  14235. envMapMode: material.envMap && material.envMap.mapping,
  14236. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  14237. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  14238. lightMap: !! material.lightMap,
  14239. aoMap: !! material.aoMap,
  14240. emissiveMap: !! material.emissiveMap,
  14241. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  14242. bumpMap: !! material.bumpMap,
  14243. normalMap: !! material.normalMap,
  14244. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  14245. displacementMap: !! material.displacementMap,
  14246. roughnessMap: !! material.roughnessMap,
  14247. metalnessMap: !! material.metalnessMap,
  14248. specularMap: !! material.specularMap,
  14249. alphaMap: !! material.alphaMap,
  14250. gradientMap: !! material.gradientMap,
  14251. combine: material.combine,
  14252. vertexColors: material.vertexColors,
  14253. fog: !! fog,
  14254. useFog: material.fog,
  14255. fogExp: ( fog && fog.isFogExp2 ),
  14256. flatShading: material.flatShading,
  14257. sizeAttenuation: material.sizeAttenuation,
  14258. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  14259. skinning: material.skinning && maxBones > 0,
  14260. maxBones: maxBones,
  14261. useVertexTexture: capabilities.floatVertexTextures,
  14262. morphTargets: material.morphTargets,
  14263. morphNormals: material.morphNormals,
  14264. maxMorphTargets: renderer.maxMorphTargets,
  14265. maxMorphNormals: renderer.maxMorphNormals,
  14266. numDirLights: lights.directional.length,
  14267. numPointLights: lights.point.length,
  14268. numSpotLights: lights.spot.length,
  14269. numRectAreaLights: lights.rectArea.length,
  14270. numHemiLights: lights.hemi.length,
  14271. numClippingPlanes: nClipPlanes,
  14272. numClipIntersection: nClipIntersection,
  14273. dithering: material.dithering,
  14274. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && shadows.length > 0,
  14275. shadowMapType: renderer.shadowMap.type,
  14276. toneMapping: renderer.toneMapping,
  14277. physicallyCorrectLights: renderer.physicallyCorrectLights,
  14278. premultipliedAlpha: material.premultipliedAlpha,
  14279. alphaTest: material.alphaTest,
  14280. doubleSided: material.side === DoubleSide,
  14281. flipSided: material.side === BackSide,
  14282. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  14283. };
  14284. return parameters;
  14285. };
  14286. this.getProgramCode = function ( material, parameters ) {
  14287. var array = [];
  14288. if ( parameters.shaderID ) {
  14289. array.push( parameters.shaderID );
  14290. } else {
  14291. array.push( material.fragmentShader );
  14292. array.push( material.vertexShader );
  14293. }
  14294. if ( material.defines !== undefined ) {
  14295. for ( var name in material.defines ) {
  14296. array.push( name );
  14297. array.push( material.defines[ name ] );
  14298. }
  14299. }
  14300. for ( var i = 0; i < parameterNames.length; i ++ ) {
  14301. array.push( parameters[ parameterNames[ i ] ] );
  14302. }
  14303. array.push( material.onBeforeCompile.toString() );
  14304. array.push( renderer.gammaOutput );
  14305. array.push( renderer.gammaFactor );
  14306. return array.join();
  14307. };
  14308. this.acquireProgram = function ( material, shader, parameters, code ) {
  14309. var program;
  14310. // Check if code has been already compiled
  14311. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  14312. var programInfo = programs[ p ];
  14313. if ( programInfo.code === code ) {
  14314. program = programInfo;
  14315. ++ program.usedTimes;
  14316. break;
  14317. }
  14318. }
  14319. if ( program === undefined ) {
  14320. program = new WebGLProgram( renderer, extensions, code, material, shader, parameters, capabilities );
  14321. programs.push( program );
  14322. }
  14323. return program;
  14324. };
  14325. this.releaseProgram = function ( program ) {
  14326. if ( -- program.usedTimes === 0 ) {
  14327. // Remove from unordered set
  14328. var i = programs.indexOf( program );
  14329. programs[ i ] = programs[ programs.length - 1 ];
  14330. programs.pop();
  14331. // Free WebGL resources
  14332. program.destroy();
  14333. }
  14334. };
  14335. // Exposed for resource monitoring & error feedback via renderer.info:
  14336. this.programs = programs;
  14337. }
  14338. /**
  14339. * @author fordacious / fordacious.github.io
  14340. */
  14341. function WebGLProperties() {
  14342. var properties = new WeakMap();
  14343. function get( object ) {
  14344. var map = properties.get( object );
  14345. if ( map === undefined ) {
  14346. map = {};
  14347. properties.set( object, map );
  14348. }
  14349. return map;
  14350. }
  14351. function remove( object ) {
  14352. properties.delete( object );
  14353. }
  14354. function update( object, key, value ) {
  14355. properties.get( object )[ key ] = value;
  14356. }
  14357. function dispose() {
  14358. properties = new WeakMap();
  14359. }
  14360. return {
  14361. get: get,
  14362. remove: remove,
  14363. update: update,
  14364. dispose: dispose
  14365. };
  14366. }
  14367. /**
  14368. * @author mrdoob / http://mrdoob.com/
  14369. */
  14370. function painterSortStable( a, b ) {
  14371. if ( a.renderOrder !== b.renderOrder ) {
  14372. return a.renderOrder - b.renderOrder;
  14373. } else if ( a.program && b.program && a.program !== b.program ) {
  14374. return a.program.id - b.program.id;
  14375. } else if ( a.material.id !== b.material.id ) {
  14376. return a.material.id - b.material.id;
  14377. } else if ( a.z !== b.z ) {
  14378. return a.z - b.z;
  14379. } else {
  14380. return a.id - b.id;
  14381. }
  14382. }
  14383. function reversePainterSortStable( a, b ) {
  14384. if ( a.renderOrder !== b.renderOrder ) {
  14385. return a.renderOrder - b.renderOrder;
  14386. } if ( a.z !== b.z ) {
  14387. return b.z - a.z;
  14388. } else {
  14389. return a.id - b.id;
  14390. }
  14391. }
  14392. function WebGLRenderList() {
  14393. var renderItems = [];
  14394. var renderItemsIndex = 0;
  14395. var opaque = [];
  14396. var transparent = [];
  14397. function init() {
  14398. renderItemsIndex = 0;
  14399. opaque.length = 0;
  14400. transparent.length = 0;
  14401. }
  14402. function push( object, geometry, material, z, group ) {
  14403. var renderItem = renderItems[ renderItemsIndex ];
  14404. if ( renderItem === undefined ) {
  14405. renderItem = {
  14406. id: object.id,
  14407. object: object,
  14408. geometry: geometry,
  14409. material: material,
  14410. program: material.program,
  14411. renderOrder: object.renderOrder,
  14412. z: z,
  14413. group: group
  14414. };
  14415. renderItems[ renderItemsIndex ] = renderItem;
  14416. } else {
  14417. renderItem.id = object.id;
  14418. renderItem.object = object;
  14419. renderItem.geometry = geometry;
  14420. renderItem.material = material;
  14421. renderItem.program = material.program;
  14422. renderItem.renderOrder = object.renderOrder;
  14423. renderItem.z = z;
  14424. renderItem.group = group;
  14425. }
  14426. ( material.transparent === true ? transparent : opaque ).push( renderItem );
  14427. renderItemsIndex ++;
  14428. }
  14429. function sort() {
  14430. if ( opaque.length > 1 ) opaque.sort( painterSortStable );
  14431. if ( transparent.length > 1 ) transparent.sort( reversePainterSortStable );
  14432. }
  14433. return {
  14434. opaque: opaque,
  14435. transparent: transparent,
  14436. init: init,
  14437. push: push,
  14438. sort: sort
  14439. };
  14440. }
  14441. function WebGLRenderLists() {
  14442. var lists = {};
  14443. function get( scene, camera ) {
  14444. var cameras = lists[ scene.id ];
  14445. var list;
  14446. if ( cameras === undefined ) {
  14447. list = new WebGLRenderList();
  14448. lists[ scene.id ] = {};
  14449. lists[ scene.id ][ camera.id ] = list;
  14450. } else {
  14451. list = cameras[ camera.id ];
  14452. if ( list === undefined ) {
  14453. list = new WebGLRenderList();
  14454. cameras[ camera.id ] = list;
  14455. }
  14456. }
  14457. return list;
  14458. }
  14459. function dispose() {
  14460. lists = {};
  14461. }
  14462. return {
  14463. get: get,
  14464. dispose: dispose
  14465. };
  14466. }
  14467. /**
  14468. * @author mrdoob / http://mrdoob.com/
  14469. */
  14470. function UniformsCache() {
  14471. var lights = {};
  14472. return {
  14473. get: function ( light ) {
  14474. if ( lights[ light.id ] !== undefined ) {
  14475. return lights[ light.id ];
  14476. }
  14477. var uniforms;
  14478. switch ( light.type ) {
  14479. case 'DirectionalLight':
  14480. uniforms = {
  14481. direction: new Vector3(),
  14482. color: new Color(),
  14483. shadow: false,
  14484. shadowBias: 0,
  14485. shadowRadius: 1,
  14486. shadowMapSize: new Vector2()
  14487. };
  14488. break;
  14489. case 'SpotLight':
  14490. uniforms = {
  14491. position: new Vector3(),
  14492. direction: new Vector3(),
  14493. color: new Color(),
  14494. distance: 0,
  14495. coneCos: 0,
  14496. penumbraCos: 0,
  14497. decay: 0,
  14498. shadow: false,
  14499. shadowBias: 0,
  14500. shadowRadius: 1,
  14501. shadowMapSize: new Vector2()
  14502. };
  14503. break;
  14504. case 'PointLight':
  14505. uniforms = {
  14506. position: new Vector3(),
  14507. color: new Color(),
  14508. distance: 0,
  14509. decay: 0,
  14510. shadow: false,
  14511. shadowBias: 0,
  14512. shadowRadius: 1,
  14513. shadowMapSize: new Vector2(),
  14514. shadowCameraNear: 1,
  14515. shadowCameraFar: 1000
  14516. };
  14517. break;
  14518. case 'HemisphereLight':
  14519. uniforms = {
  14520. direction: new Vector3(),
  14521. skyColor: new Color(),
  14522. groundColor: new Color()
  14523. };
  14524. break;
  14525. case 'RectAreaLight':
  14526. uniforms = {
  14527. color: new Color(),
  14528. position: new Vector3(),
  14529. halfWidth: new Vector3(),
  14530. halfHeight: new Vector3()
  14531. // TODO (abelnation): set RectAreaLight shadow uniforms
  14532. };
  14533. break;
  14534. }
  14535. lights[ light.id ] = uniforms;
  14536. return uniforms;
  14537. }
  14538. };
  14539. }
  14540. var count = 0;
  14541. function WebGLLights() {
  14542. var cache = new UniformsCache();
  14543. var state = {
  14544. id: count ++,
  14545. hash: {
  14546. stateID: - 1,
  14547. directionalLength: - 1,
  14548. pointLength: - 1,
  14549. spotLength: - 1,
  14550. rectAreaLength: - 1,
  14551. hemiLength: - 1,
  14552. shadowsLength: - 1
  14553. },
  14554. ambient: [ 0, 0, 0 ],
  14555. directional: [],
  14556. directionalShadowMap: [],
  14557. directionalShadowMatrix: [],
  14558. spot: [],
  14559. spotShadowMap: [],
  14560. spotShadowMatrix: [],
  14561. rectArea: [],
  14562. point: [],
  14563. pointShadowMap: [],
  14564. pointShadowMatrix: [],
  14565. hemi: []
  14566. };
  14567. var vector3 = new Vector3();
  14568. var matrix4 = new Matrix4();
  14569. var matrix42 = new Matrix4();
  14570. function setup( lights, shadows, camera ) {
  14571. var r = 0, g = 0, b = 0;
  14572. var directionalLength = 0;
  14573. var pointLength = 0;
  14574. var spotLength = 0;
  14575. var rectAreaLength = 0;
  14576. var hemiLength = 0;
  14577. var viewMatrix = camera.matrixWorldInverse;
  14578. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  14579. var light = lights[ i ];
  14580. var color = light.color;
  14581. var intensity = light.intensity;
  14582. var distance = light.distance;
  14583. var shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  14584. if ( light.isAmbientLight ) {
  14585. r += color.r * intensity;
  14586. g += color.g * intensity;
  14587. b += color.b * intensity;
  14588. } else if ( light.isDirectionalLight ) {
  14589. var uniforms = cache.get( light );
  14590. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  14591. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  14592. vector3.setFromMatrixPosition( light.target.matrixWorld );
  14593. uniforms.direction.sub( vector3 );
  14594. uniforms.direction.transformDirection( viewMatrix );
  14595. uniforms.shadow = light.castShadow;
  14596. if ( light.castShadow ) {
  14597. var shadow = light.shadow;
  14598. uniforms.shadowBias = shadow.bias;
  14599. uniforms.shadowRadius = shadow.radius;
  14600. uniforms.shadowMapSize = shadow.mapSize;
  14601. }
  14602. state.directionalShadowMap[ directionalLength ] = shadowMap;
  14603. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  14604. state.directional[ directionalLength ] = uniforms;
  14605. directionalLength ++;
  14606. } else if ( light.isSpotLight ) {
  14607. var uniforms = cache.get( light );
  14608. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  14609. uniforms.position.applyMatrix4( viewMatrix );
  14610. uniforms.color.copy( color ).multiplyScalar( intensity );
  14611. uniforms.distance = distance;
  14612. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  14613. vector3.setFromMatrixPosition( light.target.matrixWorld );
  14614. uniforms.direction.sub( vector3 );
  14615. uniforms.direction.transformDirection( viewMatrix );
  14616. uniforms.coneCos = Math.cos( light.angle );
  14617. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  14618. uniforms.decay = light.decay;
  14619. uniforms.shadow = light.castShadow;
  14620. if ( light.castShadow ) {
  14621. var shadow = light.shadow;
  14622. uniforms.shadowBias = shadow.bias;
  14623. uniforms.shadowRadius = shadow.radius;
  14624. uniforms.shadowMapSize = shadow.mapSize;
  14625. }
  14626. state.spotShadowMap[ spotLength ] = shadowMap;
  14627. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  14628. state.spot[ spotLength ] = uniforms;
  14629. spotLength ++;
  14630. } else if ( light.isRectAreaLight ) {
  14631. var uniforms = cache.get( light );
  14632. // (a) intensity is the total visible light emitted
  14633. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  14634. // (b) intensity is the brightness of the light
  14635. uniforms.color.copy( color ).multiplyScalar( intensity );
  14636. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  14637. uniforms.position.applyMatrix4( viewMatrix );
  14638. // extract local rotation of light to derive width/height half vectors
  14639. matrix42.identity();
  14640. matrix4.copy( light.matrixWorld );
  14641. matrix4.premultiply( viewMatrix );
  14642. matrix42.extractRotation( matrix4 );
  14643. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  14644. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  14645. uniforms.halfWidth.applyMatrix4( matrix42 );
  14646. uniforms.halfHeight.applyMatrix4( matrix42 );
  14647. // TODO (abelnation): RectAreaLight distance?
  14648. // uniforms.distance = distance;
  14649. state.rectArea[ rectAreaLength ] = uniforms;
  14650. rectAreaLength ++;
  14651. } else if ( light.isPointLight ) {
  14652. var uniforms = cache.get( light );
  14653. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  14654. uniforms.position.applyMatrix4( viewMatrix );
  14655. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  14656. uniforms.distance = light.distance;
  14657. uniforms.decay = light.decay;
  14658. uniforms.shadow = light.castShadow;
  14659. if ( light.castShadow ) {
  14660. var shadow = light.shadow;
  14661. uniforms.shadowBias = shadow.bias;
  14662. uniforms.shadowRadius = shadow.radius;
  14663. uniforms.shadowMapSize = shadow.mapSize;
  14664. uniforms.shadowCameraNear = shadow.camera.near;
  14665. uniforms.shadowCameraFar = shadow.camera.far;
  14666. }
  14667. state.pointShadowMap[ pointLength ] = shadowMap;
  14668. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  14669. state.point[ pointLength ] = uniforms;
  14670. pointLength ++;
  14671. } else if ( light.isHemisphereLight ) {
  14672. var uniforms = cache.get( light );
  14673. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  14674. uniforms.direction.transformDirection( viewMatrix );
  14675. uniforms.direction.normalize();
  14676. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  14677. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  14678. state.hemi[ hemiLength ] = uniforms;
  14679. hemiLength ++;
  14680. }
  14681. }
  14682. state.ambient[ 0 ] = r;
  14683. state.ambient[ 1 ] = g;
  14684. state.ambient[ 2 ] = b;
  14685. state.directional.length = directionalLength;
  14686. state.spot.length = spotLength;
  14687. state.rectArea.length = rectAreaLength;
  14688. state.point.length = pointLength;
  14689. state.hemi.length = hemiLength;
  14690. state.hash.stateID = state.id;
  14691. state.hash.directionalLength = directionalLength;
  14692. state.hash.pointLength = pointLength;
  14693. state.hash.spotLength = spotLength;
  14694. state.hash.rectAreaLength = rectAreaLength;
  14695. state.hash.hemiLength = hemiLength;
  14696. state.hash.shadowsLength = shadows.length;
  14697. }
  14698. return {
  14699. setup: setup,
  14700. state: state
  14701. };
  14702. }
  14703. /**
  14704. * @author Mugen87 / https://github.com/Mugen87
  14705. */
  14706. function WebGLRenderState() {
  14707. var lights = new WebGLLights();
  14708. var lightsArray = [];
  14709. var shadowsArray = [];
  14710. function init() {
  14711. lightsArray.length = 0;
  14712. shadowsArray.length = 0;
  14713. }
  14714. function pushLight( light ) {
  14715. lightsArray.push( light );
  14716. }
  14717. function pushShadow( shadowLight ) {
  14718. shadowsArray.push( shadowLight );
  14719. }
  14720. function setupLights( camera ) {
  14721. lights.setup( lightsArray, shadowsArray, camera );
  14722. }
  14723. var state = {
  14724. lightsArray: lightsArray,
  14725. shadowsArray: shadowsArray,
  14726. lights: lights
  14727. };
  14728. return {
  14729. init: init,
  14730. state: state,
  14731. setupLights: setupLights,
  14732. pushLight: pushLight,
  14733. pushShadow: pushShadow
  14734. };
  14735. }
  14736. function WebGLRenderStates() {
  14737. var renderStates = {};
  14738. function get( scene, camera ) {
  14739. var renderState;
  14740. if ( renderStates[ scene.id ] === undefined ) {
  14741. renderState = new WebGLRenderState();
  14742. renderStates[ scene.id ] = {};
  14743. renderStates[ scene.id ][ camera.id ] = renderState;
  14744. } else {
  14745. if ( renderStates[ scene.id ][ camera.id ] === undefined ) {
  14746. renderState = new WebGLRenderState();
  14747. renderStates[ scene.id ][ camera.id ] = renderState;
  14748. } else {
  14749. renderState = renderStates[ scene.id ][ camera.id ];
  14750. }
  14751. }
  14752. return renderState;
  14753. }
  14754. function dispose() {
  14755. renderStates = {};
  14756. }
  14757. return {
  14758. get: get,
  14759. dispose: dispose
  14760. };
  14761. }
  14762. /**
  14763. * @author mrdoob / http://mrdoob.com/
  14764. * @author alteredq / http://alteredqualia.com/
  14765. * @author bhouston / https://clara.io
  14766. * @author WestLangley / http://github.com/WestLangley
  14767. *
  14768. * parameters = {
  14769. *
  14770. * opacity: <float>,
  14771. *
  14772. * map: new THREE.Texture( <Image> ),
  14773. *
  14774. * alphaMap: new THREE.Texture( <Image> ),
  14775. *
  14776. * displacementMap: new THREE.Texture( <Image> ),
  14777. * displacementScale: <float>,
  14778. * displacementBias: <float>,
  14779. *
  14780. * wireframe: <boolean>,
  14781. * wireframeLinewidth: <float>
  14782. * }
  14783. */
  14784. function MeshDepthMaterial( parameters ) {
  14785. Material.call( this );
  14786. this.type = 'MeshDepthMaterial';
  14787. this.depthPacking = BasicDepthPacking;
  14788. this.skinning = false;
  14789. this.morphTargets = false;
  14790. this.map = null;
  14791. this.alphaMap = null;
  14792. this.displacementMap = null;
  14793. this.displacementScale = 1;
  14794. this.displacementBias = 0;
  14795. this.wireframe = false;
  14796. this.wireframeLinewidth = 1;
  14797. this.fog = false;
  14798. this.lights = false;
  14799. this.setValues( parameters );
  14800. }
  14801. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  14802. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  14803. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  14804. MeshDepthMaterial.prototype.copy = function ( source ) {
  14805. Material.prototype.copy.call( this, source );
  14806. this.depthPacking = source.depthPacking;
  14807. this.skinning = source.skinning;
  14808. this.morphTargets = source.morphTargets;
  14809. this.map = source.map;
  14810. this.alphaMap = source.alphaMap;
  14811. this.displacementMap = source.displacementMap;
  14812. this.displacementScale = source.displacementScale;
  14813. this.displacementBias = source.displacementBias;
  14814. this.wireframe = source.wireframe;
  14815. this.wireframeLinewidth = source.wireframeLinewidth;
  14816. return this;
  14817. };
  14818. /**
  14819. * @author WestLangley / http://github.com/WestLangley
  14820. *
  14821. * parameters = {
  14822. *
  14823. * referencePosition: <float>,
  14824. * nearDistance: <float>,
  14825. * farDistance: <float>,
  14826. *
  14827. * skinning: <bool>,
  14828. * morphTargets: <bool>,
  14829. *
  14830. * map: new THREE.Texture( <Image> ),
  14831. *
  14832. * alphaMap: new THREE.Texture( <Image> ),
  14833. *
  14834. * displacementMap: new THREE.Texture( <Image> ),
  14835. * displacementScale: <float>,
  14836. * displacementBias: <float>
  14837. *
  14838. * }
  14839. */
  14840. function MeshDistanceMaterial( parameters ) {
  14841. Material.call( this );
  14842. this.type = 'MeshDistanceMaterial';
  14843. this.referencePosition = new Vector3();
  14844. this.nearDistance = 1;
  14845. this.farDistance = 1000;
  14846. this.skinning = false;
  14847. this.morphTargets = false;
  14848. this.map = null;
  14849. this.alphaMap = null;
  14850. this.displacementMap = null;
  14851. this.displacementScale = 1;
  14852. this.displacementBias = 0;
  14853. this.fog = false;
  14854. this.lights = false;
  14855. this.setValues( parameters );
  14856. }
  14857. MeshDistanceMaterial.prototype = Object.create( Material.prototype );
  14858. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  14859. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  14860. MeshDistanceMaterial.prototype.copy = function ( source ) {
  14861. Material.prototype.copy.call( this, source );
  14862. this.referencePosition.copy( source.referencePosition );
  14863. this.nearDistance = source.nearDistance;
  14864. this.farDistance = source.farDistance;
  14865. this.skinning = source.skinning;
  14866. this.morphTargets = source.morphTargets;
  14867. this.map = source.map;
  14868. this.alphaMap = source.alphaMap;
  14869. this.displacementMap = source.displacementMap;
  14870. this.displacementScale = source.displacementScale;
  14871. this.displacementBias = source.displacementBias;
  14872. return this;
  14873. };
  14874. /**
  14875. * @author alteredq / http://alteredqualia.com/
  14876. * @author mrdoob / http://mrdoob.com/
  14877. */
  14878. function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {
  14879. var _frustum = new Frustum(),
  14880. _projScreenMatrix = new Matrix4(),
  14881. _shadowMapSize = new Vector2(),
  14882. _maxShadowMapSize = new Vector2( maxTextureSize, maxTextureSize ),
  14883. _lookTarget = new Vector3(),
  14884. _lightPositionWorld = new Vector3(),
  14885. _MorphingFlag = 1,
  14886. _SkinningFlag = 2,
  14887. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  14888. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  14889. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  14890. _materialCache = {};
  14891. var shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  14892. var cubeDirections = [
  14893. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  14894. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  14895. ];
  14896. var cubeUps = [
  14897. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  14898. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  14899. ];
  14900. var cube2DViewPorts = [
  14901. new Vector4(), new Vector4(), new Vector4(),
  14902. new Vector4(), new Vector4(), new Vector4()
  14903. ];
  14904. // init
  14905. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  14906. var useMorphing = ( i & _MorphingFlag ) !== 0;
  14907. var useSkinning = ( i & _SkinningFlag ) !== 0;
  14908. var depthMaterial = new MeshDepthMaterial( {
  14909. depthPacking: RGBADepthPacking,
  14910. morphTargets: useMorphing,
  14911. skinning: useSkinning
  14912. } );
  14913. _depthMaterials[ i ] = depthMaterial;
  14914. //
  14915. var distanceMaterial = new MeshDistanceMaterial( {
  14916. morphTargets: useMorphing,
  14917. skinning: useSkinning
  14918. } );
  14919. _distanceMaterials[ i ] = distanceMaterial;
  14920. }
  14921. //
  14922. var scope = this;
  14923. this.enabled = false;
  14924. this.autoUpdate = true;
  14925. this.needsUpdate = false;
  14926. this.type = PCFShadowMap;
  14927. this.render = function ( lights, scene, camera ) {
  14928. if ( scope.enabled === false ) return;
  14929. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  14930. if ( lights.length === 0 ) return;
  14931. // TODO Clean up (needed in case of contextlost)
  14932. var _gl = _renderer.context;
  14933. var _state = _renderer.state;
  14934. // Set GL state for depth map.
  14935. _state.disable( 3042 );
  14936. _state.buffers.color.setClear( 1, 1, 1, 1 );
  14937. _state.buffers.depth.setTest( true );
  14938. _state.setScissorTest( false );
  14939. // render depth map
  14940. var faceCount;
  14941. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14942. var light = lights[ i ];
  14943. var shadow = light.shadow;
  14944. var isPointLight = light && light.isPointLight;
  14945. if ( shadow === undefined ) {
  14946. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  14947. continue;
  14948. }
  14949. var shadowCamera = shadow.camera;
  14950. _shadowMapSize.copy( shadow.mapSize );
  14951. _shadowMapSize.min( _maxShadowMapSize );
  14952. if ( isPointLight ) {
  14953. var vpWidth = _shadowMapSize.x;
  14954. var vpHeight = _shadowMapSize.y;
  14955. // These viewports map a cube-map onto a 2D texture with the
  14956. // following orientation:
  14957. //
  14958. // xzXZ
  14959. // y Y
  14960. //
  14961. // X - Positive x direction
  14962. // x - Negative x direction
  14963. // Y - Positive y direction
  14964. // y - Negative y direction
  14965. // Z - Positive z direction
  14966. // z - Negative z direction
  14967. // positive X
  14968. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  14969. // negative X
  14970. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  14971. // positive Z
  14972. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  14973. // negative Z
  14974. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  14975. // positive Y
  14976. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  14977. // negative Y
  14978. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  14979. _shadowMapSize.x *= 4.0;
  14980. _shadowMapSize.y *= 2.0;
  14981. }
  14982. if ( shadow.map === null ) {
  14983. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  14984. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  14985. shadow.map.texture.name = light.name + ".shadowMap";
  14986. shadowCamera.updateProjectionMatrix();
  14987. }
  14988. if ( shadow.isSpotLightShadow ) {
  14989. shadow.update( light );
  14990. }
  14991. var shadowMap = shadow.map;
  14992. var shadowMatrix = shadow.matrix;
  14993. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  14994. shadowCamera.position.copy( _lightPositionWorld );
  14995. if ( isPointLight ) {
  14996. faceCount = 6;
  14997. // for point lights we set the shadow matrix to be a translation-only matrix
  14998. // equal to inverse of the light's position
  14999. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  15000. } else {
  15001. faceCount = 1;
  15002. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  15003. shadowCamera.lookAt( _lookTarget );
  15004. shadowCamera.updateMatrixWorld();
  15005. // compute shadow matrix
  15006. shadowMatrix.set(
  15007. 0.5, 0.0, 0.0, 0.5,
  15008. 0.0, 0.5, 0.0, 0.5,
  15009. 0.0, 0.0, 0.5, 0.5,
  15010. 0.0, 0.0, 0.0, 1.0
  15011. );
  15012. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  15013. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  15014. }
  15015. _renderer.setRenderTarget( shadowMap );
  15016. _renderer.clear();
  15017. // render shadow map for each cube face (if omni-directional) or
  15018. // run a single pass if not
  15019. for ( var face = 0; face < faceCount; face ++ ) {
  15020. if ( isPointLight ) {
  15021. _lookTarget.copy( shadowCamera.position );
  15022. _lookTarget.add( cubeDirections[ face ] );
  15023. shadowCamera.up.copy( cubeUps[ face ] );
  15024. shadowCamera.lookAt( _lookTarget );
  15025. shadowCamera.updateMatrixWorld();
  15026. var vpDimensions = cube2DViewPorts[ face ];
  15027. _state.viewport( vpDimensions );
  15028. }
  15029. // update camera matrices and frustum
  15030. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  15031. _frustum.setFromMatrix( _projScreenMatrix );
  15032. // set object matrices & frustum culling
  15033. renderObject( scene, camera, shadowCamera, isPointLight );
  15034. }
  15035. }
  15036. scope.needsUpdate = false;
  15037. };
  15038. function getDepthMaterial( object, material, isPointLight, lightPositionWorld, shadowCameraNear, shadowCameraFar ) {
  15039. var geometry = object.geometry;
  15040. var result = null;
  15041. var materialVariants = _depthMaterials;
  15042. var customMaterial = object.customDepthMaterial;
  15043. if ( isPointLight ) {
  15044. materialVariants = _distanceMaterials;
  15045. customMaterial = object.customDistanceMaterial;
  15046. }
  15047. if ( ! customMaterial ) {
  15048. var useMorphing = false;
  15049. if ( material.morphTargets ) {
  15050. if ( geometry && geometry.isBufferGeometry ) {
  15051. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  15052. } else if ( geometry && geometry.isGeometry ) {
  15053. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  15054. }
  15055. }
  15056. if ( object.isSkinnedMesh && material.skinning === false ) {
  15057. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  15058. }
  15059. var useSkinning = object.isSkinnedMesh && material.skinning;
  15060. var variantIndex = 0;
  15061. if ( useMorphing ) variantIndex |= _MorphingFlag;
  15062. if ( useSkinning ) variantIndex |= _SkinningFlag;
  15063. result = materialVariants[ variantIndex ];
  15064. } else {
  15065. result = customMaterial;
  15066. }
  15067. if ( _renderer.localClippingEnabled &&
  15068. material.clipShadows === true &&
  15069. material.clippingPlanes.length !== 0 ) {
  15070. // in this case we need a unique material instance reflecting the
  15071. // appropriate state
  15072. var keyA = result.uuid, keyB = material.uuid;
  15073. var materialsForVariant = _materialCache[ keyA ];
  15074. if ( materialsForVariant === undefined ) {
  15075. materialsForVariant = {};
  15076. _materialCache[ keyA ] = materialsForVariant;
  15077. }
  15078. var cachedMaterial = materialsForVariant[ keyB ];
  15079. if ( cachedMaterial === undefined ) {
  15080. cachedMaterial = result.clone();
  15081. materialsForVariant[ keyB ] = cachedMaterial;
  15082. }
  15083. result = cachedMaterial;
  15084. }
  15085. result.visible = material.visible;
  15086. result.wireframe = material.wireframe;
  15087. result.side = ( material.shadowSide != null ) ? material.shadowSide : shadowSide[ material.side ];
  15088. result.clipShadows = material.clipShadows;
  15089. result.clippingPlanes = material.clippingPlanes;
  15090. result.clipIntersection = material.clipIntersection;
  15091. result.wireframeLinewidth = material.wireframeLinewidth;
  15092. result.linewidth = material.linewidth;
  15093. if ( isPointLight && result.isMeshDistanceMaterial ) {
  15094. result.referencePosition.copy( lightPositionWorld );
  15095. result.nearDistance = shadowCameraNear;
  15096. result.farDistance = shadowCameraFar;
  15097. }
  15098. return result;
  15099. }
  15100. function renderObject( object, camera, shadowCamera, isPointLight ) {
  15101. if ( object.visible === false ) return;
  15102. var visible = object.layers.test( camera.layers );
  15103. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  15104. if ( object.castShadow && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  15105. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  15106. var geometry = _objects.update( object );
  15107. var material = object.material;
  15108. if ( Array.isArray( material ) ) {
  15109. var groups = geometry.groups;
  15110. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  15111. var group = groups[ k ];
  15112. var groupMaterial = material[ group.materialIndex ];
  15113. if ( groupMaterial && groupMaterial.visible ) {
  15114. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  15115. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  15116. }
  15117. }
  15118. } else if ( material.visible ) {
  15119. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  15120. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  15121. }
  15122. }
  15123. }
  15124. var children = object.children;
  15125. for ( var i = 0, l = children.length; i < l; i ++ ) {
  15126. renderObject( children[ i ], camera, shadowCamera, isPointLight );
  15127. }
  15128. }
  15129. }
  15130. /**
  15131. * @author mrdoob / http://mrdoob.com/
  15132. */
  15133. function WebGLState( gl, extensions, utils, capabilities ) {
  15134. function ColorBuffer() {
  15135. var locked = false;
  15136. var color = new Vector4();
  15137. var currentColorMask = null;
  15138. var currentColorClear = new Vector4( 0, 0, 0, 0 );
  15139. return {
  15140. setMask: function ( colorMask ) {
  15141. if ( currentColorMask !== colorMask && ! locked ) {
  15142. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  15143. currentColorMask = colorMask;
  15144. }
  15145. },
  15146. setLocked: function ( lock ) {
  15147. locked = lock;
  15148. },
  15149. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  15150. if ( premultipliedAlpha === true ) {
  15151. r *= a; g *= a; b *= a;
  15152. }
  15153. color.set( r, g, b, a );
  15154. if ( currentColorClear.equals( color ) === false ) {
  15155. gl.clearColor( r, g, b, a );
  15156. currentColorClear.copy( color );
  15157. }
  15158. },
  15159. reset: function () {
  15160. locked = false;
  15161. currentColorMask = null;
  15162. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  15163. }
  15164. };
  15165. }
  15166. function DepthBuffer() {
  15167. var locked = false;
  15168. var currentDepthMask = null;
  15169. var currentDepthFunc = null;
  15170. var currentDepthClear = null;
  15171. return {
  15172. setTest: function ( depthTest ) {
  15173. if ( depthTest ) {
  15174. enable( 2929 );
  15175. } else {
  15176. disable( 2929 );
  15177. }
  15178. },
  15179. setMask: function ( depthMask ) {
  15180. if ( currentDepthMask !== depthMask && ! locked ) {
  15181. gl.depthMask( depthMask );
  15182. currentDepthMask = depthMask;
  15183. }
  15184. },
  15185. setFunc: function ( depthFunc ) {
  15186. if ( currentDepthFunc !== depthFunc ) {
  15187. if ( depthFunc ) {
  15188. switch ( depthFunc ) {
  15189. case NeverDepth:
  15190. gl.depthFunc( 512 );
  15191. break;
  15192. case AlwaysDepth:
  15193. gl.depthFunc( 519 );
  15194. break;
  15195. case LessDepth:
  15196. gl.depthFunc( 513 );
  15197. break;
  15198. case LessEqualDepth:
  15199. gl.depthFunc( 515 );
  15200. break;
  15201. case EqualDepth:
  15202. gl.depthFunc( 514 );
  15203. break;
  15204. case GreaterEqualDepth:
  15205. gl.depthFunc( 518 );
  15206. break;
  15207. case GreaterDepth:
  15208. gl.depthFunc( 516 );
  15209. break;
  15210. case NotEqualDepth:
  15211. gl.depthFunc( 517 );
  15212. break;
  15213. default:
  15214. gl.depthFunc( 515 );
  15215. }
  15216. } else {
  15217. gl.depthFunc( 515 );
  15218. }
  15219. currentDepthFunc = depthFunc;
  15220. }
  15221. },
  15222. setLocked: function ( lock ) {
  15223. locked = lock;
  15224. },
  15225. setClear: function ( depth ) {
  15226. if ( currentDepthClear !== depth ) {
  15227. gl.clearDepth( depth );
  15228. currentDepthClear = depth;
  15229. }
  15230. },
  15231. reset: function () {
  15232. locked = false;
  15233. currentDepthMask = null;
  15234. currentDepthFunc = null;
  15235. currentDepthClear = null;
  15236. }
  15237. };
  15238. }
  15239. function StencilBuffer() {
  15240. var locked = false;
  15241. var currentStencilMask = null;
  15242. var currentStencilFunc = null;
  15243. var currentStencilRef = null;
  15244. var currentStencilFuncMask = null;
  15245. var currentStencilFail = null;
  15246. var currentStencilZFail = null;
  15247. var currentStencilZPass = null;
  15248. var currentStencilClear = null;
  15249. return {
  15250. setTest: function ( stencilTest ) {
  15251. if ( stencilTest ) {
  15252. enable( 2960 );
  15253. } else {
  15254. disable( 2960 );
  15255. }
  15256. },
  15257. setMask: function ( stencilMask ) {
  15258. if ( currentStencilMask !== stencilMask && ! locked ) {
  15259. gl.stencilMask( stencilMask );
  15260. currentStencilMask = stencilMask;
  15261. }
  15262. },
  15263. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  15264. if ( currentStencilFunc !== stencilFunc ||
  15265. currentStencilRef !== stencilRef ||
  15266. currentStencilFuncMask !== stencilMask ) {
  15267. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  15268. currentStencilFunc = stencilFunc;
  15269. currentStencilRef = stencilRef;
  15270. currentStencilFuncMask = stencilMask;
  15271. }
  15272. },
  15273. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  15274. if ( currentStencilFail !== stencilFail ||
  15275. currentStencilZFail !== stencilZFail ||
  15276. currentStencilZPass !== stencilZPass ) {
  15277. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  15278. currentStencilFail = stencilFail;
  15279. currentStencilZFail = stencilZFail;
  15280. currentStencilZPass = stencilZPass;
  15281. }
  15282. },
  15283. setLocked: function ( lock ) {
  15284. locked = lock;
  15285. },
  15286. setClear: function ( stencil ) {
  15287. if ( currentStencilClear !== stencil ) {
  15288. gl.clearStencil( stencil );
  15289. currentStencilClear = stencil;
  15290. }
  15291. },
  15292. reset: function () {
  15293. locked = false;
  15294. currentStencilMask = null;
  15295. currentStencilFunc = null;
  15296. currentStencilRef = null;
  15297. currentStencilFuncMask = null;
  15298. currentStencilFail = null;
  15299. currentStencilZFail = null;
  15300. currentStencilZPass = null;
  15301. currentStencilClear = null;
  15302. }
  15303. };
  15304. }
  15305. //
  15306. var colorBuffer = new ColorBuffer();
  15307. var depthBuffer = new DepthBuffer();
  15308. var stencilBuffer = new StencilBuffer();
  15309. var maxVertexAttributes = gl.getParameter( 34921 );
  15310. var newAttributes = new Uint8Array( maxVertexAttributes );
  15311. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  15312. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  15313. var enabledCapabilities = {};
  15314. var compressedTextureFormats = null;
  15315. var currentProgram = null;
  15316. var currentBlendingEnabled = null;
  15317. var currentBlending = null;
  15318. var currentBlendEquation = null;
  15319. var currentBlendSrc = null;
  15320. var currentBlendDst = null;
  15321. var currentBlendEquationAlpha = null;
  15322. var currentBlendSrcAlpha = null;
  15323. var currentBlendDstAlpha = null;
  15324. var currentPremultipledAlpha = false;
  15325. var currentFlipSided = null;
  15326. var currentCullFace = null;
  15327. var currentLineWidth = null;
  15328. var currentPolygonOffsetFactor = null;
  15329. var currentPolygonOffsetUnits = null;
  15330. var maxTextures = gl.getParameter( 35661 );
  15331. var lineWidthAvailable = false;
  15332. var version = 0;
  15333. var glVersion = gl.getParameter( 7938 );
  15334. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  15335. version = parseFloat( /^WebGL\ ([0-9])/.exec( glVersion )[ 1 ] );
  15336. lineWidthAvailable = ( version >= 1.0 );
  15337. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  15338. version = parseFloat( /^OpenGL\ ES\ ([0-9])/.exec( glVersion )[ 1 ] );
  15339. lineWidthAvailable = ( version >= 2.0 );
  15340. }
  15341. var currentTextureSlot = null;
  15342. var currentBoundTextures = {};
  15343. var currentScissor = new Vector4();
  15344. var currentViewport = new Vector4();
  15345. function createTexture( type, target, count ) {
  15346. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  15347. var texture = gl.createTexture();
  15348. gl.bindTexture( type, texture );
  15349. gl.texParameteri( type, 10241, 9728 );
  15350. gl.texParameteri( type, 10240, 9728 );
  15351. for ( var i = 0; i < count; i ++ ) {
  15352. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  15353. }
  15354. return texture;
  15355. }
  15356. var emptyTextures = {};
  15357. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  15358. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  15359. // init
  15360. colorBuffer.setClear( 0, 0, 0, 1 );
  15361. depthBuffer.setClear( 1 );
  15362. stencilBuffer.setClear( 0 );
  15363. enable( 2929 );
  15364. depthBuffer.setFunc( LessEqualDepth );
  15365. setFlipSided( false );
  15366. setCullFace( CullFaceBack );
  15367. enable( 2884 );
  15368. setBlending( NoBlending );
  15369. //
  15370. function initAttributes() {
  15371. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  15372. newAttributes[ i ] = 0;
  15373. }
  15374. }
  15375. function enableAttribute( attribute ) {
  15376. enableAttributeAndDivisor( attribute, 0 );
  15377. }
  15378. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  15379. newAttributes[ attribute ] = 1;
  15380. if ( enabledAttributes[ attribute ] === 0 ) {
  15381. gl.enableVertexAttribArray( attribute );
  15382. enabledAttributes[ attribute ] = 1;
  15383. }
  15384. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  15385. var extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  15386. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  15387. attributeDivisors[ attribute ] = meshPerAttribute;
  15388. }
  15389. }
  15390. function disableUnusedAttributes() {
  15391. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  15392. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  15393. gl.disableVertexAttribArray( i );
  15394. enabledAttributes[ i ] = 0;
  15395. }
  15396. }
  15397. }
  15398. function enable( id ) {
  15399. if ( enabledCapabilities[ id ] !== true ) {
  15400. gl.enable( id );
  15401. enabledCapabilities[ id ] = true;
  15402. }
  15403. }
  15404. function disable( id ) {
  15405. if ( enabledCapabilities[ id ] !== false ) {
  15406. gl.disable( id );
  15407. enabledCapabilities[ id ] = false;
  15408. }
  15409. }
  15410. function getCompressedTextureFormats() {
  15411. if ( compressedTextureFormats === null ) {
  15412. compressedTextureFormats = [];
  15413. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  15414. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  15415. extensions.get( 'WEBGL_compressed_texture_etc1' ) ||
  15416. extensions.get( 'WEBGL_compressed_texture_astc' ) ) {
  15417. var formats = gl.getParameter( 34467 );
  15418. for ( var i = 0; i < formats.length; i ++ ) {
  15419. compressedTextureFormats.push( formats[ i ] );
  15420. }
  15421. }
  15422. }
  15423. return compressedTextureFormats;
  15424. }
  15425. function useProgram( program ) {
  15426. if ( currentProgram !== program ) {
  15427. gl.useProgram( program );
  15428. currentProgram = program;
  15429. return true;
  15430. }
  15431. return false;
  15432. }
  15433. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  15434. if ( blending === NoBlending ) {
  15435. if ( currentBlendingEnabled ) {
  15436. disable( 3042 );
  15437. currentBlendingEnabled = false;
  15438. }
  15439. return;
  15440. }
  15441. if ( ! currentBlendingEnabled ) {
  15442. enable( 3042 );
  15443. currentBlendingEnabled = true;
  15444. }
  15445. if ( blending !== CustomBlending ) {
  15446. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  15447. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  15448. gl.blendEquation( 32774 );
  15449. currentBlendEquation = AddEquation;
  15450. currentBlendEquationAlpha = AddEquation;
  15451. }
  15452. if ( premultipliedAlpha ) {
  15453. switch ( blending ) {
  15454. case NormalBlending:
  15455. gl.blendFuncSeparate( 1, 771, 1, 771 );
  15456. break;
  15457. case AdditiveBlending:
  15458. gl.blendFunc( 1, 1 );
  15459. break;
  15460. case SubtractiveBlending:
  15461. gl.blendFuncSeparate( 0, 0, 769, 771 );
  15462. break;
  15463. case MultiplyBlending:
  15464. gl.blendFuncSeparate( 0, 768, 0, 770 );
  15465. break;
  15466. default:
  15467. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  15468. break;
  15469. }
  15470. } else {
  15471. switch ( blending ) {
  15472. case NormalBlending:
  15473. gl.blendFuncSeparate( 770, 771, 1, 771 );
  15474. break;
  15475. case AdditiveBlending:
  15476. gl.blendFunc( 770, 1 );
  15477. break;
  15478. case SubtractiveBlending:
  15479. gl.blendFunc( 0, 769 );
  15480. break;
  15481. case MultiplyBlending:
  15482. gl.blendFunc( 0, 768 );
  15483. break;
  15484. default:
  15485. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  15486. break;
  15487. }
  15488. }
  15489. currentBlendSrc = null;
  15490. currentBlendDst = null;
  15491. currentBlendSrcAlpha = null;
  15492. currentBlendDstAlpha = null;
  15493. currentBlending = blending;
  15494. currentPremultipledAlpha = premultipliedAlpha;
  15495. }
  15496. return;
  15497. }
  15498. // custom blending
  15499. blendEquationAlpha = blendEquationAlpha || blendEquation;
  15500. blendSrcAlpha = blendSrcAlpha || blendSrc;
  15501. blendDstAlpha = blendDstAlpha || blendDst;
  15502. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  15503. gl.blendEquationSeparate( utils.convert( blendEquation ), utils.convert( blendEquationAlpha ) );
  15504. currentBlendEquation = blendEquation;
  15505. currentBlendEquationAlpha = blendEquationAlpha;
  15506. }
  15507. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  15508. gl.blendFuncSeparate( utils.convert( blendSrc ), utils.convert( blendDst ), utils.convert( blendSrcAlpha ), utils.convert( blendDstAlpha ) );
  15509. currentBlendSrc = blendSrc;
  15510. currentBlendDst = blendDst;
  15511. currentBlendSrcAlpha = blendSrcAlpha;
  15512. currentBlendDstAlpha = blendDstAlpha;
  15513. }
  15514. currentBlending = blending;
  15515. currentPremultipledAlpha = null;
  15516. }
  15517. function setMaterial( material, frontFaceCW ) {
  15518. material.side === DoubleSide
  15519. ? disable( 2884 )
  15520. : enable( 2884 );
  15521. var flipSided = ( material.side === BackSide );
  15522. if ( frontFaceCW ) flipSided = ! flipSided;
  15523. setFlipSided( flipSided );
  15524. ( material.blending === NormalBlending && material.transparent === false )
  15525. ? setBlending( NoBlending )
  15526. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  15527. depthBuffer.setFunc( material.depthFunc );
  15528. depthBuffer.setTest( material.depthTest );
  15529. depthBuffer.setMask( material.depthWrite );
  15530. colorBuffer.setMask( material.colorWrite );
  15531. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  15532. }
  15533. //
  15534. function setFlipSided( flipSided ) {
  15535. if ( currentFlipSided !== flipSided ) {
  15536. if ( flipSided ) {
  15537. gl.frontFace( 2304 );
  15538. } else {
  15539. gl.frontFace( 2305 );
  15540. }
  15541. currentFlipSided = flipSided;
  15542. }
  15543. }
  15544. function setCullFace( cullFace ) {
  15545. if ( cullFace !== CullFaceNone ) {
  15546. enable( 2884 );
  15547. if ( cullFace !== currentCullFace ) {
  15548. if ( cullFace === CullFaceBack ) {
  15549. gl.cullFace( 1029 );
  15550. } else if ( cullFace === CullFaceFront ) {
  15551. gl.cullFace( 1028 );
  15552. } else {
  15553. gl.cullFace( 1032 );
  15554. }
  15555. }
  15556. } else {
  15557. disable( 2884 );
  15558. }
  15559. currentCullFace = cullFace;
  15560. }
  15561. function setLineWidth( width ) {
  15562. if ( width !== currentLineWidth ) {
  15563. if ( lineWidthAvailable ) gl.lineWidth( width );
  15564. currentLineWidth = width;
  15565. }
  15566. }
  15567. function setPolygonOffset( polygonOffset, factor, units ) {
  15568. if ( polygonOffset ) {
  15569. enable( 32823 );
  15570. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  15571. gl.polygonOffset( factor, units );
  15572. currentPolygonOffsetFactor = factor;
  15573. currentPolygonOffsetUnits = units;
  15574. }
  15575. } else {
  15576. disable( 32823 );
  15577. }
  15578. }
  15579. function setScissorTest( scissorTest ) {
  15580. if ( scissorTest ) {
  15581. enable( 3089 );
  15582. } else {
  15583. disable( 3089 );
  15584. }
  15585. }
  15586. // texture
  15587. function activeTexture( webglSlot ) {
  15588. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  15589. if ( currentTextureSlot !== webglSlot ) {
  15590. gl.activeTexture( webglSlot );
  15591. currentTextureSlot = webglSlot;
  15592. }
  15593. }
  15594. function bindTexture( webglType, webglTexture ) {
  15595. if ( currentTextureSlot === null ) {
  15596. activeTexture();
  15597. }
  15598. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  15599. if ( boundTexture === undefined ) {
  15600. boundTexture = { type: undefined, texture: undefined };
  15601. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  15602. }
  15603. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  15604. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  15605. boundTexture.type = webglType;
  15606. boundTexture.texture = webglTexture;
  15607. }
  15608. }
  15609. function compressedTexImage2D() {
  15610. try {
  15611. gl.compressedTexImage2D.apply( gl, arguments );
  15612. } catch ( error ) {
  15613. console.error( 'THREE.WebGLState:', error );
  15614. }
  15615. }
  15616. function texImage2D() {
  15617. try {
  15618. gl.texImage2D.apply( gl, arguments );
  15619. } catch ( error ) {
  15620. console.error( 'THREE.WebGLState:', error );
  15621. }
  15622. }
  15623. function texImage3D() {
  15624. try {
  15625. gl.texImage3D.apply( gl, arguments );
  15626. } catch ( error ) {
  15627. console.error( 'THREE.WebGLState:', error );
  15628. }
  15629. }
  15630. //
  15631. function scissor( scissor ) {
  15632. if ( currentScissor.equals( scissor ) === false ) {
  15633. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  15634. currentScissor.copy( scissor );
  15635. }
  15636. }
  15637. function viewport( viewport ) {
  15638. if ( currentViewport.equals( viewport ) === false ) {
  15639. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  15640. currentViewport.copy( viewport );
  15641. }
  15642. }
  15643. //
  15644. function reset() {
  15645. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  15646. if ( enabledAttributes[ i ] === 1 ) {
  15647. gl.disableVertexAttribArray( i );
  15648. enabledAttributes[ i ] = 0;
  15649. }
  15650. }
  15651. enabledCapabilities = {};
  15652. compressedTextureFormats = null;
  15653. currentTextureSlot = null;
  15654. currentBoundTextures = {};
  15655. currentProgram = null;
  15656. currentBlending = null;
  15657. currentFlipSided = null;
  15658. currentCullFace = null;
  15659. colorBuffer.reset();
  15660. depthBuffer.reset();
  15661. stencilBuffer.reset();
  15662. }
  15663. return {
  15664. buffers: {
  15665. color: colorBuffer,
  15666. depth: depthBuffer,
  15667. stencil: stencilBuffer
  15668. },
  15669. initAttributes: initAttributes,
  15670. enableAttribute: enableAttribute,
  15671. enableAttributeAndDivisor: enableAttributeAndDivisor,
  15672. disableUnusedAttributes: disableUnusedAttributes,
  15673. enable: enable,
  15674. disable: disable,
  15675. getCompressedTextureFormats: getCompressedTextureFormats,
  15676. useProgram: useProgram,
  15677. setBlending: setBlending,
  15678. setMaterial: setMaterial,
  15679. setFlipSided: setFlipSided,
  15680. setCullFace: setCullFace,
  15681. setLineWidth: setLineWidth,
  15682. setPolygonOffset: setPolygonOffset,
  15683. setScissorTest: setScissorTest,
  15684. activeTexture: activeTexture,
  15685. bindTexture: bindTexture,
  15686. compressedTexImage2D: compressedTexImage2D,
  15687. texImage2D: texImage2D,
  15688. texImage3D: texImage3D,
  15689. scissor: scissor,
  15690. viewport: viewport,
  15691. reset: reset
  15692. };
  15693. }
  15694. /**
  15695. * @author mrdoob / http://mrdoob.com/
  15696. */
  15697. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  15698. var _videoTextures = {};
  15699. var _canvas;
  15700. //
  15701. function clampToMaxSize( image, maxSize ) {
  15702. if ( image.width > maxSize || image.height > maxSize ) {
  15703. if ( 'data' in image ) {
  15704. console.warn( 'THREE.WebGLRenderer: image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  15705. return;
  15706. }
  15707. // Warning: Scaling through the canvas will only work with images that use
  15708. // premultiplied alpha.
  15709. var scale = maxSize / Math.max( image.width, image.height );
  15710. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  15711. canvas.width = Math.floor( image.width * scale );
  15712. canvas.height = Math.floor( image.height * scale );
  15713. var context = canvas.getContext( '2d' );
  15714. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  15715. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height );
  15716. return canvas;
  15717. }
  15718. return image;
  15719. }
  15720. function isPowerOfTwo( image ) {
  15721. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  15722. }
  15723. function makePowerOfTwo( image ) {
  15724. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement || image instanceof ImageBitmap ) {
  15725. if ( _canvas === undefined ) _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  15726. _canvas.width = _Math.floorPowerOfTwo( image.width );
  15727. _canvas.height = _Math.floorPowerOfTwo( image.height );
  15728. var context = _canvas.getContext( '2d' );
  15729. context.drawImage( image, 0, 0, _canvas.width, _canvas.height );
  15730. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + _canvas.width + 'x' + _canvas.height );
  15731. return _canvas;
  15732. }
  15733. return image;
  15734. }
  15735. function textureNeedsPowerOfTwo( texture ) {
  15736. if ( capabilities.isWebGL2 ) return false;
  15737. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  15738. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  15739. }
  15740. function textureNeedsGenerateMipmaps( texture, isPowerOfTwo ) {
  15741. return texture.generateMipmaps && isPowerOfTwo &&
  15742. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  15743. }
  15744. function generateMipmap( target, texture, width, height ) {
  15745. _gl.generateMipmap( target );
  15746. var textureProperties = properties.get( texture );
  15747. // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  15748. textureProperties.__maxMipLevel = Math.log( Math.max( width, height ) ) * Math.LOG2E;
  15749. }
  15750. function getInternalFormat( glFormat, glType ) {
  15751. if ( ! capabilities.isWebGL2 ) return glFormat;
  15752. if ( glFormat === 6403 ) {
  15753. if ( glType === 5126 ) return 33326;
  15754. if ( glType === 5131 ) return 33325;
  15755. if ( glType === 5121 ) return 33321;
  15756. }
  15757. if ( glFormat === 6407 ) {
  15758. if ( glType === 5126 ) return 34837;
  15759. if ( glType === 5131 ) return 34843;
  15760. if ( glType === 5121 ) return 32849;
  15761. }
  15762. if ( glFormat === 6408 ) {
  15763. if ( glType === 5126 ) return 34836;
  15764. if ( glType === 5131 ) return 34842;
  15765. if ( glType === 5121 ) return 32856;
  15766. }
  15767. return glFormat;
  15768. }
  15769. // Fallback filters for non-power-of-2 textures
  15770. function filterFallback( f ) {
  15771. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  15772. return 9728;
  15773. }
  15774. return 9729;
  15775. }
  15776. //
  15777. function onTextureDispose( event ) {
  15778. var texture = event.target;
  15779. texture.removeEventListener( 'dispose', onTextureDispose );
  15780. deallocateTexture( texture );
  15781. if ( texture.isVideoTexture ) {
  15782. delete _videoTextures[ texture.id ];
  15783. }
  15784. info.memory.textures --;
  15785. }
  15786. function onRenderTargetDispose( event ) {
  15787. var renderTarget = event.target;
  15788. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  15789. deallocateRenderTarget( renderTarget );
  15790. info.memory.textures --;
  15791. }
  15792. //
  15793. function deallocateTexture( texture ) {
  15794. var textureProperties = properties.get( texture );
  15795. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  15796. // cube texture
  15797. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  15798. } else {
  15799. // 2D texture
  15800. if ( textureProperties.__webglInit === undefined ) return;
  15801. _gl.deleteTexture( textureProperties.__webglTexture );
  15802. }
  15803. // remove all webgl properties
  15804. properties.remove( texture );
  15805. }
  15806. function deallocateRenderTarget( renderTarget ) {
  15807. var renderTargetProperties = properties.get( renderTarget );
  15808. var textureProperties = properties.get( renderTarget.texture );
  15809. if ( ! renderTarget ) return;
  15810. if ( textureProperties.__webglTexture !== undefined ) {
  15811. _gl.deleteTexture( textureProperties.__webglTexture );
  15812. }
  15813. if ( renderTarget.depthTexture ) {
  15814. renderTarget.depthTexture.dispose();
  15815. }
  15816. if ( renderTarget.isWebGLRenderTargetCube ) {
  15817. for ( var i = 0; i < 6; i ++ ) {
  15818. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  15819. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  15820. }
  15821. } else {
  15822. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  15823. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  15824. }
  15825. properties.remove( renderTarget.texture );
  15826. properties.remove( renderTarget );
  15827. }
  15828. //
  15829. function setTexture2D( texture, slot ) {
  15830. var textureProperties = properties.get( texture );
  15831. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  15832. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  15833. var image = texture.image;
  15834. if ( image === undefined ) {
  15835. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );
  15836. } else if ( image.complete === false ) {
  15837. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  15838. } else {
  15839. uploadTexture( textureProperties, texture, slot );
  15840. return;
  15841. }
  15842. }
  15843. state.activeTexture( 33984 + slot );
  15844. state.bindTexture( 3553, textureProperties.__webglTexture );
  15845. }
  15846. function setTexture3D( texture, slot ) {
  15847. var textureProperties = properties.get( texture );
  15848. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  15849. uploadTexture( textureProperties, texture, slot );
  15850. return;
  15851. }
  15852. state.activeTexture( 33984 + slot );
  15853. state.bindTexture( 32879, textureProperties.__webglTexture );
  15854. }
  15855. function setTextureCube( texture, slot ) {
  15856. var textureProperties = properties.get( texture );
  15857. if ( texture.image.length === 6 ) {
  15858. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  15859. if ( ! textureProperties.__image__webglTextureCube ) {
  15860. texture.addEventListener( 'dispose', onTextureDispose );
  15861. textureProperties.__image__webglTextureCube = _gl.createTexture();
  15862. info.memory.textures ++;
  15863. }
  15864. state.activeTexture( 33984 + slot );
  15865. state.bindTexture( 34067, textureProperties.__image__webglTextureCube );
  15866. _gl.pixelStorei( 37440, texture.flipY );
  15867. var isCompressed = ( texture && texture.isCompressedTexture );
  15868. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  15869. var cubeImage = [];
  15870. for ( var i = 0; i < 6; i ++ ) {
  15871. if ( ! isCompressed && ! isDataTexture ) {
  15872. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  15873. } else {
  15874. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  15875. }
  15876. }
  15877. var image = cubeImage[ 0 ],
  15878. isPowerOfTwoImage = isPowerOfTwo( image ),
  15879. glFormat = utils.convert( texture.format ),
  15880. glType = utils.convert( texture.type ),
  15881. glInternalFormat = getInternalFormat( glFormat, glType );
  15882. setTextureParameters( 34067, texture, isPowerOfTwoImage );
  15883. for ( var i = 0; i < 6; i ++ ) {
  15884. if ( ! isCompressed ) {
  15885. if ( isDataTexture ) {
  15886. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  15887. } else {
  15888. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  15889. }
  15890. } else {
  15891. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15892. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15893. mipmap = mipmaps[ j ];
  15894. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  15895. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  15896. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15897. } else {
  15898. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  15899. }
  15900. } else {
  15901. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15902. }
  15903. }
  15904. }
  15905. }
  15906. if ( ! isCompressed ) {
  15907. textureProperties.__maxMipLevel = 0;
  15908. } else {
  15909. textureProperties.__maxMipLevel = mipmaps.length - 1;
  15910. }
  15911. if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) {
  15912. // We assume images for cube map have the same size.
  15913. generateMipmap( 34067, texture, image.width, image.height );
  15914. }
  15915. textureProperties.__version = texture.version;
  15916. if ( texture.onUpdate ) texture.onUpdate( texture );
  15917. } else {
  15918. state.activeTexture( 33984 + slot );
  15919. state.bindTexture( 34067, textureProperties.__image__webglTextureCube );
  15920. }
  15921. }
  15922. }
  15923. function setTextureCubeDynamic( texture, slot ) {
  15924. state.activeTexture( 33984 + slot );
  15925. state.bindTexture( 34067, properties.get( texture ).__webglTexture );
  15926. }
  15927. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  15928. var extension;
  15929. if ( isPowerOfTwoImage ) {
  15930. _gl.texParameteri( textureType, 10242, utils.convert( texture.wrapS ) );
  15931. _gl.texParameteri( textureType, 10243, utils.convert( texture.wrapT ) );
  15932. _gl.texParameteri( textureType, 10240, utils.convert( texture.magFilter ) );
  15933. _gl.texParameteri( textureType, 10241, utils.convert( texture.minFilter ) );
  15934. } else {
  15935. _gl.texParameteri( textureType, 10242, 33071 );
  15936. _gl.texParameteri( textureType, 10243, 33071 );
  15937. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  15938. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  15939. }
  15940. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  15941. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  15942. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  15943. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  15944. }
  15945. }
  15946. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  15947. if ( extension ) {
  15948. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  15949. if ( texture.type === HalfFloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_half_float_linear' ) ) === null ) return;
  15950. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  15951. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  15952. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  15953. }
  15954. }
  15955. }
  15956. function uploadTexture( textureProperties, texture, slot ) {
  15957. var textureType;
  15958. if ( texture.isDataTexture3D ) {
  15959. textureType = 32879;
  15960. } else {
  15961. textureType = 3553;
  15962. }
  15963. if ( textureProperties.__webglInit === undefined ) {
  15964. textureProperties.__webglInit = true;
  15965. texture.addEventListener( 'dispose', onTextureDispose );
  15966. textureProperties.__webglTexture = _gl.createTexture();
  15967. info.memory.textures ++;
  15968. }
  15969. state.activeTexture( 33984 + slot );
  15970. state.bindTexture( textureType, textureProperties.__webglTexture );
  15971. _gl.pixelStorei( 37440, texture.flipY );
  15972. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  15973. _gl.pixelStorei( 3317, texture.unpackAlignment );
  15974. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  15975. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  15976. image = makePowerOfTwo( image );
  15977. }
  15978. var isPowerOfTwoImage = isPowerOfTwo( image ),
  15979. glFormat = utils.convert( texture.format ),
  15980. glType = utils.convert( texture.type ),
  15981. glInternalFormat = getInternalFormat( glFormat, glType );
  15982. setTextureParameters( textureType, texture, isPowerOfTwoImage );
  15983. var mipmap, mipmaps = texture.mipmaps;
  15984. if ( texture.isDepthTexture ) {
  15985. // populate depth texture with dummy data
  15986. glInternalFormat = 6402;
  15987. if ( texture.type === FloatType ) {
  15988. if ( ! capabilities.isWebGL2 ) throw new Error( 'Float Depth Texture only supported in WebGL2.0' );
  15989. glInternalFormat = 36012;
  15990. } else if ( capabilities.isWebGL2 ) {
  15991. // WebGL 2.0 requires signed internalformat for glTexImage2D
  15992. glInternalFormat = 33189;
  15993. }
  15994. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  15995. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  15996. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  15997. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  15998. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  15999. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  16000. texture.type = UnsignedShortType;
  16001. glType = utils.convert( texture.type );
  16002. }
  16003. }
  16004. // Depth stencil textures need the DEPTH_STENCIL internal format
  16005. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  16006. if ( texture.format === DepthStencilFormat ) {
  16007. glInternalFormat = 34041;
  16008. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  16009. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  16010. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  16011. if ( texture.type !== UnsignedInt248Type ) {
  16012. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  16013. texture.type = UnsignedInt248Type;
  16014. glType = utils.convert( texture.type );
  16015. }
  16016. }
  16017. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  16018. } else if ( texture.isDataTexture ) {
  16019. // use manually created mipmaps if available
  16020. // if there are no manual mipmaps
  16021. // set 0 level mipmap and then use GL to generate other mipmap levels
  16022. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  16023. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16024. mipmap = mipmaps[ i ];
  16025. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16026. }
  16027. texture.generateMipmaps = false;
  16028. textureProperties.__maxMipLevel = mipmaps.length - 1;
  16029. } else {
  16030. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  16031. textureProperties.__maxMipLevel = 0;
  16032. }
  16033. } else if ( texture.isCompressedTexture ) {
  16034. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16035. mipmap = mipmaps[ i ];
  16036. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  16037. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  16038. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  16039. } else {
  16040. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  16041. }
  16042. } else {
  16043. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16044. }
  16045. }
  16046. textureProperties.__maxMipLevel = mipmaps.length - 1;
  16047. } else if ( texture.isDataTexture3D ) {
  16048. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  16049. textureProperties.__maxMipLevel = 0;
  16050. } else {
  16051. // regular Texture (image, video, canvas)
  16052. // use manually created mipmaps if available
  16053. // if there are no manual mipmaps
  16054. // set 0 level mipmap and then use GL to generate other mipmap levels
  16055. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  16056. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16057. mipmap = mipmaps[ i ];
  16058. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  16059. }
  16060. texture.generateMipmaps = false;
  16061. textureProperties.__maxMipLevel = mipmaps.length - 1;
  16062. } else {
  16063. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  16064. textureProperties.__maxMipLevel = 0;
  16065. }
  16066. }
  16067. if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) {
  16068. generateMipmap( 3553, texture, image.width, image.height );
  16069. }
  16070. textureProperties.__version = texture.version;
  16071. if ( texture.onUpdate ) texture.onUpdate( texture );
  16072. }
  16073. // Render targets
  16074. // Setup storage for target texture and bind it to correct framebuffer
  16075. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  16076. var glFormat = utils.convert( renderTarget.texture.format );
  16077. var glType = utils.convert( renderTarget.texture.type );
  16078. var glInternalFormat = getInternalFormat( glFormat, glType );
  16079. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  16080. _gl.bindFramebuffer( 36160, framebuffer );
  16081. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  16082. _gl.bindFramebuffer( 36160, null );
  16083. }
  16084. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  16085. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  16086. _gl.bindRenderbuffer( 36161, renderbuffer );
  16087. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  16088. _gl.renderbufferStorage( 36161, 33189, renderTarget.width, renderTarget.height );
  16089. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  16090. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  16091. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  16092. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  16093. } else {
  16094. // FIXME: We don't support !depth !stencil
  16095. _gl.renderbufferStorage( 36161, 32854, renderTarget.width, renderTarget.height );
  16096. }
  16097. _gl.bindRenderbuffer( 36161, null );
  16098. }
  16099. // Setup resources for a Depth Texture for a FBO (needs an extension)
  16100. function setupDepthTexture( framebuffer, renderTarget ) {
  16101. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  16102. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  16103. _gl.bindFramebuffer( 36160, framebuffer );
  16104. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  16105. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  16106. }
  16107. // upload an empty depth texture with framebuffer size
  16108. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  16109. renderTarget.depthTexture.image.width !== renderTarget.width ||
  16110. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  16111. renderTarget.depthTexture.image.width = renderTarget.width;
  16112. renderTarget.depthTexture.image.height = renderTarget.height;
  16113. renderTarget.depthTexture.needsUpdate = true;
  16114. }
  16115. setTexture2D( renderTarget.depthTexture, 0 );
  16116. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  16117. if ( renderTarget.depthTexture.format === DepthFormat ) {
  16118. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  16119. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  16120. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  16121. } else {
  16122. throw new Error( 'Unknown depthTexture format' );
  16123. }
  16124. }
  16125. // Setup GL resources for a non-texture depth buffer
  16126. function setupDepthRenderbuffer( renderTarget ) {
  16127. var renderTargetProperties = properties.get( renderTarget );
  16128. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  16129. if ( renderTarget.depthTexture ) {
  16130. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  16131. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  16132. } else {
  16133. if ( isCube ) {
  16134. renderTargetProperties.__webglDepthbuffer = [];
  16135. for ( var i = 0; i < 6; i ++ ) {
  16136. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  16137. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  16138. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  16139. }
  16140. } else {
  16141. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  16142. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  16143. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  16144. }
  16145. }
  16146. _gl.bindFramebuffer( 36160, null );
  16147. }
  16148. // Set up GL resources for the render target
  16149. function setupRenderTarget( renderTarget ) {
  16150. var renderTargetProperties = properties.get( renderTarget );
  16151. var textureProperties = properties.get( renderTarget.texture );
  16152. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  16153. textureProperties.__webglTexture = _gl.createTexture();
  16154. info.memory.textures ++;
  16155. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  16156. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  16157. // Setup framebuffer
  16158. if ( isCube ) {
  16159. renderTargetProperties.__webglFramebuffer = [];
  16160. for ( var i = 0; i < 6; i ++ ) {
  16161. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  16162. }
  16163. } else {
  16164. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  16165. }
  16166. // Setup color buffer
  16167. if ( isCube ) {
  16168. state.bindTexture( 34067, textureProperties.__webglTexture );
  16169. setTextureParameters( 34067, renderTarget.texture, isTargetPowerOfTwo );
  16170. for ( var i = 0; i < 6; i ++ ) {
  16171. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, 36064, 34069 + i );
  16172. }
  16173. if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) {
  16174. generateMipmap( 34067, renderTarget.texture, renderTarget.width, renderTarget.height );
  16175. }
  16176. state.bindTexture( 34067, null );
  16177. } else {
  16178. state.bindTexture( 3553, textureProperties.__webglTexture );
  16179. setTextureParameters( 3553, renderTarget.texture, isTargetPowerOfTwo );
  16180. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553 );
  16181. if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) {
  16182. generateMipmap( 3553, renderTarget.texture, renderTarget.width, renderTarget.height );
  16183. }
  16184. state.bindTexture( 3553, null );
  16185. }
  16186. // Setup depth and stencil buffers
  16187. if ( renderTarget.depthBuffer ) {
  16188. setupDepthRenderbuffer( renderTarget );
  16189. }
  16190. }
  16191. function updateRenderTargetMipmap( renderTarget ) {
  16192. var texture = renderTarget.texture;
  16193. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  16194. if ( textureNeedsGenerateMipmaps( texture, isTargetPowerOfTwo ) ) {
  16195. var target = renderTarget.isWebGLRenderTargetCube ? 34067 : 3553;
  16196. var webglTexture = properties.get( texture ).__webglTexture;
  16197. state.bindTexture( target, webglTexture );
  16198. generateMipmap( target, texture, renderTarget.width, renderTarget.height );
  16199. state.bindTexture( target, null );
  16200. }
  16201. }
  16202. function updateVideoTexture( texture ) {
  16203. var id = texture.id;
  16204. var frame = info.render.frame;
  16205. // Check the last frame we updated the VideoTexture
  16206. if ( _videoTextures[ id ] !== frame ) {
  16207. _videoTextures[ id ] = frame;
  16208. texture.update();
  16209. }
  16210. }
  16211. this.setTexture2D = setTexture2D;
  16212. this.setTexture3D = setTexture3D;
  16213. this.setTextureCube = setTextureCube;
  16214. this.setTextureCubeDynamic = setTextureCubeDynamic;
  16215. this.setupRenderTarget = setupRenderTarget;
  16216. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  16217. }
  16218. /**
  16219. * @author thespite / http://www.twitter.com/thespite
  16220. */
  16221. function WebGLUtils( gl, extensions, capabilities ) {
  16222. function convert( p ) {
  16223. var extension;
  16224. if ( p === RepeatWrapping ) return 10497;
  16225. if ( p === ClampToEdgeWrapping ) return 33071;
  16226. if ( p === MirroredRepeatWrapping ) return 33648;
  16227. if ( p === NearestFilter ) return 9728;
  16228. if ( p === NearestMipMapNearestFilter ) return 9984;
  16229. if ( p === NearestMipMapLinearFilter ) return 9986;
  16230. if ( p === LinearFilter ) return 9729;
  16231. if ( p === LinearMipMapNearestFilter ) return 9985;
  16232. if ( p === LinearMipMapLinearFilter ) return 9987;
  16233. if ( p === UnsignedByteType ) return 5121;
  16234. if ( p === UnsignedShort4444Type ) return 32819;
  16235. if ( p === UnsignedShort5551Type ) return 32820;
  16236. if ( p === UnsignedShort565Type ) return 33635;
  16237. if ( p === ByteType ) return 5120;
  16238. if ( p === ShortType ) return 5122;
  16239. if ( p === UnsignedShortType ) return 5123;
  16240. if ( p === IntType ) return 5124;
  16241. if ( p === UnsignedIntType ) return 5125;
  16242. if ( p === FloatType ) return 5126;
  16243. if ( p === HalfFloatType ) {
  16244. if ( capabilities.isWebGL2 ) return 5131;
  16245. extension = extensions.get( 'OES_texture_half_float' );
  16246. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  16247. }
  16248. if ( p === AlphaFormat ) return 6406;
  16249. if ( p === RGBFormat ) return 6407;
  16250. if ( p === RGBAFormat ) return 6408;
  16251. if ( p === LuminanceFormat ) return 6409;
  16252. if ( p === LuminanceAlphaFormat ) return 6410;
  16253. if ( p === DepthFormat ) return 6402;
  16254. if ( p === DepthStencilFormat ) return 34041;
  16255. if ( p === RedFormat ) return 6403;
  16256. if ( p === AddEquation ) return 32774;
  16257. if ( p === SubtractEquation ) return 32778;
  16258. if ( p === ReverseSubtractEquation ) return 32779;
  16259. if ( p === ZeroFactor ) return 0;
  16260. if ( p === OneFactor ) return 1;
  16261. if ( p === SrcColorFactor ) return 768;
  16262. if ( p === OneMinusSrcColorFactor ) return 769;
  16263. if ( p === SrcAlphaFactor ) return 770;
  16264. if ( p === OneMinusSrcAlphaFactor ) return 771;
  16265. if ( p === DstAlphaFactor ) return 772;
  16266. if ( p === OneMinusDstAlphaFactor ) return 773;
  16267. if ( p === DstColorFactor ) return 774;
  16268. if ( p === OneMinusDstColorFactor ) return 775;
  16269. if ( p === SrcAlphaSaturateFactor ) return 776;
  16270. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  16271. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  16272. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  16273. if ( extension !== null ) {
  16274. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  16275. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  16276. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  16277. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  16278. }
  16279. }
  16280. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  16281. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  16282. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  16283. if ( extension !== null ) {
  16284. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  16285. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  16286. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  16287. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  16288. }
  16289. }
  16290. if ( p === RGB_ETC1_Format ) {
  16291. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  16292. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  16293. }
  16294. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  16295. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  16296. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  16297. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  16298. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  16299. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  16300. if ( extension !== null ) {
  16301. return p;
  16302. }
  16303. }
  16304. if ( p === MinEquation || p === MaxEquation ) {
  16305. if ( capabilities.isWebGL2 ) {
  16306. if ( p === MinEquation ) return 32775;
  16307. if ( p === MaxEquation ) return 32776;
  16308. }
  16309. extension = extensions.get( 'EXT_blend_minmax' );
  16310. if ( extension !== null ) {
  16311. if ( p === MinEquation ) return extension.MIN_EXT;
  16312. if ( p === MaxEquation ) return extension.MAX_EXT;
  16313. }
  16314. }
  16315. if ( p === UnsignedInt248Type ) {
  16316. if ( capabilities.isWebGL2 ) return 34042;
  16317. extension = extensions.get( 'WEBGL_depth_texture' );
  16318. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  16319. }
  16320. return 0;
  16321. }
  16322. return { convert: convert };
  16323. }
  16324. /**
  16325. * @author mrdoob / http://mrdoob.com/
  16326. */
  16327. function Group() {
  16328. Object3D.call( this );
  16329. this.type = 'Group';
  16330. }
  16331. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16332. constructor: Group,
  16333. isGroup: true
  16334. } );
  16335. /**
  16336. * @author mrdoob / http://mrdoob.com/
  16337. * @author mikael emtinger / http://gomo.se/
  16338. * @author WestLangley / http://github.com/WestLangley
  16339. */
  16340. function Camera() {
  16341. Object3D.call( this );
  16342. this.type = 'Camera';
  16343. this.matrixWorldInverse = new Matrix4();
  16344. this.projectionMatrix = new Matrix4();
  16345. this.projectionMatrixInverse = new Matrix4();
  16346. }
  16347. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16348. constructor: Camera,
  16349. isCamera: true,
  16350. copy: function ( source, recursive ) {
  16351. Object3D.prototype.copy.call( this, source, recursive );
  16352. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  16353. this.projectionMatrix.copy( source.projectionMatrix );
  16354. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  16355. return this;
  16356. },
  16357. getWorldDirection: function ( target ) {
  16358. if ( target === undefined ) {
  16359. console.warn( 'THREE.Camera: .getWorldDirection() target is now required' );
  16360. target = new Vector3();
  16361. }
  16362. this.updateMatrixWorld( true );
  16363. var e = this.matrixWorld.elements;
  16364. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  16365. },
  16366. updateMatrixWorld: function ( force ) {
  16367. Object3D.prototype.updateMatrixWorld.call( this, force );
  16368. this.matrixWorldInverse.getInverse( this.matrixWorld );
  16369. },
  16370. clone: function () {
  16371. return new this.constructor().copy( this );
  16372. }
  16373. } );
  16374. /**
  16375. * @author mrdoob / http://mrdoob.com/
  16376. * @author greggman / http://games.greggman.com/
  16377. * @author zz85 / http://www.lab4games.net/zz85/blog
  16378. * @author tschw
  16379. */
  16380. function PerspectiveCamera( fov, aspect, near, far ) {
  16381. Camera.call( this );
  16382. this.type = 'PerspectiveCamera';
  16383. this.fov = fov !== undefined ? fov : 50;
  16384. this.zoom = 1;
  16385. this.near = near !== undefined ? near : 0.1;
  16386. this.far = far !== undefined ? far : 2000;
  16387. this.focus = 10;
  16388. this.aspect = aspect !== undefined ? aspect : 1;
  16389. this.view = null;
  16390. this.filmGauge = 35; // width of the film (default in millimeters)
  16391. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  16392. this.updateProjectionMatrix();
  16393. }
  16394. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  16395. constructor: PerspectiveCamera,
  16396. isPerspectiveCamera: true,
  16397. copy: function ( source, recursive ) {
  16398. Camera.prototype.copy.call( this, source, recursive );
  16399. this.fov = source.fov;
  16400. this.zoom = source.zoom;
  16401. this.near = source.near;
  16402. this.far = source.far;
  16403. this.focus = source.focus;
  16404. this.aspect = source.aspect;
  16405. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16406. this.filmGauge = source.filmGauge;
  16407. this.filmOffset = source.filmOffset;
  16408. return this;
  16409. },
  16410. /**
  16411. * Sets the FOV by focal length in respect to the current .filmGauge.
  16412. *
  16413. * The default film gauge is 35, so that the focal length can be specified for
  16414. * a 35mm (full frame) camera.
  16415. *
  16416. * Values for focal length and film gauge must have the same unit.
  16417. */
  16418. setFocalLength: function ( focalLength ) {
  16419. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  16420. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  16421. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  16422. this.updateProjectionMatrix();
  16423. },
  16424. /**
  16425. * Calculates the focal length from the current .fov and .filmGauge.
  16426. */
  16427. getFocalLength: function () {
  16428. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  16429. return 0.5 * this.getFilmHeight() / vExtentSlope;
  16430. },
  16431. getEffectiveFOV: function () {
  16432. return _Math.RAD2DEG * 2 * Math.atan(
  16433. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  16434. },
  16435. getFilmWidth: function () {
  16436. // film not completely covered in portrait format (aspect < 1)
  16437. return this.filmGauge * Math.min( this.aspect, 1 );
  16438. },
  16439. getFilmHeight: function () {
  16440. // film not completely covered in landscape format (aspect > 1)
  16441. return this.filmGauge / Math.max( this.aspect, 1 );
  16442. },
  16443. /**
  16444. * Sets an offset in a larger frustum. This is useful for multi-window or
  16445. * multi-monitor/multi-machine setups.
  16446. *
  16447. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  16448. * the monitors are in grid like this
  16449. *
  16450. * +---+---+---+
  16451. * | A | B | C |
  16452. * +---+---+---+
  16453. * | D | E | F |
  16454. * +---+---+---+
  16455. *
  16456. * then for each monitor you would call it like this
  16457. *
  16458. * var w = 1920;
  16459. * var h = 1080;
  16460. * var fullWidth = w * 3;
  16461. * var fullHeight = h * 2;
  16462. *
  16463. * --A--
  16464. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  16465. * --B--
  16466. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  16467. * --C--
  16468. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  16469. * --D--
  16470. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  16471. * --E--
  16472. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  16473. * --F--
  16474. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  16475. *
  16476. * Note there is no reason monitors have to be the same size or in a grid.
  16477. */
  16478. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  16479. this.aspect = fullWidth / fullHeight;
  16480. if ( this.view === null ) {
  16481. this.view = {
  16482. enabled: true,
  16483. fullWidth: 1,
  16484. fullHeight: 1,
  16485. offsetX: 0,
  16486. offsetY: 0,
  16487. width: 1,
  16488. height: 1
  16489. };
  16490. }
  16491. this.view.enabled = true;
  16492. this.view.fullWidth = fullWidth;
  16493. this.view.fullHeight = fullHeight;
  16494. this.view.offsetX = x;
  16495. this.view.offsetY = y;
  16496. this.view.width = width;
  16497. this.view.height = height;
  16498. this.updateProjectionMatrix();
  16499. },
  16500. clearViewOffset: function () {
  16501. if ( this.view !== null ) {
  16502. this.view.enabled = false;
  16503. }
  16504. this.updateProjectionMatrix();
  16505. },
  16506. updateProjectionMatrix: function () {
  16507. var near = this.near,
  16508. top = near * Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  16509. height = 2 * top,
  16510. width = this.aspect * height,
  16511. left = - 0.5 * width,
  16512. view = this.view;
  16513. if ( this.view !== null && this.view.enabled ) {
  16514. var fullWidth = view.fullWidth,
  16515. fullHeight = view.fullHeight;
  16516. left += view.offsetX * width / fullWidth;
  16517. top -= view.offsetY * height / fullHeight;
  16518. width *= view.width / fullWidth;
  16519. height *= view.height / fullHeight;
  16520. }
  16521. var skew = this.filmOffset;
  16522. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16523. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  16524. this.projectionMatrixInverse.getInverse( this.projectionMatrix );
  16525. },
  16526. toJSON: function ( meta ) {
  16527. var data = Object3D.prototype.toJSON.call( this, meta );
  16528. data.object.fov = this.fov;
  16529. data.object.zoom = this.zoom;
  16530. data.object.near = this.near;
  16531. data.object.far = this.far;
  16532. data.object.focus = this.focus;
  16533. data.object.aspect = this.aspect;
  16534. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16535. data.object.filmGauge = this.filmGauge;
  16536. data.object.filmOffset = this.filmOffset;
  16537. return data;
  16538. }
  16539. } );
  16540. /**
  16541. * @author mrdoob / http://mrdoob.com/
  16542. */
  16543. function ArrayCamera( array ) {
  16544. PerspectiveCamera.call( this );
  16545. this.cameras = array || [];
  16546. }
  16547. ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
  16548. constructor: ArrayCamera,
  16549. isArrayCamera: true
  16550. } );
  16551. /**
  16552. * @author jsantell / https://www.jsantell.com/
  16553. * @author mrdoob / http://mrdoob.com/
  16554. */
  16555. var cameraLPos = new Vector3();
  16556. var cameraRPos = new Vector3();
  16557. /**
  16558. * Assumes 2 cameras that are parallel and share an X-axis, and that
  16559. * the cameras' projection and world matrices have already been set.
  16560. * And that near and far planes are identical for both cameras.
  16561. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  16562. */
  16563. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  16564. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  16565. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  16566. var ipd = cameraLPos.distanceTo( cameraRPos );
  16567. var projL = cameraL.projectionMatrix.elements;
  16568. var projR = cameraR.projectionMatrix.elements;
  16569. // VR systems will have identical far and near planes, and
  16570. // most likely identical top and bottom frustum extents.
  16571. // Use the left camera for these values.
  16572. var near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  16573. var far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  16574. var topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  16575. var bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  16576. var leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  16577. var rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  16578. var left = near * leftFov;
  16579. var right = near * rightFov;
  16580. // Calculate the new camera's position offset from the
  16581. // left camera. xOffset should be roughly half `ipd`.
  16582. var zOffset = ipd / ( - leftFov + rightFov );
  16583. var xOffset = zOffset * - leftFov;
  16584. // TODO: Better way to apply this offset?
  16585. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  16586. camera.translateX( xOffset );
  16587. camera.translateZ( zOffset );
  16588. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  16589. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  16590. // Find the union of the frustum values of the cameras and scale
  16591. // the values so that the near plane's position does not change in world space,
  16592. // although must now be relative to the new union camera.
  16593. var near2 = near + zOffset;
  16594. var far2 = far + zOffset;
  16595. var left2 = left - xOffset;
  16596. var right2 = right + ( ipd - xOffset );
  16597. var top2 = topFov * far / far2 * near2;
  16598. var bottom2 = bottomFov * far / far2 * near2;
  16599. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  16600. }
  16601. /**
  16602. * @author mrdoob / http://mrdoob.com/
  16603. */
  16604. function WebVRManager( renderer ) {
  16605. var scope = this;
  16606. var device = null;
  16607. var frameData = null;
  16608. var poseTarget = null;
  16609. var controllers = [];
  16610. var standingMatrix = new Matrix4();
  16611. var standingMatrixInverse = new Matrix4();
  16612. var framebufferScaleFactor = 1.0;
  16613. var frameOfReferenceType = 'stage';
  16614. if ( typeof window !== 'undefined' && 'VRFrameData' in window ) {
  16615. frameData = new window.VRFrameData();
  16616. window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
  16617. }
  16618. var matrixWorldInverse = new Matrix4();
  16619. var tempQuaternion = new Quaternion();
  16620. var tempPosition = new Vector3();
  16621. var cameraL = new PerspectiveCamera();
  16622. cameraL.bounds = new Vector4( 0.0, 0.0, 0.5, 1.0 );
  16623. cameraL.layers.enable( 1 );
  16624. var cameraR = new PerspectiveCamera();
  16625. cameraR.bounds = new Vector4( 0.5, 0.0, 0.5, 1.0 );
  16626. cameraR.layers.enable( 2 );
  16627. var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
  16628. cameraVR.layers.enable( 1 );
  16629. cameraVR.layers.enable( 2 );
  16630. //
  16631. function isPresenting() {
  16632. return device !== null && device.isPresenting === true;
  16633. }
  16634. var currentSize, currentPixelRatio;
  16635. function onVRDisplayPresentChange() {
  16636. if ( isPresenting() ) {
  16637. var eyeParameters = device.getEyeParameters( 'left' );
  16638. var renderWidth = eyeParameters.renderWidth * framebufferScaleFactor;
  16639. var renderHeight = eyeParameters.renderHeight * framebufferScaleFactor;
  16640. currentPixelRatio = renderer.getPixelRatio();
  16641. currentSize = renderer.getSize();
  16642. renderer.setDrawingBufferSize( renderWidth * 2, renderHeight, 1 );
  16643. animation.start();
  16644. } else {
  16645. if ( scope.enabled ) {
  16646. renderer.setDrawingBufferSize( currentSize.width, currentSize.height, currentPixelRatio );
  16647. }
  16648. animation.stop();
  16649. }
  16650. }
  16651. //
  16652. var triggers = [];
  16653. function findGamepad( id ) {
  16654. var gamepads = navigator.getGamepads && navigator.getGamepads();
  16655. for ( var i = 0, j = 0, l = gamepads.length; i < l; i ++ ) {
  16656. var gamepad = gamepads[ i ];
  16657. if ( gamepad && ( gamepad.id === 'Daydream Controller' ||
  16658. gamepad.id === 'Gear VR Controller' || gamepad.id === 'Oculus Go Controller' ||
  16659. gamepad.id === 'OpenVR Gamepad' || gamepad.id.startsWith( 'Oculus Touch' ) ||
  16660. gamepad.id.startsWith( 'Spatial Controller' ) ) ) {
  16661. if ( j === id ) return gamepad;
  16662. j ++;
  16663. }
  16664. }
  16665. }
  16666. function updateControllers() {
  16667. for ( var i = 0; i < controllers.length; i ++ ) {
  16668. var controller = controllers[ i ];
  16669. var gamepad = findGamepad( i );
  16670. if ( gamepad !== undefined && gamepad.pose !== undefined ) {
  16671. if ( gamepad.pose === null ) return;
  16672. // Pose
  16673. var pose = gamepad.pose;
  16674. if ( pose.hasPosition === false ) controller.position.set( 0.2, - 0.6, - 0.05 );
  16675. if ( pose.position !== null ) controller.position.fromArray( pose.position );
  16676. if ( pose.orientation !== null ) controller.quaternion.fromArray( pose.orientation );
  16677. controller.matrix.compose( controller.position, controller.quaternion, controller.scale );
  16678. controller.matrix.premultiply( standingMatrix );
  16679. controller.matrix.decompose( controller.position, controller.quaternion, controller.scale );
  16680. controller.matrixWorldNeedsUpdate = true;
  16681. controller.visible = true;
  16682. // Trigger
  16683. var buttonId = gamepad.id === 'Daydream Controller' ? 0 : 1;
  16684. if ( triggers[ i ] !== gamepad.buttons[ buttonId ].pressed ) {
  16685. triggers[ i ] = gamepad.buttons[ buttonId ].pressed;
  16686. if ( triggers[ i ] === true ) {
  16687. controller.dispatchEvent( { type: 'selectstart' } );
  16688. } else {
  16689. controller.dispatchEvent( { type: 'selectend' } );
  16690. controller.dispatchEvent( { type: 'select' } );
  16691. }
  16692. }
  16693. } else {
  16694. controller.visible = false;
  16695. }
  16696. }
  16697. }
  16698. //
  16699. this.enabled = false;
  16700. this.getController = function ( id ) {
  16701. var controller = controllers[ id ];
  16702. if ( controller === undefined ) {
  16703. controller = new Group();
  16704. controller.matrixAutoUpdate = false;
  16705. controller.visible = false;
  16706. controllers[ id ] = controller;
  16707. }
  16708. return controller;
  16709. };
  16710. this.getDevice = function () {
  16711. return device;
  16712. };
  16713. this.setDevice = function ( value ) {
  16714. if ( value !== undefined ) device = value;
  16715. animation.setContext( value );
  16716. };
  16717. this.setFramebufferScaleFactor = function ( value ) {
  16718. framebufferScaleFactor = value;
  16719. };
  16720. this.setFrameOfReferenceType = function ( value ) {
  16721. frameOfReferenceType = value;
  16722. };
  16723. this.setPoseTarget = function ( object ) {
  16724. if ( object !== undefined ) poseTarget = object;
  16725. };
  16726. this.getCamera = function ( camera ) {
  16727. var userHeight = frameOfReferenceType === 'stage' ? 1.6 : 0;
  16728. if ( device === null ) {
  16729. camera.position.set( 0, userHeight, 0 );
  16730. return camera;
  16731. }
  16732. device.depthNear = camera.near;
  16733. device.depthFar = camera.far;
  16734. device.getFrameData( frameData );
  16735. //
  16736. if ( frameOfReferenceType === 'stage' ) {
  16737. var stageParameters = device.stageParameters;
  16738. if ( stageParameters ) {
  16739. standingMatrix.fromArray( stageParameters.sittingToStandingTransform );
  16740. } else {
  16741. standingMatrix.makeTranslation( 0, userHeight, 0 );
  16742. }
  16743. }
  16744. var pose = frameData.pose;
  16745. var poseObject = poseTarget !== null ? poseTarget : camera;
  16746. // We want to manipulate poseObject by its position and quaternion components since users may rely on them.
  16747. poseObject.matrix.copy( standingMatrix );
  16748. poseObject.matrix.decompose( poseObject.position, poseObject.quaternion, poseObject.scale );
  16749. if ( pose.orientation !== null ) {
  16750. tempQuaternion.fromArray( pose.orientation );
  16751. poseObject.quaternion.multiply( tempQuaternion );
  16752. }
  16753. if ( pose.position !== null ) {
  16754. tempQuaternion.setFromRotationMatrix( standingMatrix );
  16755. tempPosition.fromArray( pose.position );
  16756. tempPosition.applyQuaternion( tempQuaternion );
  16757. poseObject.position.add( tempPosition );
  16758. }
  16759. poseObject.updateMatrixWorld();
  16760. if ( device.isPresenting === false ) return camera;
  16761. //
  16762. cameraL.near = camera.near;
  16763. cameraR.near = camera.near;
  16764. cameraL.far = camera.far;
  16765. cameraR.far = camera.far;
  16766. cameraL.matrixWorldInverse.fromArray( frameData.leftViewMatrix );
  16767. cameraR.matrixWorldInverse.fromArray( frameData.rightViewMatrix );
  16768. // TODO (mrdoob) Double check this code
  16769. standingMatrixInverse.getInverse( standingMatrix );
  16770. if ( frameOfReferenceType === 'stage' ) {
  16771. cameraL.matrixWorldInverse.multiply( standingMatrixInverse );
  16772. cameraR.matrixWorldInverse.multiply( standingMatrixInverse );
  16773. }
  16774. var parent = poseObject.parent;
  16775. if ( parent !== null ) {
  16776. matrixWorldInverse.getInverse( parent.matrixWorld );
  16777. cameraL.matrixWorldInverse.multiply( matrixWorldInverse );
  16778. cameraR.matrixWorldInverse.multiply( matrixWorldInverse );
  16779. }
  16780. // envMap and Mirror needs camera.matrixWorld
  16781. cameraL.matrixWorld.getInverse( cameraL.matrixWorldInverse );
  16782. cameraR.matrixWorld.getInverse( cameraR.matrixWorldInverse );
  16783. cameraL.projectionMatrix.fromArray( frameData.leftProjectionMatrix );
  16784. cameraR.projectionMatrix.fromArray( frameData.rightProjectionMatrix );
  16785. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  16786. //
  16787. var layers = device.getLayers();
  16788. if ( layers.length ) {
  16789. var layer = layers[ 0 ];
  16790. if ( layer.leftBounds !== null && layer.leftBounds.length === 4 ) {
  16791. cameraL.bounds.fromArray( layer.leftBounds );
  16792. }
  16793. if ( layer.rightBounds !== null && layer.rightBounds.length === 4 ) {
  16794. cameraR.bounds.fromArray( layer.rightBounds );
  16795. }
  16796. }
  16797. updateControllers();
  16798. return cameraVR;
  16799. };
  16800. this.getStandingMatrix = function () {
  16801. return standingMatrix;
  16802. };
  16803. this.isPresenting = isPresenting;
  16804. // Animation Loop
  16805. var animation = new WebGLAnimation();
  16806. this.setAnimationLoop = function ( callback ) {
  16807. animation.setAnimationLoop( callback );
  16808. };
  16809. this.submitFrame = function () {
  16810. if ( isPresenting() ) device.submitFrame();
  16811. };
  16812. this.dispose = function () {
  16813. if ( typeof window !== 'undefined' ) {
  16814. window.removeEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange );
  16815. }
  16816. };
  16817. }
  16818. /**
  16819. * @author mrdoob / http://mrdoob.com/
  16820. */
  16821. function WebXRManager( renderer ) {
  16822. var gl = renderer.context;
  16823. var device = null;
  16824. var session = null;
  16825. var framebufferScaleFactor = 1.0;
  16826. var frameOfReference = null;
  16827. var frameOfReferenceType = 'stage';
  16828. var pose = null;
  16829. var poseTarget = null;
  16830. var controllers = [];
  16831. var inputSources = [];
  16832. function isPresenting() {
  16833. return session !== null && frameOfReference !== null;
  16834. }
  16835. //
  16836. var cameraL = new PerspectiveCamera();
  16837. cameraL.layers.enable( 1 );
  16838. cameraL.viewport = new Vector4();
  16839. var cameraR = new PerspectiveCamera();
  16840. cameraR.layers.enable( 2 );
  16841. cameraR.viewport = new Vector4();
  16842. var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
  16843. cameraVR.layers.enable( 1 );
  16844. cameraVR.layers.enable( 2 );
  16845. //
  16846. this.enabled = false;
  16847. this.getController = function ( id ) {
  16848. var controller = controllers[ id ];
  16849. if ( controller === undefined ) {
  16850. controller = new Group();
  16851. controller.matrixAutoUpdate = false;
  16852. controller.visible = false;
  16853. controllers[ id ] = controller;
  16854. }
  16855. return controller;
  16856. };
  16857. this.getDevice = function () {
  16858. return device;
  16859. };
  16860. this.setDevice = function ( value ) {
  16861. if ( value !== undefined ) device = value;
  16862. if ( value instanceof XRDevice ) gl.setCompatibleXRDevice( value );
  16863. };
  16864. //
  16865. function onSessionEvent( event ) {
  16866. var controller = controllers[ inputSources.indexOf( event.inputSource ) ];
  16867. if ( controller ) controller.dispatchEvent( { type: event.type } );
  16868. }
  16869. function onSessionEnd() {
  16870. renderer.setFramebuffer( null );
  16871. animation.stop();
  16872. }
  16873. this.setFramebufferScaleFactor = function ( value ) {
  16874. framebufferScaleFactor = value;
  16875. };
  16876. this.setFrameOfReferenceType = function ( value ) {
  16877. frameOfReferenceType = value;
  16878. };
  16879. this.setSession = function ( value ) {
  16880. session = value;
  16881. if ( session !== null ) {
  16882. session.addEventListener( 'select', onSessionEvent );
  16883. session.addEventListener( 'selectstart', onSessionEvent );
  16884. session.addEventListener( 'selectend', onSessionEvent );
  16885. session.addEventListener( 'end', onSessionEnd );
  16886. session.baseLayer = new XRWebGLLayer( session, gl, { framebufferScaleFactor: framebufferScaleFactor } );
  16887. session.requestFrameOfReference( frameOfReferenceType ).then( function ( value ) {
  16888. frameOfReference = value;
  16889. renderer.setFramebuffer( session.baseLayer.framebuffer );
  16890. animation.setContext( session );
  16891. animation.start();
  16892. } );
  16893. //
  16894. inputSources = session.getInputSources();
  16895. session.addEventListener( 'inputsourceschange', function () {
  16896. inputSources = session.getInputSources();
  16897. console.log( inputSources );
  16898. for ( var i = 0; i < controllers.length; i ++ ) {
  16899. var controller = controllers[ i ];
  16900. controller.userData.inputSource = inputSources[ i ];
  16901. }
  16902. } );
  16903. }
  16904. };
  16905. function updateCamera( camera, parent ) {
  16906. if ( parent === null ) {
  16907. camera.matrixWorld.copy( camera.matrix );
  16908. } else {
  16909. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  16910. }
  16911. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  16912. }
  16913. this.setPoseTarget = function ( object ) {
  16914. if ( object !== undefined ) poseTarget = object;
  16915. };
  16916. this.getCamera = function ( camera ) {
  16917. if ( isPresenting() ) {
  16918. var parent = camera.parent;
  16919. var cameras = cameraVR.cameras;
  16920. var object = poseTarget || camera;
  16921. updateCamera( cameraVR, parent );
  16922. for ( var i = 0; i < cameras.length; i ++ ) {
  16923. updateCamera( cameras[ i ], parent );
  16924. }
  16925. // update camera and its children
  16926. object.matrixWorld.copy( cameraVR.matrixWorld );
  16927. var children = object.children;
  16928. for ( var i = 0, l = children.length; i < l; i ++ ) {
  16929. children[ i ].updateMatrixWorld( true );
  16930. }
  16931. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  16932. return cameraVR;
  16933. }
  16934. return camera;
  16935. };
  16936. this.getCameraPose = function ( ) {
  16937. return pose;
  16938. };
  16939. this.isPresenting = isPresenting;
  16940. // Animation Loop
  16941. var onAnimationFrameCallback = null;
  16942. function onAnimationFrame( time, frame ) {
  16943. pose = frame.getDevicePose( frameOfReference );
  16944. if ( pose !== null ) {
  16945. var layer = session.baseLayer;
  16946. var views = frame.views;
  16947. for ( var i = 0; i < views.length; i ++ ) {
  16948. var view = views[ i ];
  16949. var viewport = layer.getViewport( view );
  16950. var viewMatrix = pose.getViewMatrix( view );
  16951. var camera = cameraVR.cameras[ i ];
  16952. camera.matrix.fromArray( viewMatrix ).getInverse( camera.matrix );
  16953. camera.projectionMatrix.fromArray( view.projectionMatrix );
  16954. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  16955. if ( i === 0 ) {
  16956. cameraVR.matrix.copy( camera.matrix );
  16957. }
  16958. }
  16959. }
  16960. //
  16961. for ( var i = 0; i < controllers.length; i ++ ) {
  16962. var controller = controllers[ i ];
  16963. var inputSource = inputSources[ i ];
  16964. if ( inputSource ) {
  16965. var inputPose = frame.getInputPose( inputSource, frameOfReference );
  16966. if ( inputPose !== null ) {
  16967. if ( 'targetRay' in inputPose ) {
  16968. controller.matrix.elements = inputPose.targetRay.transformMatrix;
  16969. } else if ( 'pointerMatrix' in inputPose ) {
  16970. // DEPRECATED
  16971. controller.matrix.elements = inputPose.pointerMatrix;
  16972. }
  16973. controller.matrix.decompose( controller.position, controller.rotation, controller.scale );
  16974. controller.visible = true;
  16975. continue;
  16976. }
  16977. }
  16978. controller.visible = false;
  16979. }
  16980. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  16981. }
  16982. var animation = new WebGLAnimation();
  16983. animation.setAnimationLoop( onAnimationFrame );
  16984. this.setAnimationLoop = function ( callback ) {
  16985. onAnimationFrameCallback = callback;
  16986. };
  16987. this.dispose = function () {};
  16988. // DEPRECATED
  16989. this.getStandingMatrix = function () {
  16990. console.warn( 'THREE.WebXRManager: getStandingMatrix() is no longer needed.' );
  16991. return new THREE.Matrix4();
  16992. };
  16993. this.submitFrame = function () {};
  16994. }
  16995. /**
  16996. * @author supereggbert / http://www.paulbrunt.co.uk/
  16997. * @author mrdoob / http://mrdoob.com/
  16998. * @author alteredq / http://alteredqualia.com/
  16999. * @author szimek / https://github.com/szimek/
  17000. * @author tschw
  17001. */
  17002. function WebGLRenderer( parameters ) {
  17003. console.log( 'THREE.WebGLRenderer', REVISION );
  17004. parameters = parameters || {};
  17005. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  17006. _context = parameters.context !== undefined ? parameters.context : null,
  17007. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  17008. _depth = parameters.depth !== undefined ? parameters.depth : true,
  17009. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  17010. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  17011. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  17012. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  17013. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default';
  17014. var currentRenderList = null;
  17015. var currentRenderState = null;
  17016. // public properties
  17017. this.domElement = _canvas;
  17018. this.context = null;
  17019. // clearing
  17020. this.autoClear = true;
  17021. this.autoClearColor = true;
  17022. this.autoClearDepth = true;
  17023. this.autoClearStencil = true;
  17024. // scene graph
  17025. this.sortObjects = true;
  17026. // user-defined clipping
  17027. this.clippingPlanes = [];
  17028. this.localClippingEnabled = false;
  17029. // physically based shading
  17030. this.gammaFactor = 2.0; // for backwards compatibility
  17031. this.gammaInput = false;
  17032. this.gammaOutput = false;
  17033. // physical lights
  17034. this.physicallyCorrectLights = false;
  17035. // tone mapping
  17036. this.toneMapping = LinearToneMapping;
  17037. this.toneMappingExposure = 1.0;
  17038. this.toneMappingWhitePoint = 1.0;
  17039. // morphs
  17040. this.maxMorphTargets = 8;
  17041. this.maxMorphNormals = 4;
  17042. // internal properties
  17043. var _this = this,
  17044. _isContextLost = false,
  17045. // internal state cache
  17046. _framebuffer = null,
  17047. _currentRenderTarget = null,
  17048. _currentFramebuffer = null,
  17049. _currentMaterialId = - 1,
  17050. // geometry and program caching
  17051. _currentGeometryProgram = {
  17052. geometry: null,
  17053. program: null,
  17054. wireframe: false
  17055. },
  17056. _currentCamera = null,
  17057. _currentArrayCamera = null,
  17058. _currentViewport = new Vector4(),
  17059. _currentScissor = new Vector4(),
  17060. _currentScissorTest = null,
  17061. //
  17062. _usedTextureUnits = 0,
  17063. //
  17064. _width = _canvas.width,
  17065. _height = _canvas.height,
  17066. _pixelRatio = 1,
  17067. _viewport = new Vector4( 0, 0, _width, _height ),
  17068. _scissor = new Vector4( 0, 0, _width, _height ),
  17069. _scissorTest = false,
  17070. // frustum
  17071. _frustum = new Frustum(),
  17072. // clipping
  17073. _clipping = new WebGLClipping(),
  17074. _clippingEnabled = false,
  17075. _localClippingEnabled = false,
  17076. // camera matrices cache
  17077. _projScreenMatrix = new Matrix4(),
  17078. _vector3 = new Vector3();
  17079. function getTargetPixelRatio() {
  17080. return _currentRenderTarget === null ? _pixelRatio : 1;
  17081. }
  17082. // initialize
  17083. var _gl;
  17084. try {
  17085. var contextAttributes = {
  17086. alpha: _alpha,
  17087. depth: _depth,
  17088. stencil: _stencil,
  17089. antialias: _antialias,
  17090. premultipliedAlpha: _premultipliedAlpha,
  17091. preserveDrawingBuffer: _preserveDrawingBuffer,
  17092. powerPreference: _powerPreference
  17093. };
  17094. // event listeners must be registered before WebGL context is created, see #12753
  17095. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  17096. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  17097. _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );
  17098. if ( _gl === null ) {
  17099. if ( _canvas.getContext( 'webgl' ) !== null ) {
  17100. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  17101. } else {
  17102. throw new Error( 'Error creating WebGL context.' );
  17103. }
  17104. }
  17105. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  17106. if ( _gl.getShaderPrecisionFormat === undefined ) {
  17107. _gl.getShaderPrecisionFormat = function () {
  17108. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  17109. };
  17110. }
  17111. } catch ( error ) {
  17112. console.error( 'THREE.WebGLRenderer: ' + error.message );
  17113. }
  17114. var extensions, capabilities, state, info;
  17115. var properties, textures, attributes, geometries, objects;
  17116. var programCache, renderLists, renderStates;
  17117. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  17118. var utils;
  17119. function initGLContext() {
  17120. extensions = new WebGLExtensions( _gl );
  17121. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  17122. if ( ! capabilities.isWebGL2 ) {
  17123. extensions.get( 'WEBGL_depth_texture' );
  17124. extensions.get( 'OES_texture_float' );
  17125. extensions.get( 'OES_texture_half_float' );
  17126. extensions.get( 'OES_texture_half_float_linear' );
  17127. extensions.get( 'OES_standard_derivatives' );
  17128. extensions.get( 'OES_element_index_uint' );
  17129. extensions.get( 'ANGLE_instanced_arrays' );
  17130. }
  17131. extensions.get( 'OES_texture_float_linear' );
  17132. utils = new WebGLUtils( _gl, extensions, capabilities );
  17133. state = new WebGLState( _gl, extensions, utils, capabilities );
  17134. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  17135. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  17136. info = new WebGLInfo( _gl );
  17137. properties = new WebGLProperties();
  17138. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  17139. attributes = new WebGLAttributes( _gl );
  17140. geometries = new WebGLGeometries( _gl, attributes, info );
  17141. objects = new WebGLObjects( geometries, info );
  17142. morphtargets = new WebGLMorphtargets( _gl );
  17143. programCache = new WebGLPrograms( _this, extensions, capabilities );
  17144. renderLists = new WebGLRenderLists();
  17145. renderStates = new WebGLRenderStates();
  17146. background = new WebGLBackground( _this, state, objects, _premultipliedAlpha );
  17147. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  17148. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  17149. info.programs = programCache.programs;
  17150. _this.context = _gl;
  17151. _this.capabilities = capabilities;
  17152. _this.extensions = extensions;
  17153. _this.properties = properties;
  17154. _this.renderLists = renderLists;
  17155. _this.state = state;
  17156. _this.info = info;
  17157. }
  17158. initGLContext();
  17159. // vr
  17160. var vr = null;
  17161. if ( typeof navigator !== 'undefined' ) {
  17162. vr = ( 'xr' in navigator ) ? new WebXRManager( _this ) : new WebVRManager( _this );
  17163. }
  17164. this.vr = vr;
  17165. // shadow map
  17166. var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  17167. this.shadowMap = shadowMap;
  17168. // API
  17169. this.getContext = function () {
  17170. return _gl;
  17171. };
  17172. this.getContextAttributes = function () {
  17173. return _gl.getContextAttributes();
  17174. };
  17175. this.forceContextLoss = function () {
  17176. var extension = extensions.get( 'WEBGL_lose_context' );
  17177. if ( extension ) extension.loseContext();
  17178. };
  17179. this.forceContextRestore = function () {
  17180. var extension = extensions.get( 'WEBGL_lose_context' );
  17181. if ( extension ) extension.restoreContext();
  17182. };
  17183. this.getPixelRatio = function () {
  17184. return _pixelRatio;
  17185. };
  17186. this.setPixelRatio = function ( value ) {
  17187. if ( value === undefined ) return;
  17188. _pixelRatio = value;
  17189. this.setSize( _width, _height, false );
  17190. };
  17191. this.getSize = function () {
  17192. return {
  17193. width: _width,
  17194. height: _height
  17195. };
  17196. };
  17197. this.setSize = function ( width, height, updateStyle ) {
  17198. if ( vr.isPresenting() ) {
  17199. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  17200. return;
  17201. }
  17202. _width = width;
  17203. _height = height;
  17204. _canvas.width = width * _pixelRatio;
  17205. _canvas.height = height * _pixelRatio;
  17206. if ( updateStyle !== false ) {
  17207. _canvas.style.width = width + 'px';
  17208. _canvas.style.height = height + 'px';
  17209. }
  17210. this.setViewport( 0, 0, width, height );
  17211. };
  17212. this.getDrawingBufferSize = function () {
  17213. return {
  17214. width: _width * _pixelRatio,
  17215. height: _height * _pixelRatio
  17216. };
  17217. };
  17218. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  17219. _width = width;
  17220. _height = height;
  17221. _pixelRatio = pixelRatio;
  17222. _canvas.width = width * pixelRatio;
  17223. _canvas.height = height * pixelRatio;
  17224. this.setViewport( 0, 0, width, height );
  17225. };
  17226. this.getCurrentViewport = function () {
  17227. return _currentViewport;
  17228. };
  17229. this.setViewport = function ( x, y, width, height ) {
  17230. _viewport.set( x, _height - y - height, width, height );
  17231. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  17232. };
  17233. this.setScissor = function ( x, y, width, height ) {
  17234. _scissor.set( x, _height - y - height, width, height );
  17235. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  17236. };
  17237. this.setScissorTest = function ( boolean ) {
  17238. state.setScissorTest( _scissorTest = boolean );
  17239. };
  17240. // Clearing
  17241. this.getClearColor = function () {
  17242. return background.getClearColor();
  17243. };
  17244. this.setClearColor = function () {
  17245. background.setClearColor.apply( background, arguments );
  17246. };
  17247. this.getClearAlpha = function () {
  17248. return background.getClearAlpha();
  17249. };
  17250. this.setClearAlpha = function () {
  17251. background.setClearAlpha.apply( background, arguments );
  17252. };
  17253. this.clear = function ( color, depth, stencil ) {
  17254. var bits = 0;
  17255. if ( color === undefined || color ) bits |= 16384;
  17256. if ( depth === undefined || depth ) bits |= 256;
  17257. if ( stencil === undefined || stencil ) bits |= 1024;
  17258. _gl.clear( bits );
  17259. };
  17260. this.clearColor = function () {
  17261. this.clear( true, false, false );
  17262. };
  17263. this.clearDepth = function () {
  17264. this.clear( false, true, false );
  17265. };
  17266. this.clearStencil = function () {
  17267. this.clear( false, false, true );
  17268. };
  17269. //
  17270. this.dispose = function () {
  17271. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  17272. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  17273. renderLists.dispose();
  17274. renderStates.dispose();
  17275. properties.dispose();
  17276. objects.dispose();
  17277. vr.dispose();
  17278. animation.stop();
  17279. };
  17280. // Events
  17281. function onContextLost( event ) {
  17282. event.preventDefault();
  17283. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  17284. _isContextLost = true;
  17285. }
  17286. function onContextRestore( /* event */ ) {
  17287. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  17288. _isContextLost = false;
  17289. initGLContext();
  17290. }
  17291. function onMaterialDispose( event ) {
  17292. var material = event.target;
  17293. material.removeEventListener( 'dispose', onMaterialDispose );
  17294. deallocateMaterial( material );
  17295. }
  17296. // Buffer deallocation
  17297. function deallocateMaterial( material ) {
  17298. releaseMaterialProgramReference( material );
  17299. properties.remove( material );
  17300. }
  17301. function releaseMaterialProgramReference( material ) {
  17302. var programInfo = properties.get( material ).program;
  17303. material.program = undefined;
  17304. if ( programInfo !== undefined ) {
  17305. programCache.releaseProgram( programInfo );
  17306. }
  17307. }
  17308. // Buffer rendering
  17309. function renderObjectImmediate( object, program ) {
  17310. object.render( function ( object ) {
  17311. _this.renderBufferImmediate( object, program );
  17312. } );
  17313. }
  17314. this.renderBufferImmediate = function ( object, program ) {
  17315. state.initAttributes();
  17316. var buffers = properties.get( object );
  17317. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  17318. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  17319. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  17320. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  17321. var programAttributes = program.getAttributes();
  17322. if ( object.hasPositions ) {
  17323. _gl.bindBuffer( 34962, buffers.position );
  17324. _gl.bufferData( 34962, object.positionArray, 35048 );
  17325. state.enableAttribute( programAttributes.position );
  17326. _gl.vertexAttribPointer( programAttributes.position, 3, 5126, false, 0, 0 );
  17327. }
  17328. if ( object.hasNormals ) {
  17329. _gl.bindBuffer( 34962, buffers.normal );
  17330. _gl.bufferData( 34962, object.normalArray, 35048 );
  17331. state.enableAttribute( programAttributes.normal );
  17332. _gl.vertexAttribPointer( programAttributes.normal, 3, 5126, false, 0, 0 );
  17333. }
  17334. if ( object.hasUvs ) {
  17335. _gl.bindBuffer( 34962, buffers.uv );
  17336. _gl.bufferData( 34962, object.uvArray, 35048 );
  17337. state.enableAttribute( programAttributes.uv );
  17338. _gl.vertexAttribPointer( programAttributes.uv, 2, 5126, false, 0, 0 );
  17339. }
  17340. if ( object.hasColors ) {
  17341. _gl.bindBuffer( 34962, buffers.color );
  17342. _gl.bufferData( 34962, object.colorArray, 35048 );
  17343. state.enableAttribute( programAttributes.color );
  17344. _gl.vertexAttribPointer( programAttributes.color, 3, 5126, false, 0, 0 );
  17345. }
  17346. state.disableUnusedAttributes();
  17347. _gl.drawArrays( 4, 0, object.count );
  17348. object.count = 0;
  17349. };
  17350. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  17351. var frontFaceCW = ( object.isMesh && object.normalMatrix.determinant() < 0 );
  17352. state.setMaterial( material, frontFaceCW );
  17353. var program = setProgram( camera, fog, material, object );
  17354. var updateBuffers = false;
  17355. if ( _currentGeometryProgram.geometry !== geometry.id ||
  17356. _currentGeometryProgram.program !== program.id ||
  17357. _currentGeometryProgram.wireframe !== ( material.wireframe === true ) ) {
  17358. _currentGeometryProgram.geometry = geometry.id;
  17359. _currentGeometryProgram.program = program.id;
  17360. _currentGeometryProgram.wireframe = material.wireframe === true;
  17361. updateBuffers = true;
  17362. }
  17363. if ( object.morphTargetInfluences ) {
  17364. morphtargets.update( object, geometry, material, program );
  17365. updateBuffers = true;
  17366. }
  17367. //
  17368. var index = geometry.index;
  17369. var position = geometry.attributes.position;
  17370. var rangeFactor = 1;
  17371. if ( material.wireframe === true ) {
  17372. index = geometries.getWireframeAttribute( geometry );
  17373. rangeFactor = 2;
  17374. }
  17375. var attribute;
  17376. var renderer = bufferRenderer;
  17377. if ( index !== null ) {
  17378. attribute = attributes.get( index );
  17379. renderer = indexedBufferRenderer;
  17380. renderer.setIndex( attribute );
  17381. }
  17382. if ( updateBuffers ) {
  17383. setupVertexAttributes( material, program, geometry );
  17384. if ( index !== null ) {
  17385. _gl.bindBuffer( 34963, attribute.buffer );
  17386. }
  17387. }
  17388. //
  17389. var dataCount = Infinity;
  17390. if ( index !== null ) {
  17391. dataCount = index.count;
  17392. } else if ( position !== undefined ) {
  17393. dataCount = position.count;
  17394. }
  17395. var rangeStart = geometry.drawRange.start * rangeFactor;
  17396. var rangeCount = geometry.drawRange.count * rangeFactor;
  17397. var groupStart = group !== null ? group.start * rangeFactor : 0;
  17398. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  17399. var drawStart = Math.max( rangeStart, groupStart );
  17400. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  17401. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  17402. if ( drawCount === 0 ) return;
  17403. //
  17404. if ( object.isMesh ) {
  17405. if ( material.wireframe === true ) {
  17406. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  17407. renderer.setMode( 1 );
  17408. } else {
  17409. switch ( object.drawMode ) {
  17410. case TrianglesDrawMode:
  17411. renderer.setMode( 4 );
  17412. break;
  17413. case TriangleStripDrawMode:
  17414. renderer.setMode( 5 );
  17415. break;
  17416. case TriangleFanDrawMode:
  17417. renderer.setMode( 6 );
  17418. break;
  17419. }
  17420. }
  17421. } else if ( object.isLine ) {
  17422. var lineWidth = material.linewidth;
  17423. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  17424. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  17425. if ( object.isLineSegments ) {
  17426. renderer.setMode( 1 );
  17427. } else if ( object.isLineLoop ) {
  17428. renderer.setMode( 2 );
  17429. } else {
  17430. renderer.setMode( 3 );
  17431. }
  17432. } else if ( object.isPoints ) {
  17433. renderer.setMode( 0 );
  17434. } else if ( object.isSprite ) {
  17435. renderer.setMode( 4 );
  17436. }
  17437. if ( geometry && geometry.isInstancedBufferGeometry ) {
  17438. if ( geometry.maxInstancedCount > 0 ) {
  17439. renderer.renderInstances( geometry, drawStart, drawCount );
  17440. }
  17441. } else {
  17442. renderer.render( drawStart, drawCount );
  17443. }
  17444. };
  17445. function setupVertexAttributes( material, program, geometry ) {
  17446. if ( geometry && geometry.isInstancedBufferGeometry & ! capabilities.isWebGL2 ) {
  17447. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) {
  17448. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  17449. return;
  17450. }
  17451. }
  17452. state.initAttributes();
  17453. var geometryAttributes = geometry.attributes;
  17454. var programAttributes = program.getAttributes();
  17455. var materialDefaultAttributeValues = material.defaultAttributeValues;
  17456. for ( var name in programAttributes ) {
  17457. var programAttribute = programAttributes[ name ];
  17458. if ( programAttribute >= 0 ) {
  17459. var geometryAttribute = geometryAttributes[ name ];
  17460. if ( geometryAttribute !== undefined ) {
  17461. var normalized = geometryAttribute.normalized;
  17462. var size = geometryAttribute.itemSize;
  17463. var attribute = attributes.get( geometryAttribute );
  17464. // TODO Attribute may not be available on context restore
  17465. if ( attribute === undefined ) continue;
  17466. var buffer = attribute.buffer;
  17467. var type = attribute.type;
  17468. var bytesPerElement = attribute.bytesPerElement;
  17469. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  17470. var data = geometryAttribute.data;
  17471. var stride = data.stride;
  17472. var offset = geometryAttribute.offset;
  17473. if ( data && data.isInstancedInterleavedBuffer ) {
  17474. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  17475. if ( geometry.maxInstancedCount === undefined ) {
  17476. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  17477. }
  17478. } else {
  17479. state.enableAttribute( programAttribute );
  17480. }
  17481. _gl.bindBuffer( 34962, buffer );
  17482. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );
  17483. } else {
  17484. if ( geometryAttribute.isInstancedBufferAttribute ) {
  17485. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  17486. if ( geometry.maxInstancedCount === undefined ) {
  17487. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  17488. }
  17489. } else {
  17490. state.enableAttribute( programAttribute );
  17491. }
  17492. _gl.bindBuffer( 34962, buffer );
  17493. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );
  17494. }
  17495. } else if ( materialDefaultAttributeValues !== undefined ) {
  17496. var value = materialDefaultAttributeValues[ name ];
  17497. if ( value !== undefined ) {
  17498. switch ( value.length ) {
  17499. case 2:
  17500. _gl.vertexAttrib2fv( programAttribute, value );
  17501. break;
  17502. case 3:
  17503. _gl.vertexAttrib3fv( programAttribute, value );
  17504. break;
  17505. case 4:
  17506. _gl.vertexAttrib4fv( programAttribute, value );
  17507. break;
  17508. default:
  17509. _gl.vertexAttrib1fv( programAttribute, value );
  17510. }
  17511. }
  17512. }
  17513. }
  17514. }
  17515. state.disableUnusedAttributes();
  17516. }
  17517. // Compile
  17518. this.compile = function ( scene, camera ) {
  17519. currentRenderState = renderStates.get( scene, camera );
  17520. currentRenderState.init();
  17521. scene.traverse( function ( object ) {
  17522. if ( object.isLight ) {
  17523. currentRenderState.pushLight( object );
  17524. if ( object.castShadow ) {
  17525. currentRenderState.pushShadow( object );
  17526. }
  17527. }
  17528. } );
  17529. currentRenderState.setupLights( camera );
  17530. scene.traverse( function ( object ) {
  17531. if ( object.material ) {
  17532. if ( Array.isArray( object.material ) ) {
  17533. for ( var i = 0; i < object.material.length; i ++ ) {
  17534. initMaterial( object.material[ i ], scene.fog, object );
  17535. }
  17536. } else {
  17537. initMaterial( object.material, scene.fog, object );
  17538. }
  17539. }
  17540. } );
  17541. };
  17542. // Animation Loop
  17543. var onAnimationFrameCallback = null;
  17544. function onAnimationFrame( time ) {
  17545. if ( vr.isPresenting() ) return;
  17546. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  17547. }
  17548. var animation = new WebGLAnimation();
  17549. animation.setAnimationLoop( onAnimationFrame );
  17550. if ( typeof window !== 'undefined' ) animation.setContext( window );
  17551. this.setAnimationLoop = function ( callback ) {
  17552. onAnimationFrameCallback = callback;
  17553. vr.setAnimationLoop( callback );
  17554. animation.start();
  17555. };
  17556. // Rendering
  17557. this.render = function ( scene, camera, renderTarget, forceClear ) {
  17558. if ( ! ( camera && camera.isCamera ) ) {
  17559. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  17560. return;
  17561. }
  17562. if ( _isContextLost ) return;
  17563. // reset caching for this frame
  17564. _currentGeometryProgram.geometry = null;
  17565. _currentGeometryProgram.program = null;
  17566. _currentGeometryProgram.wireframe = false;
  17567. _currentMaterialId = - 1;
  17568. _currentCamera = null;
  17569. // update scene graph
  17570. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  17571. // update camera matrices and frustum
  17572. if ( camera.parent === null ) camera.updateMatrixWorld();
  17573. if ( vr.enabled ) {
  17574. camera = vr.getCamera( camera );
  17575. }
  17576. //
  17577. currentRenderState = renderStates.get( scene, camera );
  17578. currentRenderState.init();
  17579. scene.onBeforeRender( _this, scene, camera, renderTarget );
  17580. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  17581. _frustum.setFromMatrix( _projScreenMatrix );
  17582. _localClippingEnabled = this.localClippingEnabled;
  17583. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  17584. currentRenderList = renderLists.get( scene, camera );
  17585. currentRenderList.init();
  17586. projectObject( scene, camera, _this.sortObjects );
  17587. if ( _this.sortObjects === true ) {
  17588. currentRenderList.sort();
  17589. }
  17590. //
  17591. if ( _clippingEnabled ) _clipping.beginShadows();
  17592. var shadowsArray = currentRenderState.state.shadowsArray;
  17593. shadowMap.render( shadowsArray, scene, camera );
  17594. currentRenderState.setupLights( camera );
  17595. if ( _clippingEnabled ) _clipping.endShadows();
  17596. //
  17597. if ( this.info.autoReset ) this.info.reset();
  17598. if ( renderTarget === undefined ) {
  17599. renderTarget = null;
  17600. }
  17601. this.setRenderTarget( renderTarget );
  17602. //
  17603. background.render( currentRenderList, scene, camera, forceClear );
  17604. // render scene
  17605. var opaqueObjects = currentRenderList.opaque;
  17606. var transparentObjects = currentRenderList.transparent;
  17607. if ( scene.overrideMaterial ) {
  17608. var overrideMaterial = scene.overrideMaterial;
  17609. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  17610. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial );
  17611. } else {
  17612. // opaque pass (front-to-back order)
  17613. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
  17614. // transparent pass (back-to-front order)
  17615. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera );
  17616. }
  17617. // Generate mipmap if we're using any kind of mipmap filtering
  17618. if ( renderTarget ) {
  17619. textures.updateRenderTargetMipmap( renderTarget );
  17620. }
  17621. // Ensure depth buffer writing is enabled so it can be cleared on next render
  17622. state.buffers.depth.setTest( true );
  17623. state.buffers.depth.setMask( true );
  17624. state.buffers.color.setMask( true );
  17625. state.setPolygonOffset( false );
  17626. scene.onAfterRender( _this, scene, camera );
  17627. if ( vr.enabled ) {
  17628. vr.submitFrame();
  17629. }
  17630. // _gl.finish();
  17631. currentRenderList = null;
  17632. currentRenderState = null;
  17633. };
  17634. function projectObject( object, camera, sortObjects ) {
  17635. if ( object.visible === false ) return;
  17636. var visible = object.layers.test( camera.layers );
  17637. if ( visible ) {
  17638. if ( object.isLight ) {
  17639. currentRenderState.pushLight( object );
  17640. if ( object.castShadow ) {
  17641. currentRenderState.pushShadow( object );
  17642. }
  17643. } else if ( object.isSprite ) {
  17644. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  17645. if ( sortObjects ) {
  17646. _vector3.setFromMatrixPosition( object.matrixWorld )
  17647. .applyMatrix4( _projScreenMatrix );
  17648. }
  17649. var geometry = objects.update( object );
  17650. var material = object.material;
  17651. currentRenderList.push( object, geometry, material, _vector3.z, null );
  17652. }
  17653. } else if ( object.isImmediateRenderObject ) {
  17654. if ( sortObjects ) {
  17655. _vector3.setFromMatrixPosition( object.matrixWorld )
  17656. .applyMatrix4( _projScreenMatrix );
  17657. }
  17658. currentRenderList.push( object, null, object.material, _vector3.z, null );
  17659. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  17660. if ( object.isSkinnedMesh ) {
  17661. object.skeleton.update();
  17662. }
  17663. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  17664. if ( sortObjects ) {
  17665. _vector3.setFromMatrixPosition( object.matrixWorld )
  17666. .applyMatrix4( _projScreenMatrix );
  17667. }
  17668. var geometry = objects.update( object );
  17669. var material = object.material;
  17670. if ( Array.isArray( material ) ) {
  17671. var groups = geometry.groups;
  17672. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  17673. var group = groups[ i ];
  17674. var groupMaterial = material[ group.materialIndex ];
  17675. if ( groupMaterial && groupMaterial.visible ) {
  17676. currentRenderList.push( object, geometry, groupMaterial, _vector3.z, group );
  17677. }
  17678. }
  17679. } else if ( material.visible ) {
  17680. currentRenderList.push( object, geometry, material, _vector3.z, null );
  17681. }
  17682. }
  17683. }
  17684. }
  17685. var children = object.children;
  17686. for ( var i = 0, l = children.length; i < l; i ++ ) {
  17687. projectObject( children[ i ], camera, sortObjects );
  17688. }
  17689. }
  17690. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  17691. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  17692. var renderItem = renderList[ i ];
  17693. var object = renderItem.object;
  17694. var geometry = renderItem.geometry;
  17695. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  17696. var group = renderItem.group;
  17697. if ( camera.isArrayCamera ) {
  17698. _currentArrayCamera = camera;
  17699. var cameras = camera.cameras;
  17700. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  17701. var camera2 = cameras[ j ];
  17702. if ( object.layers.test( camera2.layers ) ) {
  17703. if ( 'viewport' in camera2 ) { // XR
  17704. state.viewport( _currentViewport.copy( camera2.viewport ) );
  17705. } else {
  17706. var bounds = camera2.bounds;
  17707. var x = bounds.x * _width;
  17708. var y = bounds.y * _height;
  17709. var width = bounds.z * _width;
  17710. var height = bounds.w * _height;
  17711. state.viewport( _currentViewport.set( x, y, width, height ).multiplyScalar( _pixelRatio ) );
  17712. }
  17713. currentRenderState.setupLights( camera2 );
  17714. renderObject( object, scene, camera2, geometry, material, group );
  17715. }
  17716. }
  17717. } else {
  17718. _currentArrayCamera = null;
  17719. renderObject( object, scene, camera, geometry, material, group );
  17720. }
  17721. }
  17722. }
  17723. function renderObject( object, scene, camera, geometry, material, group ) {
  17724. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  17725. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  17726. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  17727. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  17728. if ( object.isImmediateRenderObject ) {
  17729. state.setMaterial( material );
  17730. var program = setProgram( camera, scene.fog, material, object );
  17731. _currentGeometryProgram.geometry = null;
  17732. _currentGeometryProgram.program = null;
  17733. _currentGeometryProgram.wireframe = false;
  17734. renderObjectImmediate( object, program );
  17735. } else {
  17736. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  17737. }
  17738. object.onAfterRender( _this, scene, camera, geometry, material, group );
  17739. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  17740. }
  17741. function initMaterial( material, fog, object ) {
  17742. var materialProperties = properties.get( material );
  17743. var lights = currentRenderState.state.lights;
  17744. var shadowsArray = currentRenderState.state.shadowsArray;
  17745. var lightsHash = materialProperties.lightsHash;
  17746. var lightsStateHash = lights.state.hash;
  17747. var parameters = programCache.getParameters(
  17748. material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  17749. var code = programCache.getProgramCode( material, parameters );
  17750. var program = materialProperties.program;
  17751. var programChange = true;
  17752. if ( program === undefined ) {
  17753. // new material
  17754. material.addEventListener( 'dispose', onMaterialDispose );
  17755. } else if ( program.code !== code ) {
  17756. // changed glsl or parameters
  17757. releaseMaterialProgramReference( material );
  17758. } else if ( lightsHash.stateID !== lightsStateHash.stateID ||
  17759. lightsHash.directionalLength !== lightsStateHash.directionalLength ||
  17760. lightsHash.pointLength !== lightsStateHash.pointLength ||
  17761. lightsHash.spotLength !== lightsStateHash.spotLength ||
  17762. lightsHash.rectAreaLength !== lightsStateHash.rectAreaLength ||
  17763. lightsHash.hemiLength !== lightsStateHash.hemiLength ||
  17764. lightsHash.shadowsLength !== lightsStateHash.shadowsLength ) {
  17765. lightsHash.stateID = lightsStateHash.stateID;
  17766. lightsHash.directionalLength = lightsStateHash.directionalLength;
  17767. lightsHash.pointLength = lightsStateHash.pointLength;
  17768. lightsHash.spotLength = lightsStateHash.spotLength;
  17769. lightsHash.rectAreaLength = lightsStateHash.rectAreaLength;
  17770. lightsHash.hemiLength = lightsStateHash.hemiLength;
  17771. lightsHash.shadowsLength = lightsStateHash.shadowsLength;
  17772. programChange = false;
  17773. } else if ( parameters.shaderID !== undefined ) {
  17774. // same glsl and uniform list
  17775. return;
  17776. } else {
  17777. // only rebuild uniform list
  17778. programChange = false;
  17779. }
  17780. if ( programChange ) {
  17781. if ( parameters.shaderID ) {
  17782. var shader = ShaderLib[ parameters.shaderID ];
  17783. materialProperties.shader = {
  17784. name: material.type,
  17785. uniforms: UniformsUtils.clone( shader.uniforms ),
  17786. vertexShader: shader.vertexShader,
  17787. fragmentShader: shader.fragmentShader
  17788. };
  17789. } else {
  17790. materialProperties.shader = {
  17791. name: material.type,
  17792. uniforms: material.uniforms,
  17793. vertexShader: material.vertexShader,
  17794. fragmentShader: material.fragmentShader
  17795. };
  17796. }
  17797. material.onBeforeCompile( materialProperties.shader, _this );
  17798. // Computing code again as onBeforeCompile may have changed the shaders
  17799. code = programCache.getProgramCode( material, parameters );
  17800. program = programCache.acquireProgram( material, materialProperties.shader, parameters, code );
  17801. materialProperties.program = program;
  17802. material.program = program;
  17803. }
  17804. var programAttributes = program.getAttributes();
  17805. if ( material.morphTargets ) {
  17806. material.numSupportedMorphTargets = 0;
  17807. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  17808. if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
  17809. material.numSupportedMorphTargets ++;
  17810. }
  17811. }
  17812. }
  17813. if ( material.morphNormals ) {
  17814. material.numSupportedMorphNormals = 0;
  17815. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  17816. if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {
  17817. material.numSupportedMorphNormals ++;
  17818. }
  17819. }
  17820. }
  17821. var uniforms = materialProperties.shader.uniforms;
  17822. if ( ! material.isShaderMaterial &&
  17823. ! material.isRawShaderMaterial ||
  17824. material.clipping === true ) {
  17825. materialProperties.numClippingPlanes = _clipping.numPlanes;
  17826. materialProperties.numIntersection = _clipping.numIntersection;
  17827. uniforms.clippingPlanes = _clipping.uniform;
  17828. }
  17829. materialProperties.fog = fog;
  17830. // store the light setup it was created for
  17831. if ( lightsHash === undefined ) {
  17832. materialProperties.lightsHash = lightsHash = {};
  17833. }
  17834. lightsHash.stateID = lightsStateHash.stateID;
  17835. lightsHash.directionalLength = lightsStateHash.directionalLength;
  17836. lightsHash.pointLength = lightsStateHash.pointLength;
  17837. lightsHash.spotLength = lightsStateHash.spotLength;
  17838. lightsHash.rectAreaLength = lightsStateHash.rectAreaLength;
  17839. lightsHash.hemiLength = lightsStateHash.hemiLength;
  17840. lightsHash.shadowsLength = lightsStateHash.shadowsLength;
  17841. if ( material.lights ) {
  17842. // wire up the material to this renderer's lighting state
  17843. uniforms.ambientLightColor.value = lights.state.ambient;
  17844. uniforms.directionalLights.value = lights.state.directional;
  17845. uniforms.spotLights.value = lights.state.spot;
  17846. uniforms.rectAreaLights.value = lights.state.rectArea;
  17847. uniforms.pointLights.value = lights.state.point;
  17848. uniforms.hemisphereLights.value = lights.state.hemi;
  17849. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  17850. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  17851. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  17852. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  17853. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  17854. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  17855. // TODO (abelnation): add area lights shadow info to uniforms
  17856. }
  17857. var progUniforms = materialProperties.program.getUniforms(),
  17858. uniformsList =
  17859. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  17860. materialProperties.uniformsList = uniformsList;
  17861. }
  17862. function setProgram( camera, fog, material, object ) {
  17863. _usedTextureUnits = 0;
  17864. var materialProperties = properties.get( material );
  17865. var lights = currentRenderState.state.lights;
  17866. var lightsHash = materialProperties.lightsHash;
  17867. var lightsStateHash = lights.state.hash;
  17868. if ( _clippingEnabled ) {
  17869. if ( _localClippingEnabled || camera !== _currentCamera ) {
  17870. var useCache =
  17871. camera === _currentCamera &&
  17872. material.id === _currentMaterialId;
  17873. // we might want to call this function with some ClippingGroup
  17874. // object instead of the material, once it becomes feasible
  17875. // (#8465, #8379)
  17876. _clipping.setState(
  17877. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  17878. camera, materialProperties, useCache );
  17879. }
  17880. }
  17881. if ( material.needsUpdate === false ) {
  17882. if ( materialProperties.program === undefined ) {
  17883. material.needsUpdate = true;
  17884. } else if ( material.fog && materialProperties.fog !== fog ) {
  17885. material.needsUpdate = true;
  17886. } else if ( material.lights && ( lightsHash.stateID !== lightsStateHash.stateID ||
  17887. lightsHash.directionalLength !== lightsStateHash.directionalLength ||
  17888. lightsHash.pointLength !== lightsStateHash.pointLength ||
  17889. lightsHash.spotLength !== lightsStateHash.spotLength ||
  17890. lightsHash.rectAreaLength !== lightsStateHash.rectAreaLength ||
  17891. lightsHash.hemiLength !== lightsStateHash.hemiLength ||
  17892. lightsHash.shadowsLength !== lightsStateHash.shadowsLength ) ) {
  17893. material.needsUpdate = true;
  17894. } else if ( materialProperties.numClippingPlanes !== undefined &&
  17895. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  17896. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  17897. material.needsUpdate = true;
  17898. }
  17899. }
  17900. if ( material.needsUpdate ) {
  17901. initMaterial( material, fog, object );
  17902. material.needsUpdate = false;
  17903. }
  17904. var refreshProgram = false;
  17905. var refreshMaterial = false;
  17906. var refreshLights = false;
  17907. var program = materialProperties.program,
  17908. p_uniforms = program.getUniforms(),
  17909. m_uniforms = materialProperties.shader.uniforms;
  17910. if ( state.useProgram( program.program ) ) {
  17911. refreshProgram = true;
  17912. refreshMaterial = true;
  17913. refreshLights = true;
  17914. }
  17915. if ( material.id !== _currentMaterialId ) {
  17916. _currentMaterialId = material.id;
  17917. refreshMaterial = true;
  17918. }
  17919. if ( refreshProgram || _currentCamera !== camera ) {
  17920. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  17921. if ( capabilities.logarithmicDepthBuffer ) {
  17922. p_uniforms.setValue( _gl, 'logDepthBufFC',
  17923. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  17924. }
  17925. if ( _currentCamera !== camera ) {
  17926. _currentCamera = camera;
  17927. // lighting uniforms depend on the camera so enforce an update
  17928. // now, in case this material supports lights - or later, when
  17929. // the next material that does gets activated:
  17930. refreshMaterial = true; // set to true on material change
  17931. refreshLights = true; // remains set until update done
  17932. }
  17933. // load material specific uniforms
  17934. // (shader material also gets them for the sake of genericity)
  17935. if ( material.isShaderMaterial ||
  17936. material.isMeshPhongMaterial ||
  17937. material.isMeshStandardMaterial ||
  17938. material.envMap ) {
  17939. var uCamPos = p_uniforms.map.cameraPosition;
  17940. if ( uCamPos !== undefined ) {
  17941. uCamPos.setValue( _gl,
  17942. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  17943. }
  17944. }
  17945. if ( material.isMeshPhongMaterial ||
  17946. material.isMeshLambertMaterial ||
  17947. material.isMeshBasicMaterial ||
  17948. material.isMeshStandardMaterial ||
  17949. material.isShaderMaterial ||
  17950. material.skinning ) {
  17951. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  17952. }
  17953. }
  17954. // skinning uniforms must be set even if material didn't change
  17955. // auto-setting of texture unit for bone texture must go before other textures
  17956. // not sure why, but otherwise weird things happen
  17957. if ( material.skinning ) {
  17958. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  17959. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  17960. var skeleton = object.skeleton;
  17961. if ( skeleton ) {
  17962. var bones = skeleton.bones;
  17963. if ( capabilities.floatVertexTextures ) {
  17964. if ( skeleton.boneTexture === undefined ) {
  17965. // layout (1 matrix = 4 pixels)
  17966. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17967. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17968. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17969. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17970. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17971. var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  17972. size = _Math.ceilPowerOfTwo( size );
  17973. size = Math.max( size, 4 );
  17974. var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  17975. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  17976. var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  17977. boneTexture.needsUpdate = true;
  17978. skeleton.boneMatrices = boneMatrices;
  17979. skeleton.boneTexture = boneTexture;
  17980. skeleton.boneTextureSize = size;
  17981. }
  17982. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture );
  17983. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  17984. } else {
  17985. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  17986. }
  17987. }
  17988. }
  17989. if ( refreshMaterial ) {
  17990. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  17991. p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );
  17992. if ( material.lights ) {
  17993. // the current material requires lighting info
  17994. // note: all lighting uniforms are always set correctly
  17995. // they simply reference the renderer's state for their
  17996. // values
  17997. //
  17998. // use the current material's .needsUpdate flags to set
  17999. // the GL state when required
  18000. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  18001. }
  18002. // refresh uniforms common to several materials
  18003. if ( fog && material.fog ) {
  18004. refreshUniformsFog( m_uniforms, fog );
  18005. }
  18006. if ( material.isMeshBasicMaterial ) {
  18007. refreshUniformsCommon( m_uniforms, material );
  18008. } else if ( material.isMeshLambertMaterial ) {
  18009. refreshUniformsCommon( m_uniforms, material );
  18010. refreshUniformsLambert( m_uniforms, material );
  18011. } else if ( material.isMeshPhongMaterial ) {
  18012. refreshUniformsCommon( m_uniforms, material );
  18013. if ( material.isMeshToonMaterial ) {
  18014. refreshUniformsToon( m_uniforms, material );
  18015. } else {
  18016. refreshUniformsPhong( m_uniforms, material );
  18017. }
  18018. } else if ( material.isMeshStandardMaterial ) {
  18019. refreshUniformsCommon( m_uniforms, material );
  18020. if ( material.isMeshPhysicalMaterial ) {
  18021. refreshUniformsPhysical( m_uniforms, material );
  18022. } else {
  18023. refreshUniformsStandard( m_uniforms, material );
  18024. }
  18025. } else if ( material.isMeshMatcapMaterial ) {
  18026. refreshUniformsCommon( m_uniforms, material );
  18027. refreshUniformsMatcap( m_uniforms, material );
  18028. } else if ( material.isMeshDepthMaterial ) {
  18029. refreshUniformsCommon( m_uniforms, material );
  18030. refreshUniformsDepth( m_uniforms, material );
  18031. } else if ( material.isMeshDistanceMaterial ) {
  18032. refreshUniformsCommon( m_uniforms, material );
  18033. refreshUniformsDistance( m_uniforms, material );
  18034. } else if ( material.isMeshNormalMaterial ) {
  18035. refreshUniformsCommon( m_uniforms, material );
  18036. refreshUniformsNormal( m_uniforms, material );
  18037. } else if ( material.isLineBasicMaterial ) {
  18038. refreshUniformsLine( m_uniforms, material );
  18039. if ( material.isLineDashedMaterial ) {
  18040. refreshUniformsDash( m_uniforms, material );
  18041. }
  18042. } else if ( material.isPointsMaterial ) {
  18043. refreshUniformsPoints( m_uniforms, material );
  18044. } else if ( material.isSpriteMaterial ) {
  18045. refreshUniformsSprites( m_uniforms, material );
  18046. } else if ( material.isShadowMaterial ) {
  18047. m_uniforms.color.value = material.color;
  18048. m_uniforms.opacity.value = material.opacity;
  18049. }
  18050. // RectAreaLight Texture
  18051. // TODO (mrdoob): Find a nicer implementation
  18052. if ( m_uniforms.ltc_1 !== undefined ) m_uniforms.ltc_1.value = UniformsLib.LTC_1;
  18053. if ( m_uniforms.ltc_2 !== undefined ) m_uniforms.ltc_2.value = UniformsLib.LTC_2;
  18054. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, _this );
  18055. }
  18056. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  18057. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, _this );
  18058. material.uniformsNeedUpdate = false;
  18059. }
  18060. if ( material.isSpriteMaterial ) {
  18061. p_uniforms.setValue( _gl, 'center', object.center );
  18062. }
  18063. // common matrices
  18064. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  18065. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  18066. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  18067. return program;
  18068. }
  18069. // Uniforms (refresh uniforms objects)
  18070. function refreshUniformsCommon( uniforms, material ) {
  18071. uniforms.opacity.value = material.opacity;
  18072. if ( material.color ) {
  18073. uniforms.diffuse.value = material.color;
  18074. }
  18075. if ( material.emissive ) {
  18076. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  18077. }
  18078. if ( material.map ) {
  18079. uniforms.map.value = material.map;
  18080. }
  18081. if ( material.alphaMap ) {
  18082. uniforms.alphaMap.value = material.alphaMap;
  18083. }
  18084. if ( material.specularMap ) {
  18085. uniforms.specularMap.value = material.specularMap;
  18086. }
  18087. if ( material.envMap ) {
  18088. uniforms.envMap.value = material.envMap;
  18089. // don't flip CubeTexture envMaps, flip everything else:
  18090. // WebGLRenderTargetCube will be flipped for backwards compatibility
  18091. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  18092. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  18093. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  18094. uniforms.reflectivity.value = material.reflectivity;
  18095. uniforms.refractionRatio.value = material.refractionRatio;
  18096. uniforms.maxMipLevel.value = properties.get( material.envMap ).__maxMipLevel;
  18097. }
  18098. if ( material.lightMap ) {
  18099. uniforms.lightMap.value = material.lightMap;
  18100. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  18101. }
  18102. if ( material.aoMap ) {
  18103. uniforms.aoMap.value = material.aoMap;
  18104. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  18105. }
  18106. // uv repeat and offset setting priorities
  18107. // 1. color map
  18108. // 2. specular map
  18109. // 3. normal map
  18110. // 4. bump map
  18111. // 5. alpha map
  18112. // 6. emissive map
  18113. var uvScaleMap;
  18114. if ( material.map ) {
  18115. uvScaleMap = material.map;
  18116. } else if ( material.specularMap ) {
  18117. uvScaleMap = material.specularMap;
  18118. } else if ( material.displacementMap ) {
  18119. uvScaleMap = material.displacementMap;
  18120. } else if ( material.normalMap ) {
  18121. uvScaleMap = material.normalMap;
  18122. } else if ( material.bumpMap ) {
  18123. uvScaleMap = material.bumpMap;
  18124. } else if ( material.roughnessMap ) {
  18125. uvScaleMap = material.roughnessMap;
  18126. } else if ( material.metalnessMap ) {
  18127. uvScaleMap = material.metalnessMap;
  18128. } else if ( material.alphaMap ) {
  18129. uvScaleMap = material.alphaMap;
  18130. } else if ( material.emissiveMap ) {
  18131. uvScaleMap = material.emissiveMap;
  18132. }
  18133. if ( uvScaleMap !== undefined ) {
  18134. // backwards compatibility
  18135. if ( uvScaleMap.isWebGLRenderTarget ) {
  18136. uvScaleMap = uvScaleMap.texture;
  18137. }
  18138. if ( uvScaleMap.matrixAutoUpdate === true ) {
  18139. uvScaleMap.updateMatrix();
  18140. }
  18141. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  18142. }
  18143. }
  18144. function refreshUniformsLine( uniforms, material ) {
  18145. uniforms.diffuse.value = material.color;
  18146. uniforms.opacity.value = material.opacity;
  18147. }
  18148. function refreshUniformsDash( uniforms, material ) {
  18149. uniforms.dashSize.value = material.dashSize;
  18150. uniforms.totalSize.value = material.dashSize + material.gapSize;
  18151. uniforms.scale.value = material.scale;
  18152. }
  18153. function refreshUniformsPoints( uniforms, material ) {
  18154. uniforms.diffuse.value = material.color;
  18155. uniforms.opacity.value = material.opacity;
  18156. uniforms.size.value = material.size * _pixelRatio;
  18157. uniforms.scale.value = _height * 0.5;
  18158. uniforms.map.value = material.map;
  18159. if ( material.map !== null ) {
  18160. if ( material.map.matrixAutoUpdate === true ) {
  18161. material.map.updateMatrix();
  18162. }
  18163. uniforms.uvTransform.value.copy( material.map.matrix );
  18164. }
  18165. }
  18166. function refreshUniformsSprites( uniforms, material ) {
  18167. uniforms.diffuse.value = material.color;
  18168. uniforms.opacity.value = material.opacity;
  18169. uniforms.rotation.value = material.rotation;
  18170. uniforms.map.value = material.map;
  18171. if ( material.map !== null ) {
  18172. if ( material.map.matrixAutoUpdate === true ) {
  18173. material.map.updateMatrix();
  18174. }
  18175. uniforms.uvTransform.value.copy( material.map.matrix );
  18176. }
  18177. }
  18178. function refreshUniformsFog( uniforms, fog ) {
  18179. uniforms.fogColor.value = fog.color;
  18180. if ( fog.isFog ) {
  18181. uniforms.fogNear.value = fog.near;
  18182. uniforms.fogFar.value = fog.far;
  18183. } else if ( fog.isFogExp2 ) {
  18184. uniforms.fogDensity.value = fog.density;
  18185. }
  18186. }
  18187. function refreshUniformsLambert( uniforms, material ) {
  18188. if ( material.emissiveMap ) {
  18189. uniforms.emissiveMap.value = material.emissiveMap;
  18190. }
  18191. }
  18192. function refreshUniformsPhong( uniforms, material ) {
  18193. uniforms.specular.value = material.specular;
  18194. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  18195. if ( material.emissiveMap ) {
  18196. uniforms.emissiveMap.value = material.emissiveMap;
  18197. }
  18198. if ( material.bumpMap ) {
  18199. uniforms.bumpMap.value = material.bumpMap;
  18200. uniforms.bumpScale.value = material.bumpScale;
  18201. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  18202. }
  18203. if ( material.normalMap ) {
  18204. uniforms.normalMap.value = material.normalMap;
  18205. uniforms.normalScale.value.copy( material.normalScale );
  18206. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  18207. }
  18208. if ( material.displacementMap ) {
  18209. uniforms.displacementMap.value = material.displacementMap;
  18210. uniforms.displacementScale.value = material.displacementScale;
  18211. uniforms.displacementBias.value = material.displacementBias;
  18212. }
  18213. }
  18214. function refreshUniformsToon( uniforms, material ) {
  18215. refreshUniformsPhong( uniforms, material );
  18216. if ( material.gradientMap ) {
  18217. uniforms.gradientMap.value = material.gradientMap;
  18218. }
  18219. }
  18220. function refreshUniformsStandard( uniforms, material ) {
  18221. uniforms.roughness.value = material.roughness;
  18222. uniforms.metalness.value = material.metalness;
  18223. if ( material.roughnessMap ) {
  18224. uniforms.roughnessMap.value = material.roughnessMap;
  18225. }
  18226. if ( material.metalnessMap ) {
  18227. uniforms.metalnessMap.value = material.metalnessMap;
  18228. }
  18229. if ( material.emissiveMap ) {
  18230. uniforms.emissiveMap.value = material.emissiveMap;
  18231. }
  18232. if ( material.bumpMap ) {
  18233. uniforms.bumpMap.value = material.bumpMap;
  18234. uniforms.bumpScale.value = material.bumpScale;
  18235. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  18236. }
  18237. if ( material.normalMap ) {
  18238. uniforms.normalMap.value = material.normalMap;
  18239. uniforms.normalScale.value.copy( material.normalScale );
  18240. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  18241. }
  18242. if ( material.displacementMap ) {
  18243. uniforms.displacementMap.value = material.displacementMap;
  18244. uniforms.displacementScale.value = material.displacementScale;
  18245. uniforms.displacementBias.value = material.displacementBias;
  18246. }
  18247. if ( material.envMap ) {
  18248. //uniforms.envMap.value = material.envMap; // part of uniforms common
  18249. uniforms.envMapIntensity.value = material.envMapIntensity;
  18250. }
  18251. }
  18252. function refreshUniformsPhysical( uniforms, material ) {
  18253. refreshUniformsStandard( uniforms, material );
  18254. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  18255. uniforms.clearCoat.value = material.clearCoat;
  18256. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  18257. }
  18258. function refreshUniformsMatcap( uniforms, material ) {
  18259. if ( material.matcap ) {
  18260. uniforms.matcap.value = material.matcap;
  18261. }
  18262. if ( material.bumpMap ) {
  18263. uniforms.bumpMap.value = material.bumpMap;
  18264. uniforms.bumpScale.value = material.bumpScale;
  18265. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  18266. }
  18267. if ( material.normalMap ) {
  18268. uniforms.normalMap.value = material.normalMap;
  18269. uniforms.normalScale.value.copy( material.normalScale );
  18270. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  18271. }
  18272. if ( material.displacementMap ) {
  18273. uniforms.displacementMap.value = material.displacementMap;
  18274. uniforms.displacementScale.value = material.displacementScale;
  18275. uniforms.displacementBias.value = material.displacementBias;
  18276. }
  18277. }
  18278. function refreshUniformsDepth( uniforms, material ) {
  18279. if ( material.displacementMap ) {
  18280. uniforms.displacementMap.value = material.displacementMap;
  18281. uniforms.displacementScale.value = material.displacementScale;
  18282. uniforms.displacementBias.value = material.displacementBias;
  18283. }
  18284. }
  18285. function refreshUniformsDistance( uniforms, material ) {
  18286. if ( material.displacementMap ) {
  18287. uniforms.displacementMap.value = material.displacementMap;
  18288. uniforms.displacementScale.value = material.displacementScale;
  18289. uniforms.displacementBias.value = material.displacementBias;
  18290. }
  18291. uniforms.referencePosition.value.copy( material.referencePosition );
  18292. uniforms.nearDistance.value = material.nearDistance;
  18293. uniforms.farDistance.value = material.farDistance;
  18294. }
  18295. function refreshUniformsNormal( uniforms, material ) {
  18296. if ( material.bumpMap ) {
  18297. uniforms.bumpMap.value = material.bumpMap;
  18298. uniforms.bumpScale.value = material.bumpScale;
  18299. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  18300. }
  18301. if ( material.normalMap ) {
  18302. uniforms.normalMap.value = material.normalMap;
  18303. uniforms.normalScale.value.copy( material.normalScale );
  18304. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  18305. }
  18306. if ( material.displacementMap ) {
  18307. uniforms.displacementMap.value = material.displacementMap;
  18308. uniforms.displacementScale.value = material.displacementScale;
  18309. uniforms.displacementBias.value = material.displacementBias;
  18310. }
  18311. }
  18312. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  18313. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  18314. uniforms.ambientLightColor.needsUpdate = value;
  18315. uniforms.directionalLights.needsUpdate = value;
  18316. uniforms.pointLights.needsUpdate = value;
  18317. uniforms.spotLights.needsUpdate = value;
  18318. uniforms.rectAreaLights.needsUpdate = value;
  18319. uniforms.hemisphereLights.needsUpdate = value;
  18320. }
  18321. // Textures
  18322. function allocTextureUnit() {
  18323. var textureUnit = _usedTextureUnits;
  18324. if ( textureUnit >= capabilities.maxTextures ) {
  18325. console.warn( 'THREE.WebGLRenderer: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  18326. }
  18327. _usedTextureUnits += 1;
  18328. return textureUnit;
  18329. }
  18330. this.allocTextureUnit = allocTextureUnit;
  18331. // this.setTexture2D = setTexture2D;
  18332. this.setTexture2D = ( function () {
  18333. var warned = false;
  18334. // backwards compatibility: peel texture.texture
  18335. return function setTexture2D( texture, slot ) {
  18336. if ( texture && texture.isWebGLRenderTarget ) {
  18337. if ( ! warned ) {
  18338. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  18339. warned = true;
  18340. }
  18341. texture = texture.texture;
  18342. }
  18343. textures.setTexture2D( texture, slot );
  18344. };
  18345. }() );
  18346. this.setTexture3D = ( function () {
  18347. // backwards compatibility: peel texture.texture
  18348. return function setTexture3D( texture, slot ) {
  18349. textures.setTexture3D( texture, slot );
  18350. };
  18351. }() );
  18352. this.setTexture = ( function () {
  18353. var warned = false;
  18354. return function setTexture( texture, slot ) {
  18355. if ( ! warned ) {
  18356. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  18357. warned = true;
  18358. }
  18359. textures.setTexture2D( texture, slot );
  18360. };
  18361. }() );
  18362. this.setTextureCube = ( function () {
  18363. var warned = false;
  18364. return function setTextureCube( texture, slot ) {
  18365. // backwards compatibility: peel texture.texture
  18366. if ( texture && texture.isWebGLRenderTargetCube ) {
  18367. if ( ! warned ) {
  18368. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  18369. warned = true;
  18370. }
  18371. texture = texture.texture;
  18372. }
  18373. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  18374. // TODO: unify these code paths
  18375. if ( ( texture && texture.isCubeTexture ) ||
  18376. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  18377. // CompressedTexture can have Array in image :/
  18378. // this function alone should take care of cube textures
  18379. textures.setTextureCube( texture, slot );
  18380. } else {
  18381. // assumed: texture property of THREE.WebGLRenderTargetCube
  18382. textures.setTextureCubeDynamic( texture, slot );
  18383. }
  18384. };
  18385. }() );
  18386. //
  18387. this.setFramebuffer = function ( value ) {
  18388. _framebuffer = value;
  18389. };
  18390. this.getRenderTarget = function () {
  18391. return _currentRenderTarget;
  18392. };
  18393. this.setRenderTarget = function ( renderTarget ) {
  18394. _currentRenderTarget = renderTarget;
  18395. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  18396. textures.setupRenderTarget( renderTarget );
  18397. }
  18398. var framebuffer = _framebuffer;
  18399. var isCube = false;
  18400. if ( renderTarget ) {
  18401. var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18402. if ( renderTarget.isWebGLRenderTargetCube ) {
  18403. framebuffer = __webglFramebuffer[ renderTarget.activeCubeFace ];
  18404. isCube = true;
  18405. } else {
  18406. framebuffer = __webglFramebuffer;
  18407. }
  18408. _currentViewport.copy( renderTarget.viewport );
  18409. _currentScissor.copy( renderTarget.scissor );
  18410. _currentScissorTest = renderTarget.scissorTest;
  18411. } else {
  18412. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  18413. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  18414. _currentScissorTest = _scissorTest;
  18415. }
  18416. if ( _currentFramebuffer !== framebuffer ) {
  18417. _gl.bindFramebuffer( 36160, framebuffer );
  18418. _currentFramebuffer = framebuffer;
  18419. }
  18420. state.viewport( _currentViewport );
  18421. state.scissor( _currentScissor );
  18422. state.setScissorTest( _currentScissorTest );
  18423. if ( isCube ) {
  18424. var textureProperties = properties.get( renderTarget.texture );
  18425. _gl.framebufferTexture2D( 36160, 36064, 34069 + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  18426. }
  18427. };
  18428. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  18429. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  18430. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  18431. return;
  18432. }
  18433. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18434. if ( framebuffer ) {
  18435. var restore = false;
  18436. if ( framebuffer !== _currentFramebuffer ) {
  18437. _gl.bindFramebuffer( 36160, framebuffer );
  18438. restore = true;
  18439. }
  18440. try {
  18441. var texture = renderTarget.texture;
  18442. var textureFormat = texture.format;
  18443. var textureType = texture.type;
  18444. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  18445. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  18446. return;
  18447. }
  18448. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  18449. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  18450. ! ( textureType === HalfFloatType && ( capabilities.isWebGL2 ? extensions.get( 'EXT_color_buffer_float' ) : extensions.get( 'EXT_color_buffer_half_float' ) ) ) ) {
  18451. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  18452. return;
  18453. }
  18454. if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) {
  18455. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  18456. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  18457. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  18458. }
  18459. } else {
  18460. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  18461. }
  18462. } finally {
  18463. if ( restore ) {
  18464. _gl.bindFramebuffer( 36160, _currentFramebuffer );
  18465. }
  18466. }
  18467. }
  18468. };
  18469. this.copyFramebufferToTexture = function ( position, texture, level ) {
  18470. var width = texture.image.width;
  18471. var height = texture.image.height;
  18472. var glFormat = utils.convert( texture.format );
  18473. this.setTexture2D( texture, 0 );
  18474. _gl.copyTexImage2D( 3553, level || 0, glFormat, position.x, position.y, width, height, 0 );
  18475. };
  18476. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level ) {
  18477. var width = srcTexture.image.width;
  18478. var height = srcTexture.image.height;
  18479. var glFormat = utils.convert( dstTexture.format );
  18480. var glType = utils.convert( dstTexture.type );
  18481. this.setTexture2D( dstTexture, 0 );
  18482. if ( srcTexture.isDataTexture ) {
  18483. _gl.texSubImage2D( 3553, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  18484. } else {
  18485. _gl.texSubImage2D( 3553, level || 0, position.x, position.y, glFormat, glType, srcTexture.image );
  18486. }
  18487. };
  18488. }
  18489. /**
  18490. * @author mrdoob / http://mrdoob.com/
  18491. * @author alteredq / http://alteredqualia.com/
  18492. */
  18493. function FogExp2( color, density ) {
  18494. this.name = '';
  18495. this.color = new Color( color );
  18496. this.density = ( density !== undefined ) ? density : 0.00025;
  18497. }
  18498. FogExp2.prototype.isFogExp2 = true;
  18499. FogExp2.prototype.clone = function () {
  18500. return new FogExp2( this.color, this.density );
  18501. };
  18502. FogExp2.prototype.toJSON = function ( /* meta */ ) {
  18503. return {
  18504. type: 'FogExp2',
  18505. color: this.color.getHex(),
  18506. density: this.density
  18507. };
  18508. };
  18509. /**
  18510. * @author mrdoob / http://mrdoob.com/
  18511. * @author alteredq / http://alteredqualia.com/
  18512. */
  18513. function Fog( color, near, far ) {
  18514. this.name = '';
  18515. this.color = new Color( color );
  18516. this.near = ( near !== undefined ) ? near : 1;
  18517. this.far = ( far !== undefined ) ? far : 1000;
  18518. }
  18519. Fog.prototype.isFog = true;
  18520. Fog.prototype.clone = function () {
  18521. return new Fog( this.color, this.near, this.far );
  18522. };
  18523. Fog.prototype.toJSON = function ( /* meta */ ) {
  18524. return {
  18525. type: 'Fog',
  18526. color: this.color.getHex(),
  18527. near: this.near,
  18528. far: this.far
  18529. };
  18530. };
  18531. /**
  18532. * @author mrdoob / http://mrdoob.com/
  18533. */
  18534. function Scene() {
  18535. Object3D.call( this );
  18536. this.type = 'Scene';
  18537. this.background = null;
  18538. this.fog = null;
  18539. this.overrideMaterial = null;
  18540. this.autoUpdate = true; // checked by the renderer
  18541. }
  18542. Scene.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18543. constructor: Scene,
  18544. copy: function ( source, recursive ) {
  18545. Object3D.prototype.copy.call( this, source, recursive );
  18546. if ( source.background !== null ) this.background = source.background.clone();
  18547. if ( source.fog !== null ) this.fog = source.fog.clone();
  18548. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  18549. this.autoUpdate = source.autoUpdate;
  18550. this.matrixAutoUpdate = source.matrixAutoUpdate;
  18551. return this;
  18552. },
  18553. toJSON: function ( meta ) {
  18554. var data = Object3D.prototype.toJSON.call( this, meta );
  18555. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  18556. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  18557. return data;
  18558. }
  18559. } );
  18560. /**
  18561. * @author benaadams / https://twitter.com/ben_a_adams
  18562. */
  18563. function InterleavedBuffer( array, stride ) {
  18564. this.array = array;
  18565. this.stride = stride;
  18566. this.count = array !== undefined ? array.length / stride : 0;
  18567. this.dynamic = false;
  18568. this.updateRange = { offset: 0, count: - 1 };
  18569. this.version = 0;
  18570. }
  18571. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  18572. set: function ( value ) {
  18573. if ( value === true ) this.version ++;
  18574. }
  18575. } );
  18576. Object.assign( InterleavedBuffer.prototype, {
  18577. isInterleavedBuffer: true,
  18578. onUploadCallback: function () {},
  18579. setArray: function ( array ) {
  18580. if ( Array.isArray( array ) ) {
  18581. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  18582. }
  18583. this.count = array !== undefined ? array.length / this.stride : 0;
  18584. this.array = array;
  18585. return this;
  18586. },
  18587. setDynamic: function ( value ) {
  18588. this.dynamic = value;
  18589. return this;
  18590. },
  18591. copy: function ( source ) {
  18592. this.array = new source.array.constructor( source.array );
  18593. this.count = source.count;
  18594. this.stride = source.stride;
  18595. this.dynamic = source.dynamic;
  18596. return this;
  18597. },
  18598. copyAt: function ( index1, attribute, index2 ) {
  18599. index1 *= this.stride;
  18600. index2 *= attribute.stride;
  18601. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  18602. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  18603. }
  18604. return this;
  18605. },
  18606. set: function ( value, offset ) {
  18607. if ( offset === undefined ) offset = 0;
  18608. this.array.set( value, offset );
  18609. return this;
  18610. },
  18611. clone: function () {
  18612. return new this.constructor().copy( this );
  18613. },
  18614. onUpload: function ( callback ) {
  18615. this.onUploadCallback = callback;
  18616. return this;
  18617. }
  18618. } );
  18619. /**
  18620. * @author benaadams / https://twitter.com/ben_a_adams
  18621. */
  18622. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  18623. this.data = interleavedBuffer;
  18624. this.itemSize = itemSize;
  18625. this.offset = offset;
  18626. this.normalized = normalized === true;
  18627. }
  18628. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  18629. count: {
  18630. get: function () {
  18631. return this.data.count;
  18632. }
  18633. },
  18634. array: {
  18635. get: function () {
  18636. return this.data.array;
  18637. }
  18638. }
  18639. } );
  18640. Object.assign( InterleavedBufferAttribute.prototype, {
  18641. isInterleavedBufferAttribute: true,
  18642. setX: function ( index, x ) {
  18643. this.data.array[ index * this.data.stride + this.offset ] = x;
  18644. return this;
  18645. },
  18646. setY: function ( index, y ) {
  18647. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  18648. return this;
  18649. },
  18650. setZ: function ( index, z ) {
  18651. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  18652. return this;
  18653. },
  18654. setW: function ( index, w ) {
  18655. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  18656. return this;
  18657. },
  18658. getX: function ( index ) {
  18659. return this.data.array[ index * this.data.stride + this.offset ];
  18660. },
  18661. getY: function ( index ) {
  18662. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  18663. },
  18664. getZ: function ( index ) {
  18665. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  18666. },
  18667. getW: function ( index ) {
  18668. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  18669. },
  18670. setXY: function ( index, x, y ) {
  18671. index = index * this.data.stride + this.offset;
  18672. this.data.array[ index + 0 ] = x;
  18673. this.data.array[ index + 1 ] = y;
  18674. return this;
  18675. },
  18676. setXYZ: function ( index, x, y, z ) {
  18677. index = index * this.data.stride + this.offset;
  18678. this.data.array[ index + 0 ] = x;
  18679. this.data.array[ index + 1 ] = y;
  18680. this.data.array[ index + 2 ] = z;
  18681. return this;
  18682. },
  18683. setXYZW: function ( index, x, y, z, w ) {
  18684. index = index * this.data.stride + this.offset;
  18685. this.data.array[ index + 0 ] = x;
  18686. this.data.array[ index + 1 ] = y;
  18687. this.data.array[ index + 2 ] = z;
  18688. this.data.array[ index + 3 ] = w;
  18689. return this;
  18690. }
  18691. } );
  18692. /**
  18693. * @author alteredq / http://alteredqualia.com/
  18694. *
  18695. * parameters = {
  18696. * color: <hex>,
  18697. * map: new THREE.Texture( <Image> ),
  18698. * rotation: <float>,
  18699. * sizeAttenuation: <bool>
  18700. * }
  18701. */
  18702. function SpriteMaterial( parameters ) {
  18703. Material.call( this );
  18704. this.type = 'SpriteMaterial';
  18705. this.color = new Color( 0xffffff );
  18706. this.map = null;
  18707. this.rotation = 0;
  18708. this.sizeAttenuation = true;
  18709. this.lights = false;
  18710. this.transparent = true;
  18711. this.setValues( parameters );
  18712. }
  18713. SpriteMaterial.prototype = Object.create( Material.prototype );
  18714. SpriteMaterial.prototype.constructor = SpriteMaterial;
  18715. SpriteMaterial.prototype.isSpriteMaterial = true;
  18716. SpriteMaterial.prototype.copy = function ( source ) {
  18717. Material.prototype.copy.call( this, source );
  18718. this.color.copy( source.color );
  18719. this.map = source.map;
  18720. this.rotation = source.rotation;
  18721. this.sizeAttenuation = source.sizeAttenuation;
  18722. return this;
  18723. };
  18724. /**
  18725. * @author mikael emtinger / http://gomo.se/
  18726. * @author alteredq / http://alteredqualia.com/
  18727. */
  18728. var geometry;
  18729. function Sprite( material ) {
  18730. Object3D.call( this );
  18731. this.type = 'Sprite';
  18732. if ( geometry === undefined ) {
  18733. geometry = new BufferGeometry();
  18734. var float32Array = new Float32Array( [
  18735. - 0.5, - 0.5, 0, 0, 0,
  18736. 0.5, - 0.5, 0, 1, 0,
  18737. 0.5, 0.5, 0, 1, 1,
  18738. - 0.5, 0.5, 0, 0, 1
  18739. ] );
  18740. var interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18741. geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18742. geometry.addAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18743. geometry.addAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18744. }
  18745. this.geometry = geometry;
  18746. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  18747. this.center = new Vector2( 0.5, 0.5 );
  18748. }
  18749. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18750. constructor: Sprite,
  18751. isSprite: true,
  18752. raycast: ( function () {
  18753. var intersectPoint = new Vector3();
  18754. var worldScale = new Vector3();
  18755. var mvPosition = new Vector3();
  18756. var alignedPosition = new Vector2();
  18757. var rotatedPosition = new Vector2();
  18758. var viewWorldMatrix = new Matrix4();
  18759. var vA = new Vector3();
  18760. var vB = new Vector3();
  18761. var vC = new Vector3();
  18762. var uvA = new Vector2();
  18763. var uvB = new Vector2();
  18764. var uvC = new Vector2();
  18765. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18766. // compute position in camera space
  18767. alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18768. // to check if rotation is not zero
  18769. if ( sin !== undefined ) {
  18770. rotatedPosition.x = ( cos * alignedPosition.x ) - ( sin * alignedPosition.y );
  18771. rotatedPosition.y = ( sin * alignedPosition.x ) + ( cos * alignedPosition.y );
  18772. } else {
  18773. rotatedPosition.copy( alignedPosition );
  18774. }
  18775. vertexPosition.copy( mvPosition );
  18776. vertexPosition.x += rotatedPosition.x;
  18777. vertexPosition.y += rotatedPosition.y;
  18778. // transform to world space
  18779. vertexPosition.applyMatrix4( viewWorldMatrix );
  18780. }
  18781. return function raycast( raycaster, intersects ) {
  18782. worldScale.setFromMatrixScale( this.matrixWorld );
  18783. viewWorldMatrix.getInverse( this.modelViewMatrix ).premultiply( this.matrixWorld );
  18784. mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18785. var rotation = this.material.rotation;
  18786. var sin, cos;
  18787. if ( rotation !== 0 ) {
  18788. cos = Math.cos( rotation );
  18789. sin = Math.sin( rotation );
  18790. }
  18791. var center = this.center;
  18792. transformVertex( vA.set( - 0.5, - 0.5, 0 ), mvPosition, center, worldScale, sin, cos );
  18793. transformVertex( vB.set( 0.5, - 0.5, 0 ), mvPosition, center, worldScale, sin, cos );
  18794. transformVertex( vC.set( 0.5, 0.5, 0 ), mvPosition, center, worldScale, sin, cos );
  18795. uvA.set( 0, 0 );
  18796. uvB.set( 1, 0 );
  18797. uvC.set( 1, 1 );
  18798. // check first triangle
  18799. var intersect = raycaster.ray.intersectTriangle( vA, vB, vC, false, intersectPoint );
  18800. if ( intersect === null ) {
  18801. // check second triangle
  18802. transformVertex( vB.set( - 0.5, 0.5, 0 ), mvPosition, center, worldScale, sin, cos );
  18803. uvB.set( 0, 1 );
  18804. intersect = raycaster.ray.intersectTriangle( vA, vC, vB, false, intersectPoint );
  18805. if ( intersect === null ) {
  18806. return;
  18807. }
  18808. }
  18809. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  18810. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18811. intersects.push( {
  18812. distance: distance,
  18813. point: intersectPoint.clone(),
  18814. uv: Triangle.getUV( intersectPoint, vA, vB, vC, uvA, uvB, uvC, new Vector2() ),
  18815. face: null,
  18816. object: this
  18817. } );
  18818. };
  18819. }() ),
  18820. clone: function () {
  18821. return new this.constructor( this.material ).copy( this );
  18822. },
  18823. copy: function ( source ) {
  18824. Object3D.prototype.copy.call( this, source );
  18825. if ( source.center !== undefined ) this.center.copy( source.center );
  18826. return this;
  18827. }
  18828. } );
  18829. /**
  18830. * @author mikael emtinger / http://gomo.se/
  18831. * @author alteredq / http://alteredqualia.com/
  18832. * @author mrdoob / http://mrdoob.com/
  18833. */
  18834. function LOD() {
  18835. Object3D.call( this );
  18836. this.type = 'LOD';
  18837. Object.defineProperties( this, {
  18838. levels: {
  18839. enumerable: true,
  18840. value: []
  18841. }
  18842. } );
  18843. }
  18844. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18845. constructor: LOD,
  18846. copy: function ( source ) {
  18847. Object3D.prototype.copy.call( this, source, false );
  18848. var levels = source.levels;
  18849. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  18850. var level = levels[ i ];
  18851. this.addLevel( level.object.clone(), level.distance );
  18852. }
  18853. return this;
  18854. },
  18855. addLevel: function ( object, distance ) {
  18856. if ( distance === undefined ) distance = 0;
  18857. distance = Math.abs( distance );
  18858. var levels = this.levels;
  18859. for ( var l = 0; l < levels.length; l ++ ) {
  18860. if ( distance < levels[ l ].distance ) {
  18861. break;
  18862. }
  18863. }
  18864. levels.splice( l, 0, { distance: distance, object: object } );
  18865. this.add( object );
  18866. },
  18867. getObjectForDistance: function ( distance ) {
  18868. var levels = this.levels;
  18869. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  18870. if ( distance < levels[ i ].distance ) {
  18871. break;
  18872. }
  18873. }
  18874. return levels[ i - 1 ].object;
  18875. },
  18876. raycast: ( function () {
  18877. var matrixPosition = new Vector3();
  18878. return function raycast( raycaster, intersects ) {
  18879. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  18880. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  18881. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18882. };
  18883. }() ),
  18884. update: function () {
  18885. var v1 = new Vector3();
  18886. var v2 = new Vector3();
  18887. return function update( camera ) {
  18888. var levels = this.levels;
  18889. if ( levels.length > 1 ) {
  18890. v1.setFromMatrixPosition( camera.matrixWorld );
  18891. v2.setFromMatrixPosition( this.matrixWorld );
  18892. var distance = v1.distanceTo( v2 );
  18893. levels[ 0 ].object.visible = true;
  18894. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  18895. if ( distance >= levels[ i ].distance ) {
  18896. levels[ i - 1 ].object.visible = false;
  18897. levels[ i ].object.visible = true;
  18898. } else {
  18899. break;
  18900. }
  18901. }
  18902. for ( ; i < l; i ++ ) {
  18903. levels[ i ].object.visible = false;
  18904. }
  18905. }
  18906. };
  18907. }(),
  18908. toJSON: function ( meta ) {
  18909. var data = Object3D.prototype.toJSON.call( this, meta );
  18910. data.object.levels = [];
  18911. var levels = this.levels;
  18912. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  18913. var level = levels[ i ];
  18914. data.object.levels.push( {
  18915. object: level.object.uuid,
  18916. distance: level.distance
  18917. } );
  18918. }
  18919. return data;
  18920. }
  18921. } );
  18922. /**
  18923. * @author mikael emtinger / http://gomo.se/
  18924. * @author alteredq / http://alteredqualia.com/
  18925. * @author michael guerrero / http://realitymeltdown.com
  18926. * @author ikerr / http://verold.com
  18927. */
  18928. function Skeleton( bones, boneInverses ) {
  18929. // copy the bone array
  18930. bones = bones || [];
  18931. this.bones = bones.slice( 0 );
  18932. this.boneMatrices = new Float32Array( this.bones.length * 16 );
  18933. // use the supplied bone inverses or calculate the inverses
  18934. if ( boneInverses === undefined ) {
  18935. this.calculateInverses();
  18936. } else {
  18937. if ( this.bones.length === boneInverses.length ) {
  18938. this.boneInverses = boneInverses.slice( 0 );
  18939. } else {
  18940. console.warn( 'THREE.Skeleton boneInverses is the wrong length.' );
  18941. this.boneInverses = [];
  18942. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  18943. this.boneInverses.push( new Matrix4() );
  18944. }
  18945. }
  18946. }
  18947. }
  18948. Object.assign( Skeleton.prototype, {
  18949. calculateInverses: function () {
  18950. this.boneInverses = [];
  18951. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  18952. var inverse = new Matrix4();
  18953. if ( this.bones[ i ] ) {
  18954. inverse.getInverse( this.bones[ i ].matrixWorld );
  18955. }
  18956. this.boneInverses.push( inverse );
  18957. }
  18958. },
  18959. pose: function () {
  18960. var bone, i, il;
  18961. // recover the bind-time world matrices
  18962. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  18963. bone = this.bones[ i ];
  18964. if ( bone ) {
  18965. bone.matrixWorld.getInverse( this.boneInverses[ i ] );
  18966. }
  18967. }
  18968. // compute the local matrices, positions, rotations and scales
  18969. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  18970. bone = this.bones[ i ];
  18971. if ( bone ) {
  18972. if ( bone.parent && bone.parent.isBone ) {
  18973. bone.matrix.getInverse( bone.parent.matrixWorld );
  18974. bone.matrix.multiply( bone.matrixWorld );
  18975. } else {
  18976. bone.matrix.copy( bone.matrixWorld );
  18977. }
  18978. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18979. }
  18980. }
  18981. },
  18982. update: ( function () {
  18983. var offsetMatrix = new Matrix4();
  18984. var identityMatrix = new Matrix4();
  18985. return function update() {
  18986. var bones = this.bones;
  18987. var boneInverses = this.boneInverses;
  18988. var boneMatrices = this.boneMatrices;
  18989. var boneTexture = this.boneTexture;
  18990. // flatten bone matrices to array
  18991. for ( var i = 0, il = bones.length; i < il; i ++ ) {
  18992. // compute the offset between the current and the original transform
  18993. var matrix = bones[ i ] ? bones[ i ].matrixWorld : identityMatrix;
  18994. offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18995. offsetMatrix.toArray( boneMatrices, i * 16 );
  18996. }
  18997. if ( boneTexture !== undefined ) {
  18998. boneTexture.needsUpdate = true;
  18999. }
  19000. };
  19001. } )(),
  19002. clone: function () {
  19003. return new Skeleton( this.bones, this.boneInverses );
  19004. },
  19005. getBoneByName: function ( name ) {
  19006. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  19007. var bone = this.bones[ i ];
  19008. if ( bone.name === name ) {
  19009. return bone;
  19010. }
  19011. }
  19012. return undefined;
  19013. }
  19014. } );
  19015. /**
  19016. * @author mikael emtinger / http://gomo.se/
  19017. * @author alteredq / http://alteredqualia.com/
  19018. * @author ikerr / http://verold.com
  19019. */
  19020. function Bone() {
  19021. Object3D.call( this );
  19022. this.type = 'Bone';
  19023. }
  19024. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19025. constructor: Bone,
  19026. isBone: true
  19027. } );
  19028. /**
  19029. * @author mikael emtinger / http://gomo.se/
  19030. * @author alteredq / http://alteredqualia.com/
  19031. * @author ikerr / http://verold.com
  19032. */
  19033. function SkinnedMesh( geometry, material ) {
  19034. Mesh.call( this, geometry, material );
  19035. this.type = 'SkinnedMesh';
  19036. this.bindMode = 'attached';
  19037. this.bindMatrix = new Matrix4();
  19038. this.bindMatrixInverse = new Matrix4();
  19039. var bones = this.initBones();
  19040. var skeleton = new Skeleton( bones );
  19041. this.bind( skeleton, this.matrixWorld );
  19042. this.normalizeSkinWeights();
  19043. }
  19044. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  19045. constructor: SkinnedMesh,
  19046. isSkinnedMesh: true,
  19047. initBones: function () {
  19048. var bones = [], bone, gbone;
  19049. var i, il;
  19050. if ( this.geometry && this.geometry.bones !== undefined ) {
  19051. // first, create array of 'Bone' objects from geometry data
  19052. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  19053. gbone = this.geometry.bones[ i ];
  19054. // create new 'Bone' object
  19055. bone = new Bone();
  19056. bones.push( bone );
  19057. // apply values
  19058. bone.name = gbone.name;
  19059. bone.position.fromArray( gbone.pos );
  19060. bone.quaternion.fromArray( gbone.rotq );
  19061. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  19062. }
  19063. // second, create bone hierarchy
  19064. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  19065. gbone = this.geometry.bones[ i ];
  19066. if ( ( gbone.parent !== - 1 ) && ( gbone.parent !== null ) && ( bones[ gbone.parent ] !== undefined ) ) {
  19067. // subsequent bones in the hierarchy
  19068. bones[ gbone.parent ].add( bones[ i ] );
  19069. } else {
  19070. // topmost bone, immediate child of the skinned mesh
  19071. this.add( bones[ i ] );
  19072. }
  19073. }
  19074. }
  19075. // now the bones are part of the scene graph and children of the skinned mesh.
  19076. // let's update the corresponding matrices
  19077. this.updateMatrixWorld( true );
  19078. return bones;
  19079. },
  19080. bind: function ( skeleton, bindMatrix ) {
  19081. this.skeleton = skeleton;
  19082. if ( bindMatrix === undefined ) {
  19083. this.updateMatrixWorld( true );
  19084. this.skeleton.calculateInverses();
  19085. bindMatrix = this.matrixWorld;
  19086. }
  19087. this.bindMatrix.copy( bindMatrix );
  19088. this.bindMatrixInverse.getInverse( bindMatrix );
  19089. },
  19090. pose: function () {
  19091. this.skeleton.pose();
  19092. },
  19093. normalizeSkinWeights: function () {
  19094. var scale, i;
  19095. if ( this.geometry && this.geometry.isGeometry ) {
  19096. for ( i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  19097. var sw = this.geometry.skinWeights[ i ];
  19098. scale = 1.0 / sw.manhattanLength();
  19099. if ( scale !== Infinity ) {
  19100. sw.multiplyScalar( scale );
  19101. } else {
  19102. sw.set( 1, 0, 0, 0 ); // do something reasonable
  19103. }
  19104. }
  19105. } else if ( this.geometry && this.geometry.isBufferGeometry ) {
  19106. var vec = new Vector4();
  19107. var skinWeight = this.geometry.attributes.skinWeight;
  19108. for ( i = 0; i < skinWeight.count; i ++ ) {
  19109. vec.x = skinWeight.getX( i );
  19110. vec.y = skinWeight.getY( i );
  19111. vec.z = skinWeight.getZ( i );
  19112. vec.w = skinWeight.getW( i );
  19113. scale = 1.0 / vec.manhattanLength();
  19114. if ( scale !== Infinity ) {
  19115. vec.multiplyScalar( scale );
  19116. } else {
  19117. vec.set( 1, 0, 0, 0 ); // do something reasonable
  19118. }
  19119. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  19120. }
  19121. }
  19122. },
  19123. updateMatrixWorld: function ( force ) {
  19124. Mesh.prototype.updateMatrixWorld.call( this, force );
  19125. if ( this.bindMode === 'attached' ) {
  19126. this.bindMatrixInverse.getInverse( this.matrixWorld );
  19127. } else if ( this.bindMode === 'detached' ) {
  19128. this.bindMatrixInverse.getInverse( this.bindMatrix );
  19129. } else {
  19130. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  19131. }
  19132. },
  19133. clone: function () {
  19134. return new this.constructor( this.geometry, this.material ).copy( this );
  19135. }
  19136. } );
  19137. /**
  19138. * @author mrdoob / http://mrdoob.com/
  19139. * @author alteredq / http://alteredqualia.com/
  19140. *
  19141. * parameters = {
  19142. * color: <hex>,
  19143. * opacity: <float>,
  19144. *
  19145. * linewidth: <float>,
  19146. * linecap: "round",
  19147. * linejoin: "round"
  19148. * }
  19149. */
  19150. function LineBasicMaterial( parameters ) {
  19151. Material.call( this );
  19152. this.type = 'LineBasicMaterial';
  19153. this.color = new Color( 0xffffff );
  19154. this.linewidth = 1;
  19155. this.linecap = 'round';
  19156. this.linejoin = 'round';
  19157. this.lights = false;
  19158. this.setValues( parameters );
  19159. }
  19160. LineBasicMaterial.prototype = Object.create( Material.prototype );
  19161. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  19162. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  19163. LineBasicMaterial.prototype.copy = function ( source ) {
  19164. Material.prototype.copy.call( this, source );
  19165. this.color.copy( source.color );
  19166. this.linewidth = source.linewidth;
  19167. this.linecap = source.linecap;
  19168. this.linejoin = source.linejoin;
  19169. return this;
  19170. };
  19171. /**
  19172. * @author mrdoob / http://mrdoob.com/
  19173. */
  19174. function Line( geometry, material, mode ) {
  19175. if ( mode === 1 ) {
  19176. console.error( 'THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.' );
  19177. }
  19178. Object3D.call( this );
  19179. this.type = 'Line';
  19180. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  19181. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  19182. }
  19183. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19184. constructor: Line,
  19185. isLine: true,
  19186. computeLineDistances: ( function () {
  19187. var start = new Vector3();
  19188. var end = new Vector3();
  19189. return function computeLineDistances() {
  19190. var geometry = this.geometry;
  19191. if ( geometry.isBufferGeometry ) {
  19192. // we assume non-indexed geometry
  19193. if ( geometry.index === null ) {
  19194. var positionAttribute = geometry.attributes.position;
  19195. var lineDistances = [ 0 ];
  19196. for ( var i = 1, l = positionAttribute.count; i < l; i ++ ) {
  19197. start.fromBufferAttribute( positionAttribute, i - 1 );
  19198. end.fromBufferAttribute( positionAttribute, i );
  19199. lineDistances[ i ] = lineDistances[ i - 1 ];
  19200. lineDistances[ i ] += start.distanceTo( end );
  19201. }
  19202. geometry.addAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  19203. } else {
  19204. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  19205. }
  19206. } else if ( geometry.isGeometry ) {
  19207. var vertices = geometry.vertices;
  19208. var lineDistances = geometry.lineDistances;
  19209. lineDistances[ 0 ] = 0;
  19210. for ( var i = 1, l = vertices.length; i < l; i ++ ) {
  19211. lineDistances[ i ] = lineDistances[ i - 1 ];
  19212. lineDistances[ i ] += vertices[ i - 1 ].distanceTo( vertices[ i ] );
  19213. }
  19214. }
  19215. return this;
  19216. };
  19217. }() ),
  19218. raycast: ( function () {
  19219. var inverseMatrix = new Matrix4();
  19220. var ray = new Ray();
  19221. var sphere = new Sphere();
  19222. return function raycast( raycaster, intersects ) {
  19223. var precision = raycaster.linePrecision;
  19224. var geometry = this.geometry;
  19225. var matrixWorld = this.matrixWorld;
  19226. // Checking boundingSphere distance to ray
  19227. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19228. sphere.copy( geometry.boundingSphere );
  19229. sphere.applyMatrix4( matrixWorld );
  19230. sphere.radius += precision;
  19231. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  19232. //
  19233. inverseMatrix.getInverse( matrixWorld );
  19234. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  19235. var localPrecision = precision / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  19236. var localPrecisionSq = localPrecision * localPrecision;
  19237. var vStart = new Vector3();
  19238. var vEnd = new Vector3();
  19239. var interSegment = new Vector3();
  19240. var interRay = new Vector3();
  19241. var step = ( this && this.isLineSegments ) ? 2 : 1;
  19242. if ( geometry.isBufferGeometry ) {
  19243. var index = geometry.index;
  19244. var attributes = geometry.attributes;
  19245. var positions = attributes.position.array;
  19246. if ( index !== null ) {
  19247. var indices = index.array;
  19248. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  19249. var a = indices[ i ];
  19250. var b = indices[ i + 1 ];
  19251. vStart.fromArray( positions, a * 3 );
  19252. vEnd.fromArray( positions, b * 3 );
  19253. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  19254. if ( distSq > localPrecisionSq ) continue;
  19255. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  19256. var distance = raycaster.ray.origin.distanceTo( interRay );
  19257. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  19258. intersects.push( {
  19259. distance: distance,
  19260. // What do we want? intersection point on the ray or on the segment??
  19261. // point: raycaster.ray.at( distance ),
  19262. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  19263. index: i,
  19264. face: null,
  19265. faceIndex: null,
  19266. object: this
  19267. } );
  19268. }
  19269. } else {
  19270. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  19271. vStart.fromArray( positions, 3 * i );
  19272. vEnd.fromArray( positions, 3 * i + 3 );
  19273. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  19274. if ( distSq > localPrecisionSq ) continue;
  19275. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  19276. var distance = raycaster.ray.origin.distanceTo( interRay );
  19277. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  19278. intersects.push( {
  19279. distance: distance,
  19280. // What do we want? intersection point on the ray or on the segment??
  19281. // point: raycaster.ray.at( distance ),
  19282. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  19283. index: i,
  19284. face: null,
  19285. faceIndex: null,
  19286. object: this
  19287. } );
  19288. }
  19289. }
  19290. } else if ( geometry.isGeometry ) {
  19291. var vertices = geometry.vertices;
  19292. var nbVertices = vertices.length;
  19293. for ( var i = 0; i < nbVertices - 1; i += step ) {
  19294. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  19295. if ( distSq > localPrecisionSq ) continue;
  19296. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  19297. var distance = raycaster.ray.origin.distanceTo( interRay );
  19298. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  19299. intersects.push( {
  19300. distance: distance,
  19301. // What do we want? intersection point on the ray or on the segment??
  19302. // point: raycaster.ray.at( distance ),
  19303. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  19304. index: i,
  19305. face: null,
  19306. faceIndex: null,
  19307. object: this
  19308. } );
  19309. }
  19310. }
  19311. };
  19312. }() ),
  19313. copy: function ( source ) {
  19314. Object3D.prototype.copy.call( this, source );
  19315. this.geometry.copy( source.geometry );
  19316. this.material.copy( source.material );
  19317. return this;
  19318. },
  19319. clone: function () {
  19320. return new this.constructor().copy( this );
  19321. }
  19322. } );
  19323. /**
  19324. * @author mrdoob / http://mrdoob.com/
  19325. */
  19326. function LineSegments( geometry, material ) {
  19327. Line.call( this, geometry, material );
  19328. this.type = 'LineSegments';
  19329. }
  19330. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  19331. constructor: LineSegments,
  19332. isLineSegments: true,
  19333. computeLineDistances: ( function () {
  19334. var start = new Vector3();
  19335. var end = new Vector3();
  19336. return function computeLineDistances() {
  19337. var geometry = this.geometry;
  19338. if ( geometry.isBufferGeometry ) {
  19339. // we assume non-indexed geometry
  19340. if ( geometry.index === null ) {
  19341. var positionAttribute = geometry.attributes.position;
  19342. var lineDistances = [];
  19343. for ( var i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  19344. start.fromBufferAttribute( positionAttribute, i );
  19345. end.fromBufferAttribute( positionAttribute, i + 1 );
  19346. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  19347. lineDistances[ i + 1 ] = lineDistances[ i ] + start.distanceTo( end );
  19348. }
  19349. geometry.addAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  19350. } else {
  19351. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  19352. }
  19353. } else if ( geometry.isGeometry ) {
  19354. var vertices = geometry.vertices;
  19355. var lineDistances = geometry.lineDistances;
  19356. for ( var i = 0, l = vertices.length; i < l; i += 2 ) {
  19357. start.copy( vertices[ i ] );
  19358. end.copy( vertices[ i + 1 ] );
  19359. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  19360. lineDistances[ i + 1 ] = lineDistances[ i ] + start.distanceTo( end );
  19361. }
  19362. }
  19363. return this;
  19364. };
  19365. }() )
  19366. } );
  19367. /**
  19368. * @author mgreter / http://github.com/mgreter
  19369. */
  19370. function LineLoop( geometry, material ) {
  19371. Line.call( this, geometry, material );
  19372. this.type = 'LineLoop';
  19373. }
  19374. LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
  19375. constructor: LineLoop,
  19376. isLineLoop: true,
  19377. } );
  19378. /**
  19379. * @author mrdoob / http://mrdoob.com/
  19380. * @author alteredq / http://alteredqualia.com/
  19381. *
  19382. * parameters = {
  19383. * color: <hex>,
  19384. * opacity: <float>,
  19385. * map: new THREE.Texture( <Image> ),
  19386. *
  19387. * size: <float>,
  19388. * sizeAttenuation: <bool>
  19389. *
  19390. * morphTargets: <bool>
  19391. * }
  19392. */
  19393. function PointsMaterial( parameters ) {
  19394. Material.call( this );
  19395. this.type = 'PointsMaterial';
  19396. this.color = new Color( 0xffffff );
  19397. this.map = null;
  19398. this.size = 1;
  19399. this.sizeAttenuation = true;
  19400. this.morphTargets = false;
  19401. this.lights = false;
  19402. this.setValues( parameters );
  19403. }
  19404. PointsMaterial.prototype = Object.create( Material.prototype );
  19405. PointsMaterial.prototype.constructor = PointsMaterial;
  19406. PointsMaterial.prototype.isPointsMaterial = true;
  19407. PointsMaterial.prototype.copy = function ( source ) {
  19408. Material.prototype.copy.call( this, source );
  19409. this.color.copy( source.color );
  19410. this.map = source.map;
  19411. this.size = source.size;
  19412. this.sizeAttenuation = source.sizeAttenuation;
  19413. this.morphTargets = source.morphTargets;
  19414. return this;
  19415. };
  19416. /**
  19417. * @author alteredq / http://alteredqualia.com/
  19418. */
  19419. function Points( geometry, material ) {
  19420. Object3D.call( this );
  19421. this.type = 'Points';
  19422. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  19423. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  19424. }
  19425. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19426. constructor: Points,
  19427. isPoints: true,
  19428. raycast: ( function () {
  19429. var inverseMatrix = new Matrix4();
  19430. var ray = new Ray();
  19431. var sphere = new Sphere();
  19432. return function raycast( raycaster, intersects ) {
  19433. var object = this;
  19434. var geometry = this.geometry;
  19435. var matrixWorld = this.matrixWorld;
  19436. var threshold = raycaster.params.Points.threshold;
  19437. // Checking boundingSphere distance to ray
  19438. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19439. sphere.copy( geometry.boundingSphere );
  19440. sphere.applyMatrix4( matrixWorld );
  19441. sphere.radius += threshold;
  19442. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  19443. //
  19444. inverseMatrix.getInverse( matrixWorld );
  19445. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  19446. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  19447. var localThresholdSq = localThreshold * localThreshold;
  19448. var position = new Vector3();
  19449. var intersectPoint = new Vector3();
  19450. function testPoint( point, index ) {
  19451. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  19452. if ( rayPointDistanceSq < localThresholdSq ) {
  19453. ray.closestPointToPoint( point, intersectPoint );
  19454. intersectPoint.applyMatrix4( matrixWorld );
  19455. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  19456. if ( distance < raycaster.near || distance > raycaster.far ) return;
  19457. intersects.push( {
  19458. distance: distance,
  19459. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  19460. point: intersectPoint.clone(),
  19461. index: index,
  19462. face: null,
  19463. object: object
  19464. } );
  19465. }
  19466. }
  19467. if ( geometry.isBufferGeometry ) {
  19468. var index = geometry.index;
  19469. var attributes = geometry.attributes;
  19470. var positions = attributes.position.array;
  19471. if ( index !== null ) {
  19472. var indices = index.array;
  19473. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  19474. var a = indices[ i ];
  19475. position.fromArray( positions, a * 3 );
  19476. testPoint( position, a );
  19477. }
  19478. } else {
  19479. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  19480. position.fromArray( positions, i * 3 );
  19481. testPoint( position, i );
  19482. }
  19483. }
  19484. } else {
  19485. var vertices = geometry.vertices;
  19486. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19487. testPoint( vertices[ i ], i );
  19488. }
  19489. }
  19490. };
  19491. }() ),
  19492. clone: function () {
  19493. return new this.constructor( this.geometry, this.material ).copy( this );
  19494. }
  19495. } );
  19496. /**
  19497. * @author mrdoob / http://mrdoob.com/
  19498. */
  19499. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  19500. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  19501. this.format = format !== undefined ? format : RGBFormat;
  19502. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  19503. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  19504. this.generateMipmaps = false;
  19505. }
  19506. VideoTexture.prototype = Object.assign( Object.create( Texture.prototype ), {
  19507. constructor: VideoTexture,
  19508. isVideoTexture: true,
  19509. update: function () {
  19510. var video = this.image;
  19511. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  19512. this.needsUpdate = true;
  19513. }
  19514. }
  19515. } );
  19516. /**
  19517. * @author alteredq / http://alteredqualia.com/
  19518. */
  19519. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  19520. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  19521. this.image = { width: width, height: height };
  19522. this.mipmaps = mipmaps;
  19523. // no flipping for cube textures
  19524. // (also flipping doesn't work for compressed textures )
  19525. this.flipY = false;
  19526. // can't generate mipmaps for compressed textures
  19527. // mips must be embedded in DDS files
  19528. this.generateMipmaps = false;
  19529. }
  19530. CompressedTexture.prototype = Object.create( Texture.prototype );
  19531. CompressedTexture.prototype.constructor = CompressedTexture;
  19532. CompressedTexture.prototype.isCompressedTexture = true;
  19533. /**
  19534. * @author mrdoob / http://mrdoob.com/
  19535. */
  19536. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  19537. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  19538. this.needsUpdate = true;
  19539. }
  19540. CanvasTexture.prototype = Object.create( Texture.prototype );
  19541. CanvasTexture.prototype.constructor = CanvasTexture;
  19542. CanvasTexture.prototype.isCanvasTexture = true;
  19543. /**
  19544. * @author Matt DesLauriers / @mattdesl
  19545. * @author atix / arthursilber.de
  19546. */
  19547. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  19548. format = format !== undefined ? format : DepthFormat;
  19549. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  19550. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  19551. }
  19552. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  19553. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  19554. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  19555. this.image = { width: width, height: height };
  19556. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  19557. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  19558. this.flipY = false;
  19559. this.generateMipmaps = false;
  19560. }
  19561. DepthTexture.prototype = Object.create( Texture.prototype );
  19562. DepthTexture.prototype.constructor = DepthTexture;
  19563. DepthTexture.prototype.isDepthTexture = true;
  19564. /**
  19565. * @author mrdoob / http://mrdoob.com/
  19566. * @author Mugen87 / https://github.com/Mugen87
  19567. */
  19568. function WireframeGeometry( geometry ) {
  19569. BufferGeometry.call( this );
  19570. this.type = 'WireframeGeometry';
  19571. // buffer
  19572. var vertices = [];
  19573. // helper variables
  19574. var i, j, l, o, ol;
  19575. var edge = [ 0, 0 ], edges = {}, e, edge1, edge2;
  19576. var key, keys = [ 'a', 'b', 'c' ];
  19577. var vertex;
  19578. // different logic for Geometry and BufferGeometry
  19579. if ( geometry && geometry.isGeometry ) {
  19580. // create a data structure that contains all edges without duplicates
  19581. var faces = geometry.faces;
  19582. for ( i = 0, l = faces.length; i < l; i ++ ) {
  19583. var face = faces[ i ];
  19584. for ( j = 0; j < 3; j ++ ) {
  19585. edge1 = face[ keys[ j ] ];
  19586. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  19587. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  19588. edge[ 1 ] = Math.max( edge1, edge2 );
  19589. key = edge[ 0 ] + ',' + edge[ 1 ];
  19590. if ( edges[ key ] === undefined ) {
  19591. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  19592. }
  19593. }
  19594. }
  19595. // generate vertices
  19596. for ( key in edges ) {
  19597. e = edges[ key ];
  19598. vertex = geometry.vertices[ e.index1 ];
  19599. vertices.push( vertex.x, vertex.y, vertex.z );
  19600. vertex = geometry.vertices[ e.index2 ];
  19601. vertices.push( vertex.x, vertex.y, vertex.z );
  19602. }
  19603. } else if ( geometry && geometry.isBufferGeometry ) {
  19604. var position, indices, groups;
  19605. var group, start, count;
  19606. var index1, index2;
  19607. vertex = new Vector3();
  19608. if ( geometry.index !== null ) {
  19609. // indexed BufferGeometry
  19610. position = geometry.attributes.position;
  19611. indices = geometry.index;
  19612. groups = geometry.groups;
  19613. if ( groups.length === 0 ) {
  19614. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  19615. }
  19616. // create a data structure that contains all eges without duplicates
  19617. for ( o = 0, ol = groups.length; o < ol; ++ o ) {
  19618. group = groups[ o ];
  19619. start = group.start;
  19620. count = group.count;
  19621. for ( i = start, l = ( start + count ); i < l; i += 3 ) {
  19622. for ( j = 0; j < 3; j ++ ) {
  19623. edge1 = indices.getX( i + j );
  19624. edge2 = indices.getX( i + ( j + 1 ) % 3 );
  19625. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  19626. edge[ 1 ] = Math.max( edge1, edge2 );
  19627. key = edge[ 0 ] + ',' + edge[ 1 ];
  19628. if ( edges[ key ] === undefined ) {
  19629. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  19630. }
  19631. }
  19632. }
  19633. }
  19634. // generate vertices
  19635. for ( key in edges ) {
  19636. e = edges[ key ];
  19637. vertex.fromBufferAttribute( position, e.index1 );
  19638. vertices.push( vertex.x, vertex.y, vertex.z );
  19639. vertex.fromBufferAttribute( position, e.index2 );
  19640. vertices.push( vertex.x, vertex.y, vertex.z );
  19641. }
  19642. } else {
  19643. // non-indexed BufferGeometry
  19644. position = geometry.attributes.position;
  19645. for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  19646. for ( j = 0; j < 3; j ++ ) {
  19647. // three edges per triangle, an edge is represented as (index1, index2)
  19648. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  19649. index1 = 3 * i + j;
  19650. vertex.fromBufferAttribute( position, index1 );
  19651. vertices.push( vertex.x, vertex.y, vertex.z );
  19652. index2 = 3 * i + ( ( j + 1 ) % 3 );
  19653. vertex.fromBufferAttribute( position, index2 );
  19654. vertices.push( vertex.x, vertex.y, vertex.z );
  19655. }
  19656. }
  19657. }
  19658. }
  19659. // build geometry
  19660. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19661. }
  19662. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  19663. WireframeGeometry.prototype.constructor = WireframeGeometry;
  19664. /**
  19665. * @author zz85 / https://github.com/zz85
  19666. * @author Mugen87 / https://github.com/Mugen87
  19667. *
  19668. * Parametric Surfaces Geometry
  19669. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19670. */
  19671. // ParametricGeometry
  19672. function ParametricGeometry( func, slices, stacks ) {
  19673. Geometry.call( this );
  19674. this.type = 'ParametricGeometry';
  19675. this.parameters = {
  19676. func: func,
  19677. slices: slices,
  19678. stacks: stacks
  19679. };
  19680. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  19681. this.mergeVertices();
  19682. }
  19683. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  19684. ParametricGeometry.prototype.constructor = ParametricGeometry;
  19685. // ParametricBufferGeometry
  19686. function ParametricBufferGeometry( func, slices, stacks ) {
  19687. BufferGeometry.call( this );
  19688. this.type = 'ParametricBufferGeometry';
  19689. this.parameters = {
  19690. func: func,
  19691. slices: slices,
  19692. stacks: stacks
  19693. };
  19694. // buffers
  19695. var indices = [];
  19696. var vertices = [];
  19697. var normals = [];
  19698. var uvs = [];
  19699. var EPS = 0.00001;
  19700. var normal = new Vector3();
  19701. var p0 = new Vector3(), p1 = new Vector3();
  19702. var pu = new Vector3(), pv = new Vector3();
  19703. var i, j;
  19704. if ( func.length < 3 ) {
  19705. console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' );
  19706. }
  19707. // generate vertices, normals and uvs
  19708. var sliceCount = slices + 1;
  19709. for ( i = 0; i <= stacks; i ++ ) {
  19710. var v = i / stacks;
  19711. for ( j = 0; j <= slices; j ++ ) {
  19712. var u = j / slices;
  19713. // vertex
  19714. func( u, v, p0 );
  19715. vertices.push( p0.x, p0.y, p0.z );
  19716. // normal
  19717. // approximate tangent vectors via finite differences
  19718. if ( u - EPS >= 0 ) {
  19719. func( u - EPS, v, p1 );
  19720. pu.subVectors( p0, p1 );
  19721. } else {
  19722. func( u + EPS, v, p1 );
  19723. pu.subVectors( p1, p0 );
  19724. }
  19725. if ( v - EPS >= 0 ) {
  19726. func( u, v - EPS, p1 );
  19727. pv.subVectors( p0, p1 );
  19728. } else {
  19729. func( u, v + EPS, p1 );
  19730. pv.subVectors( p1, p0 );
  19731. }
  19732. // cross product of tangent vectors returns surface normal
  19733. normal.crossVectors( pu, pv ).normalize();
  19734. normals.push( normal.x, normal.y, normal.z );
  19735. // uv
  19736. uvs.push( u, v );
  19737. }
  19738. }
  19739. // generate indices
  19740. for ( i = 0; i < stacks; i ++ ) {
  19741. for ( j = 0; j < slices; j ++ ) {
  19742. var a = i * sliceCount + j;
  19743. var b = i * sliceCount + j + 1;
  19744. var c = ( i + 1 ) * sliceCount + j + 1;
  19745. var d = ( i + 1 ) * sliceCount + j;
  19746. // faces one and two
  19747. indices.push( a, b, d );
  19748. indices.push( b, c, d );
  19749. }
  19750. }
  19751. // build geometry
  19752. this.setIndex( indices );
  19753. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19754. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19755. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19756. }
  19757. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19758. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  19759. /**
  19760. * @author clockworkgeek / https://github.com/clockworkgeek
  19761. * @author timothypratley / https://github.com/timothypratley
  19762. * @author WestLangley / http://github.com/WestLangley
  19763. * @author Mugen87 / https://github.com/Mugen87
  19764. */
  19765. // PolyhedronGeometry
  19766. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  19767. Geometry.call( this );
  19768. this.type = 'PolyhedronGeometry';
  19769. this.parameters = {
  19770. vertices: vertices,
  19771. indices: indices,
  19772. radius: radius,
  19773. detail: detail
  19774. };
  19775. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  19776. this.mergeVertices();
  19777. }
  19778. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  19779. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  19780. // PolyhedronBufferGeometry
  19781. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  19782. BufferGeometry.call( this );
  19783. this.type = 'PolyhedronBufferGeometry';
  19784. this.parameters = {
  19785. vertices: vertices,
  19786. indices: indices,
  19787. radius: radius,
  19788. detail: detail
  19789. };
  19790. radius = radius || 1;
  19791. detail = detail || 0;
  19792. // default buffer data
  19793. var vertexBuffer = [];
  19794. var uvBuffer = [];
  19795. // the subdivision creates the vertex buffer data
  19796. subdivide( detail );
  19797. // all vertices should lie on a conceptual sphere with a given radius
  19798. appplyRadius( radius );
  19799. // finally, create the uv data
  19800. generateUVs();
  19801. // build non-indexed geometry
  19802. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  19803. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  19804. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  19805. if ( detail === 0 ) {
  19806. this.computeVertexNormals(); // flat normals
  19807. } else {
  19808. this.normalizeNormals(); // smooth normals
  19809. }
  19810. // helper functions
  19811. function subdivide( detail ) {
  19812. var a = new Vector3();
  19813. var b = new Vector3();
  19814. var c = new Vector3();
  19815. // iterate over all faces and apply a subdivison with the given detail value
  19816. for ( var i = 0; i < indices.length; i += 3 ) {
  19817. // get the vertices of the face
  19818. getVertexByIndex( indices[ i + 0 ], a );
  19819. getVertexByIndex( indices[ i + 1 ], b );
  19820. getVertexByIndex( indices[ i + 2 ], c );
  19821. // perform subdivision
  19822. subdivideFace( a, b, c, detail );
  19823. }
  19824. }
  19825. function subdivideFace( a, b, c, detail ) {
  19826. var cols = Math.pow( 2, detail );
  19827. // we use this multidimensional array as a data structure for creating the subdivision
  19828. var v = [];
  19829. var i, j;
  19830. // construct all of the vertices for this subdivision
  19831. for ( i = 0; i <= cols; i ++ ) {
  19832. v[ i ] = [];
  19833. var aj = a.clone().lerp( c, i / cols );
  19834. var bj = b.clone().lerp( c, i / cols );
  19835. var rows = cols - i;
  19836. for ( j = 0; j <= rows; j ++ ) {
  19837. if ( j === 0 && i === cols ) {
  19838. v[ i ][ j ] = aj;
  19839. } else {
  19840. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  19841. }
  19842. }
  19843. }
  19844. // construct all of the faces
  19845. for ( i = 0; i < cols; i ++ ) {
  19846. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  19847. var k = Math.floor( j / 2 );
  19848. if ( j % 2 === 0 ) {
  19849. pushVertex( v[ i ][ k + 1 ] );
  19850. pushVertex( v[ i + 1 ][ k ] );
  19851. pushVertex( v[ i ][ k ] );
  19852. } else {
  19853. pushVertex( v[ i ][ k + 1 ] );
  19854. pushVertex( v[ i + 1 ][ k + 1 ] );
  19855. pushVertex( v[ i + 1 ][ k ] );
  19856. }
  19857. }
  19858. }
  19859. }
  19860. function appplyRadius( radius ) {
  19861. var vertex = new Vector3();
  19862. // iterate over the entire buffer and apply the radius to each vertex
  19863. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  19864. vertex.x = vertexBuffer[ i + 0 ];
  19865. vertex.y = vertexBuffer[ i + 1 ];
  19866. vertex.z = vertexBuffer[ i + 2 ];
  19867. vertex.normalize().multiplyScalar( radius );
  19868. vertexBuffer[ i + 0 ] = vertex.x;
  19869. vertexBuffer[ i + 1 ] = vertex.y;
  19870. vertexBuffer[ i + 2 ] = vertex.z;
  19871. }
  19872. }
  19873. function generateUVs() {
  19874. var vertex = new Vector3();
  19875. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  19876. vertex.x = vertexBuffer[ i + 0 ];
  19877. vertex.y = vertexBuffer[ i + 1 ];
  19878. vertex.z = vertexBuffer[ i + 2 ];
  19879. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  19880. var v = inclination( vertex ) / Math.PI + 0.5;
  19881. uvBuffer.push( u, 1 - v );
  19882. }
  19883. correctUVs();
  19884. correctSeam();
  19885. }
  19886. function correctSeam() {
  19887. // handle case when face straddles the seam, see #3269
  19888. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  19889. // uv data of a single face
  19890. var x0 = uvBuffer[ i + 0 ];
  19891. var x1 = uvBuffer[ i + 2 ];
  19892. var x2 = uvBuffer[ i + 4 ];
  19893. var max = Math.max( x0, x1, x2 );
  19894. var min = Math.min( x0, x1, x2 );
  19895. // 0.9 is somewhat arbitrary
  19896. if ( max > 0.9 && min < 0.1 ) {
  19897. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  19898. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  19899. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  19900. }
  19901. }
  19902. }
  19903. function pushVertex( vertex ) {
  19904. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  19905. }
  19906. function getVertexByIndex( index, vertex ) {
  19907. var stride = index * 3;
  19908. vertex.x = vertices[ stride + 0 ];
  19909. vertex.y = vertices[ stride + 1 ];
  19910. vertex.z = vertices[ stride + 2 ];
  19911. }
  19912. function correctUVs() {
  19913. var a = new Vector3();
  19914. var b = new Vector3();
  19915. var c = new Vector3();
  19916. var centroid = new Vector3();
  19917. var uvA = new Vector2();
  19918. var uvB = new Vector2();
  19919. var uvC = new Vector2();
  19920. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  19921. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  19922. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  19923. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  19924. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  19925. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  19926. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  19927. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  19928. var azi = azimuth( centroid );
  19929. correctUV( uvA, j + 0, a, azi );
  19930. correctUV( uvB, j + 2, b, azi );
  19931. correctUV( uvC, j + 4, c, azi );
  19932. }
  19933. }
  19934. function correctUV( uv, stride, vector, azimuth ) {
  19935. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  19936. uvBuffer[ stride ] = uv.x - 1;
  19937. }
  19938. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  19939. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  19940. }
  19941. }
  19942. // Angle around the Y axis, counter-clockwise when looking from above.
  19943. function azimuth( vector ) {
  19944. return Math.atan2( vector.z, - vector.x );
  19945. }
  19946. // Angle above the XZ plane.
  19947. function inclination( vector ) {
  19948. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19949. }
  19950. }
  19951. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19952. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  19953. /**
  19954. * @author timothypratley / https://github.com/timothypratley
  19955. * @author Mugen87 / https://github.com/Mugen87
  19956. */
  19957. // TetrahedronGeometry
  19958. function TetrahedronGeometry( radius, detail ) {
  19959. Geometry.call( this );
  19960. this.type = 'TetrahedronGeometry';
  19961. this.parameters = {
  19962. radius: radius,
  19963. detail: detail
  19964. };
  19965. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  19966. this.mergeVertices();
  19967. }
  19968. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  19969. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  19970. // TetrahedronBufferGeometry
  19971. function TetrahedronBufferGeometry( radius, detail ) {
  19972. var vertices = [
  19973. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  19974. ];
  19975. var indices = [
  19976. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  19977. ];
  19978. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  19979. this.type = 'TetrahedronBufferGeometry';
  19980. this.parameters = {
  19981. radius: radius,
  19982. detail: detail
  19983. };
  19984. }
  19985. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  19986. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  19987. /**
  19988. * @author timothypratley / https://github.com/timothypratley
  19989. * @author Mugen87 / https://github.com/Mugen87
  19990. */
  19991. // OctahedronGeometry
  19992. function OctahedronGeometry( radius, detail ) {
  19993. Geometry.call( this );
  19994. this.type = 'OctahedronGeometry';
  19995. this.parameters = {
  19996. radius: radius,
  19997. detail: detail
  19998. };
  19999. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  20000. this.mergeVertices();
  20001. }
  20002. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  20003. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  20004. // OctahedronBufferGeometry
  20005. function OctahedronBufferGeometry( radius, detail ) {
  20006. var vertices = [
  20007. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  20008. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  20009. ];
  20010. var indices = [
  20011. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  20012. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  20013. 1, 3, 4, 1, 4, 2
  20014. ];
  20015. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  20016. this.type = 'OctahedronBufferGeometry';
  20017. this.parameters = {
  20018. radius: radius,
  20019. detail: detail
  20020. };
  20021. }
  20022. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  20023. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  20024. /**
  20025. * @author timothypratley / https://github.com/timothypratley
  20026. * @author Mugen87 / https://github.com/Mugen87
  20027. */
  20028. // IcosahedronGeometry
  20029. function IcosahedronGeometry( radius, detail ) {
  20030. Geometry.call( this );
  20031. this.type = 'IcosahedronGeometry';
  20032. this.parameters = {
  20033. radius: radius,
  20034. detail: detail
  20035. };
  20036. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  20037. this.mergeVertices();
  20038. }
  20039. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  20040. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  20041. // IcosahedronBufferGeometry
  20042. function IcosahedronBufferGeometry( radius, detail ) {
  20043. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20044. var vertices = [
  20045. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  20046. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  20047. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  20048. ];
  20049. var indices = [
  20050. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  20051. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  20052. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  20053. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  20054. ];
  20055. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  20056. this.type = 'IcosahedronBufferGeometry';
  20057. this.parameters = {
  20058. radius: radius,
  20059. detail: detail
  20060. };
  20061. }
  20062. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  20063. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  20064. /**
  20065. * @author Abe Pazos / https://hamoid.com
  20066. * @author Mugen87 / https://github.com/Mugen87
  20067. */
  20068. // DodecahedronGeometry
  20069. function DodecahedronGeometry( radius, detail ) {
  20070. Geometry.call( this );
  20071. this.type = 'DodecahedronGeometry';
  20072. this.parameters = {
  20073. radius: radius,
  20074. detail: detail
  20075. };
  20076. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  20077. this.mergeVertices();
  20078. }
  20079. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  20080. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  20081. // DodecahedronBufferGeometry
  20082. function DodecahedronBufferGeometry( radius, detail ) {
  20083. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20084. var r = 1 / t;
  20085. var vertices = [
  20086. // (±1, ±1, ±1)
  20087. - 1, - 1, - 1, - 1, - 1, 1,
  20088. - 1, 1, - 1, - 1, 1, 1,
  20089. 1, - 1, - 1, 1, - 1, 1,
  20090. 1, 1, - 1, 1, 1, 1,
  20091. // (0, ±1/φ, ±φ)
  20092. 0, - r, - t, 0, - r, t,
  20093. 0, r, - t, 0, r, t,
  20094. // (±1/φ, ±φ, 0)
  20095. - r, - t, 0, - r, t, 0,
  20096. r, - t, 0, r, t, 0,
  20097. // (±φ, 0, ±1/φ)
  20098. - t, 0, - r, t, 0, - r,
  20099. - t, 0, r, t, 0, r
  20100. ];
  20101. var indices = [
  20102. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  20103. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  20104. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  20105. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  20106. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  20107. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  20108. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  20109. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  20110. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  20111. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  20112. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  20113. 1, 12, 14, 1, 14, 5, 1, 5, 9
  20114. ];
  20115. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  20116. this.type = 'DodecahedronBufferGeometry';
  20117. this.parameters = {
  20118. radius: radius,
  20119. detail: detail
  20120. };
  20121. }
  20122. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  20123. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  20124. /**
  20125. * @author oosmoxiecode / https://github.com/oosmoxiecode
  20126. * @author WestLangley / https://github.com/WestLangley
  20127. * @author zz85 / https://github.com/zz85
  20128. * @author miningold / https://github.com/miningold
  20129. * @author jonobr1 / https://github.com/jonobr1
  20130. * @author Mugen87 / https://github.com/Mugen87
  20131. *
  20132. */
  20133. // TubeGeometry
  20134. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  20135. Geometry.call( this );
  20136. this.type = 'TubeGeometry';
  20137. this.parameters = {
  20138. path: path,
  20139. tubularSegments: tubularSegments,
  20140. radius: radius,
  20141. radialSegments: radialSegments,
  20142. closed: closed
  20143. };
  20144. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  20145. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  20146. // expose internals
  20147. this.tangents = bufferGeometry.tangents;
  20148. this.normals = bufferGeometry.normals;
  20149. this.binormals = bufferGeometry.binormals;
  20150. // create geometry
  20151. this.fromBufferGeometry( bufferGeometry );
  20152. this.mergeVertices();
  20153. }
  20154. TubeGeometry.prototype = Object.create( Geometry.prototype );
  20155. TubeGeometry.prototype.constructor = TubeGeometry;
  20156. // TubeBufferGeometry
  20157. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  20158. BufferGeometry.call( this );
  20159. this.type = 'TubeBufferGeometry';
  20160. this.parameters = {
  20161. path: path,
  20162. tubularSegments: tubularSegments,
  20163. radius: radius,
  20164. radialSegments: radialSegments,
  20165. closed: closed
  20166. };
  20167. tubularSegments = tubularSegments || 64;
  20168. radius = radius || 1;
  20169. radialSegments = radialSegments || 8;
  20170. closed = closed || false;
  20171. var frames = path.computeFrenetFrames( tubularSegments, closed );
  20172. // expose internals
  20173. this.tangents = frames.tangents;
  20174. this.normals = frames.normals;
  20175. this.binormals = frames.binormals;
  20176. // helper variables
  20177. var vertex = new Vector3();
  20178. var normal = new Vector3();
  20179. var uv = new Vector2();
  20180. var P = new Vector3();
  20181. var i, j;
  20182. // buffer
  20183. var vertices = [];
  20184. var normals = [];
  20185. var uvs = [];
  20186. var indices = [];
  20187. // create buffer data
  20188. generateBufferData();
  20189. // build geometry
  20190. this.setIndex( indices );
  20191. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20192. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20193. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20194. // functions
  20195. function generateBufferData() {
  20196. for ( i = 0; i < tubularSegments; i ++ ) {
  20197. generateSegment( i );
  20198. }
  20199. // if the geometry is not closed, generate the last row of vertices and normals
  20200. // at the regular position on the given path
  20201. //
  20202. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  20203. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  20204. // uvs are generated in a separate function.
  20205. // this makes it easy compute correct values for closed geometries
  20206. generateUVs();
  20207. // finally create faces
  20208. generateIndices();
  20209. }
  20210. function generateSegment( i ) {
  20211. // we use getPointAt to sample evenly distributed points from the given path
  20212. P = path.getPointAt( i / tubularSegments, P );
  20213. // retrieve corresponding normal and binormal
  20214. var N = frames.normals[ i ];
  20215. var B = frames.binormals[ i ];
  20216. // generate normals and vertices for the current segment
  20217. for ( j = 0; j <= radialSegments; j ++ ) {
  20218. var v = j / radialSegments * Math.PI * 2;
  20219. var sin = Math.sin( v );
  20220. var cos = - Math.cos( v );
  20221. // normal
  20222. normal.x = ( cos * N.x + sin * B.x );
  20223. normal.y = ( cos * N.y + sin * B.y );
  20224. normal.z = ( cos * N.z + sin * B.z );
  20225. normal.normalize();
  20226. normals.push( normal.x, normal.y, normal.z );
  20227. // vertex
  20228. vertex.x = P.x + radius * normal.x;
  20229. vertex.y = P.y + radius * normal.y;
  20230. vertex.z = P.z + radius * normal.z;
  20231. vertices.push( vertex.x, vertex.y, vertex.z );
  20232. }
  20233. }
  20234. function generateIndices() {
  20235. for ( j = 1; j <= tubularSegments; j ++ ) {
  20236. for ( i = 1; i <= radialSegments; i ++ ) {
  20237. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  20238. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  20239. var c = ( radialSegments + 1 ) * j + i;
  20240. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  20241. // faces
  20242. indices.push( a, b, d );
  20243. indices.push( b, c, d );
  20244. }
  20245. }
  20246. }
  20247. function generateUVs() {
  20248. for ( i = 0; i <= tubularSegments; i ++ ) {
  20249. for ( j = 0; j <= radialSegments; j ++ ) {
  20250. uv.x = i / tubularSegments;
  20251. uv.y = j / radialSegments;
  20252. uvs.push( uv.x, uv.y );
  20253. }
  20254. }
  20255. }
  20256. }
  20257. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20258. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  20259. /**
  20260. * @author oosmoxiecode
  20261. * @author Mugen87 / https://github.com/Mugen87
  20262. *
  20263. * based on http://www.blackpawn.com/texts/pqtorus/
  20264. */
  20265. // TorusKnotGeometry
  20266. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  20267. Geometry.call( this );
  20268. this.type = 'TorusKnotGeometry';
  20269. this.parameters = {
  20270. radius: radius,
  20271. tube: tube,
  20272. tubularSegments: tubularSegments,
  20273. radialSegments: radialSegments,
  20274. p: p,
  20275. q: q
  20276. };
  20277. if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  20278. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  20279. this.mergeVertices();
  20280. }
  20281. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  20282. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  20283. // TorusKnotBufferGeometry
  20284. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  20285. BufferGeometry.call( this );
  20286. this.type = 'TorusKnotBufferGeometry';
  20287. this.parameters = {
  20288. radius: radius,
  20289. tube: tube,
  20290. tubularSegments: tubularSegments,
  20291. radialSegments: radialSegments,
  20292. p: p,
  20293. q: q
  20294. };
  20295. radius = radius || 1;
  20296. tube = tube || 0.4;
  20297. tubularSegments = Math.floor( tubularSegments ) || 64;
  20298. radialSegments = Math.floor( radialSegments ) || 8;
  20299. p = p || 2;
  20300. q = q || 3;
  20301. // buffers
  20302. var indices = [];
  20303. var vertices = [];
  20304. var normals = [];
  20305. var uvs = [];
  20306. // helper variables
  20307. var i, j;
  20308. var vertex = new Vector3();
  20309. var normal = new Vector3();
  20310. var P1 = new Vector3();
  20311. var P2 = new Vector3();
  20312. var B = new Vector3();
  20313. var T = new Vector3();
  20314. var N = new Vector3();
  20315. // generate vertices, normals and uvs
  20316. for ( i = 0; i <= tubularSegments; ++ i ) {
  20317. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  20318. var u = i / tubularSegments * p * Math.PI * 2;
  20319. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  20320. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  20321. calculatePositionOnCurve( u, p, q, radius, P1 );
  20322. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  20323. // calculate orthonormal basis
  20324. T.subVectors( P2, P1 );
  20325. N.addVectors( P2, P1 );
  20326. B.crossVectors( T, N );
  20327. N.crossVectors( B, T );
  20328. // normalize B, N. T can be ignored, we don't use it
  20329. B.normalize();
  20330. N.normalize();
  20331. for ( j = 0; j <= radialSegments; ++ j ) {
  20332. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  20333. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  20334. var v = j / radialSegments * Math.PI * 2;
  20335. var cx = - tube * Math.cos( v );
  20336. var cy = tube * Math.sin( v );
  20337. // now calculate the final vertex position.
  20338. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  20339. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  20340. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  20341. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  20342. vertices.push( vertex.x, vertex.y, vertex.z );
  20343. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  20344. normal.subVectors( vertex, P1 ).normalize();
  20345. normals.push( normal.x, normal.y, normal.z );
  20346. // uv
  20347. uvs.push( i / tubularSegments );
  20348. uvs.push( j / radialSegments );
  20349. }
  20350. }
  20351. // generate indices
  20352. for ( j = 1; j <= tubularSegments; j ++ ) {
  20353. for ( i = 1; i <= radialSegments; i ++ ) {
  20354. // indices
  20355. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  20356. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  20357. var c = ( radialSegments + 1 ) * j + i;
  20358. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  20359. // faces
  20360. indices.push( a, b, d );
  20361. indices.push( b, c, d );
  20362. }
  20363. }
  20364. // build geometry
  20365. this.setIndex( indices );
  20366. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20367. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20368. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20369. // this function calculates the current position on the torus curve
  20370. function calculatePositionOnCurve( u, p, q, radius, position ) {
  20371. var cu = Math.cos( u );
  20372. var su = Math.sin( u );
  20373. var quOverP = q / p * u;
  20374. var cs = Math.cos( quOverP );
  20375. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  20376. position.y = radius * ( 2 + cs ) * su * 0.5;
  20377. position.z = radius * Math.sin( quOverP ) * 0.5;
  20378. }
  20379. }
  20380. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20381. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  20382. /**
  20383. * @author oosmoxiecode
  20384. * @author mrdoob / http://mrdoob.com/
  20385. * @author Mugen87 / https://github.com/Mugen87
  20386. */
  20387. // TorusGeometry
  20388. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  20389. Geometry.call( this );
  20390. this.type = 'TorusGeometry';
  20391. this.parameters = {
  20392. radius: radius,
  20393. tube: tube,
  20394. radialSegments: radialSegments,
  20395. tubularSegments: tubularSegments,
  20396. arc: arc
  20397. };
  20398. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  20399. this.mergeVertices();
  20400. }
  20401. TorusGeometry.prototype = Object.create( Geometry.prototype );
  20402. TorusGeometry.prototype.constructor = TorusGeometry;
  20403. // TorusBufferGeometry
  20404. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  20405. BufferGeometry.call( this );
  20406. this.type = 'TorusBufferGeometry';
  20407. this.parameters = {
  20408. radius: radius,
  20409. tube: tube,
  20410. radialSegments: radialSegments,
  20411. tubularSegments: tubularSegments,
  20412. arc: arc
  20413. };
  20414. radius = radius || 1;
  20415. tube = tube || 0.4;
  20416. radialSegments = Math.floor( radialSegments ) || 8;
  20417. tubularSegments = Math.floor( tubularSegments ) || 6;
  20418. arc = arc || Math.PI * 2;
  20419. // buffers
  20420. var indices = [];
  20421. var vertices = [];
  20422. var normals = [];
  20423. var uvs = [];
  20424. // helper variables
  20425. var center = new Vector3();
  20426. var vertex = new Vector3();
  20427. var normal = new Vector3();
  20428. var j, i;
  20429. // generate vertices, normals and uvs
  20430. for ( j = 0; j <= radialSegments; j ++ ) {
  20431. for ( i = 0; i <= tubularSegments; i ++ ) {
  20432. var u = i / tubularSegments * arc;
  20433. var v = j / radialSegments * Math.PI * 2;
  20434. // vertex
  20435. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  20436. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  20437. vertex.z = tube * Math.sin( v );
  20438. vertices.push( vertex.x, vertex.y, vertex.z );
  20439. // normal
  20440. center.x = radius * Math.cos( u );
  20441. center.y = radius * Math.sin( u );
  20442. normal.subVectors( vertex, center ).normalize();
  20443. normals.push( normal.x, normal.y, normal.z );
  20444. // uv
  20445. uvs.push( i / tubularSegments );
  20446. uvs.push( j / radialSegments );
  20447. }
  20448. }
  20449. // generate indices
  20450. for ( j = 1; j <= radialSegments; j ++ ) {
  20451. for ( i = 1; i <= tubularSegments; i ++ ) {
  20452. // indices
  20453. var a = ( tubularSegments + 1 ) * j + i - 1;
  20454. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20455. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  20456. var d = ( tubularSegments + 1 ) * j + i;
  20457. // faces
  20458. indices.push( a, b, d );
  20459. indices.push( b, c, d );
  20460. }
  20461. }
  20462. // build geometry
  20463. this.setIndex( indices );
  20464. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20465. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20466. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20467. }
  20468. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20469. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  20470. /**
  20471. * @author Mugen87 / https://github.com/Mugen87
  20472. * Port from https://github.com/mapbox/earcut (v2.1.2)
  20473. */
  20474. var Earcut = {
  20475. triangulate: function ( data, holeIndices, dim ) {
  20476. dim = dim || 2;
  20477. var hasHoles = holeIndices && holeIndices.length,
  20478. outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length,
  20479. outerNode = linkedList( data, 0, outerLen, dim, true ),
  20480. triangles = [];
  20481. if ( ! outerNode ) return triangles;
  20482. var minX, minY, maxX, maxY, x, y, invSize;
  20483. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  20484. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  20485. if ( data.length > 80 * dim ) {
  20486. minX = maxX = data[ 0 ];
  20487. minY = maxY = data[ 1 ];
  20488. for ( var i = dim; i < outerLen; i += dim ) {
  20489. x = data[ i ];
  20490. y = data[ i + 1 ];
  20491. if ( x < minX ) minX = x;
  20492. if ( y < minY ) minY = y;
  20493. if ( x > maxX ) maxX = x;
  20494. if ( y > maxY ) maxY = y;
  20495. }
  20496. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20497. invSize = Math.max( maxX - minX, maxY - minY );
  20498. invSize = invSize !== 0 ? 1 / invSize : 0;
  20499. }
  20500. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  20501. return triangles;
  20502. }
  20503. };
  20504. // create a circular doubly linked list from polygon points in the specified winding order
  20505. function linkedList( data, start, end, dim, clockwise ) {
  20506. var i, last;
  20507. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  20508. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20509. } else {
  20510. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20511. }
  20512. if ( last && equals( last, last.next ) ) {
  20513. removeNode( last );
  20514. last = last.next;
  20515. }
  20516. return last;
  20517. }
  20518. // eliminate colinear or duplicate points
  20519. function filterPoints( start, end ) {
  20520. if ( ! start ) return start;
  20521. if ( ! end ) end = start;
  20522. var p = start, again;
  20523. do {
  20524. again = false;
  20525. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  20526. removeNode( p );
  20527. p = end = p.prev;
  20528. if ( p === p.next ) break;
  20529. again = true;
  20530. } else {
  20531. p = p.next;
  20532. }
  20533. } while ( again || p !== end );
  20534. return end;
  20535. }
  20536. // main ear slicing loop which triangulates a polygon (given as a linked list)
  20537. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  20538. if ( ! ear ) return;
  20539. // interlink polygon nodes in z-order
  20540. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  20541. var stop = ear, prev, next;
  20542. // iterate through ears, slicing them one by one
  20543. while ( ear.prev !== ear.next ) {
  20544. prev = ear.prev;
  20545. next = ear.next;
  20546. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  20547. // cut off the triangle
  20548. triangles.push( prev.i / dim );
  20549. triangles.push( ear.i / dim );
  20550. triangles.push( next.i / dim );
  20551. removeNode( ear );
  20552. // skipping the next vertice leads to less sliver triangles
  20553. ear = next.next;
  20554. stop = next.next;
  20555. continue;
  20556. }
  20557. ear = next;
  20558. // if we looped through the whole remaining polygon and can't find any more ears
  20559. if ( ear === stop ) {
  20560. // try filtering points and slicing again
  20561. if ( ! pass ) {
  20562. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  20563. // if this didn't work, try curing all small self-intersections locally
  20564. } else if ( pass === 1 ) {
  20565. ear = cureLocalIntersections( ear, triangles, dim );
  20566. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  20567. // as a last resort, try splitting the remaining polygon into two
  20568. } else if ( pass === 2 ) {
  20569. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  20570. }
  20571. break;
  20572. }
  20573. }
  20574. }
  20575. // check whether a polygon node forms a valid ear with adjacent nodes
  20576. function isEar( ear ) {
  20577. var a = ear.prev,
  20578. b = ear,
  20579. c = ear.next;
  20580. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20581. // now make sure we don't have other points inside the potential ear
  20582. var p = ear.next.next;
  20583. while ( p !== ear.prev ) {
  20584. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) {
  20585. return false;
  20586. }
  20587. p = p.next;
  20588. }
  20589. return true;
  20590. }
  20591. function isEarHashed( ear, minX, minY, invSize ) {
  20592. var a = ear.prev,
  20593. b = ear,
  20594. c = ear.next;
  20595. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20596. // triangle bbox; min & max are calculated like this for speed
  20597. var minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  20598. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  20599. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  20600. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  20601. // z-order range for the current triangle bbox;
  20602. var minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  20603. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  20604. // first look for points inside the triangle in increasing z-order
  20605. var p = ear.nextZ;
  20606. while ( p && p.z <= maxZ ) {
  20607. if ( p !== ear.prev && p !== ear.next &&
  20608. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20609. area( p.prev, p, p.next ) >= 0 ) return false;
  20610. p = p.nextZ;
  20611. }
  20612. // then look for points in decreasing z-order
  20613. p = ear.prevZ;
  20614. while ( p && p.z >= minZ ) {
  20615. if ( p !== ear.prev && p !== ear.next &&
  20616. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20617. area( p.prev, p, p.next ) >= 0 ) return false;
  20618. p = p.prevZ;
  20619. }
  20620. return true;
  20621. }
  20622. // go through all polygon nodes and cure small local self-intersections
  20623. function cureLocalIntersections( start, triangles, dim ) {
  20624. var p = start;
  20625. do {
  20626. var a = p.prev, b = p.next.next;
  20627. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  20628. triangles.push( a.i / dim );
  20629. triangles.push( p.i / dim );
  20630. triangles.push( b.i / dim );
  20631. // remove two nodes involved
  20632. removeNode( p );
  20633. removeNode( p.next );
  20634. p = start = b;
  20635. }
  20636. p = p.next;
  20637. } while ( p !== start );
  20638. return p;
  20639. }
  20640. // try splitting polygon into two and triangulate them independently
  20641. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  20642. // look for a valid diagonal that divides the polygon into two
  20643. var a = start;
  20644. do {
  20645. var b = a.next.next;
  20646. while ( b !== a.prev ) {
  20647. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  20648. // split the polygon in two by the diagonal
  20649. var c = splitPolygon( a, b );
  20650. // filter colinear points around the cuts
  20651. a = filterPoints( a, a.next );
  20652. c = filterPoints( c, c.next );
  20653. // run earcut on each half
  20654. earcutLinked( a, triangles, dim, minX, minY, invSize );
  20655. earcutLinked( c, triangles, dim, minX, minY, invSize );
  20656. return;
  20657. }
  20658. b = b.next;
  20659. }
  20660. a = a.next;
  20661. } while ( a !== start );
  20662. }
  20663. // link every hole into the outer loop, producing a single-ring polygon without holes
  20664. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  20665. var queue = [], i, len, start, end, list;
  20666. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  20667. start = holeIndices[ i ] * dim;
  20668. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  20669. list = linkedList( data, start, end, dim, false );
  20670. if ( list === list.next ) list.steiner = true;
  20671. queue.push( getLeftmost( list ) );
  20672. }
  20673. queue.sort( compareX );
  20674. // process holes from left to right
  20675. for ( i = 0; i < queue.length; i ++ ) {
  20676. eliminateHole( queue[ i ], outerNode );
  20677. outerNode = filterPoints( outerNode, outerNode.next );
  20678. }
  20679. return outerNode;
  20680. }
  20681. function compareX( a, b ) {
  20682. return a.x - b.x;
  20683. }
  20684. // find a bridge between vertices that connects hole with an outer ring and and link it
  20685. function eliminateHole( hole, outerNode ) {
  20686. outerNode = findHoleBridge( hole, outerNode );
  20687. if ( outerNode ) {
  20688. var b = splitPolygon( outerNode, hole );
  20689. filterPoints( b, b.next );
  20690. }
  20691. }
  20692. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20693. function findHoleBridge( hole, outerNode ) {
  20694. var p = outerNode,
  20695. hx = hole.x,
  20696. hy = hole.y,
  20697. qx = - Infinity,
  20698. m;
  20699. // find a segment intersected by a ray from the hole's leftmost point to the left;
  20700. // segment's endpoint with lesser x will be potential connection point
  20701. do {
  20702. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  20703. var x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  20704. if ( x <= hx && x > qx ) {
  20705. qx = x;
  20706. if ( x === hx ) {
  20707. if ( hy === p.y ) return p;
  20708. if ( hy === p.next.y ) return p.next;
  20709. }
  20710. m = p.x < p.next.x ? p : p.next;
  20711. }
  20712. }
  20713. p = p.next;
  20714. } while ( p !== outerNode );
  20715. if ( ! m ) return null;
  20716. if ( hx === qx ) return m.prev; // hole touches outer segment; pick lower endpoint
  20717. // look for points inside the triangle of hole point, segment intersection and endpoint;
  20718. // if there are no points found, we have a valid connection;
  20719. // otherwise choose the point of the minimum angle with the ray as connection point
  20720. var stop = m,
  20721. mx = m.x,
  20722. my = m.y,
  20723. tanMin = Infinity,
  20724. tan;
  20725. p = m.next;
  20726. while ( p !== stop ) {
  20727. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  20728. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  20729. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  20730. if ( ( tan < tanMin || ( tan === tanMin && p.x > m.x ) ) && locallyInside( p, hole ) ) {
  20731. m = p;
  20732. tanMin = tan;
  20733. }
  20734. }
  20735. p = p.next;
  20736. }
  20737. return m;
  20738. }
  20739. // interlink polygon nodes in z-order
  20740. function indexCurve( start, minX, minY, invSize ) {
  20741. var p = start;
  20742. do {
  20743. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  20744. p.prevZ = p.prev;
  20745. p.nextZ = p.next;
  20746. p = p.next;
  20747. } while ( p !== start );
  20748. p.prevZ.nextZ = null;
  20749. p.prevZ = null;
  20750. sortLinked( p );
  20751. }
  20752. // Simon Tatham's linked list merge sort algorithm
  20753. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  20754. function sortLinked( list ) {
  20755. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  20756. do {
  20757. p = list;
  20758. list = null;
  20759. tail = null;
  20760. numMerges = 0;
  20761. while ( p ) {
  20762. numMerges ++;
  20763. q = p;
  20764. pSize = 0;
  20765. for ( i = 0; i < inSize; i ++ ) {
  20766. pSize ++;
  20767. q = q.nextZ;
  20768. if ( ! q ) break;
  20769. }
  20770. qSize = inSize;
  20771. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  20772. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  20773. e = p;
  20774. p = p.nextZ;
  20775. pSize --;
  20776. } else {
  20777. e = q;
  20778. q = q.nextZ;
  20779. qSize --;
  20780. }
  20781. if ( tail ) tail.nextZ = e;
  20782. else list = e;
  20783. e.prevZ = tail;
  20784. tail = e;
  20785. }
  20786. p = q;
  20787. }
  20788. tail.nextZ = null;
  20789. inSize *= 2;
  20790. } while ( numMerges > 1 );
  20791. return list;
  20792. }
  20793. // z-order of a point given coords and inverse of the longer side of data bbox
  20794. function zOrder( x, y, minX, minY, invSize ) {
  20795. // coords are transformed into non-negative 15-bit integer range
  20796. x = 32767 * ( x - minX ) * invSize;
  20797. y = 32767 * ( y - minY ) * invSize;
  20798. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  20799. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  20800. x = ( x | ( x << 2 ) ) & 0x33333333;
  20801. x = ( x | ( x << 1 ) ) & 0x55555555;
  20802. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  20803. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  20804. y = ( y | ( y << 2 ) ) & 0x33333333;
  20805. y = ( y | ( y << 1 ) ) & 0x55555555;
  20806. return x | ( y << 1 );
  20807. }
  20808. // find the leftmost node of a polygon ring
  20809. function getLeftmost( start ) {
  20810. var p = start, leftmost = start;
  20811. do {
  20812. if ( p.x < leftmost.x ) leftmost = p;
  20813. p = p.next;
  20814. } while ( p !== start );
  20815. return leftmost;
  20816. }
  20817. // check if a point lies within a convex triangle
  20818. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  20819. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  20820. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  20821. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  20822. }
  20823. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  20824. function isValidDiagonal( a, b ) {
  20825. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) &&
  20826. locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b );
  20827. }
  20828. // signed area of a triangle
  20829. function area( p, q, r ) {
  20830. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  20831. }
  20832. // check if two points are equal
  20833. function equals( p1, p2 ) {
  20834. return p1.x === p2.x && p1.y === p2.y;
  20835. }
  20836. // check if two segments intersect
  20837. function intersects( p1, q1, p2, q2 ) {
  20838. if ( ( equals( p1, q1 ) && equals( p2, q2 ) ) ||
  20839. ( equals( p1, q2 ) && equals( p2, q1 ) ) ) return true;
  20840. return area( p1, q1, p2 ) > 0 !== area( p1, q1, q2 ) > 0 &&
  20841. area( p2, q2, p1 ) > 0 !== area( p2, q2, q1 ) > 0;
  20842. }
  20843. // check if a polygon diagonal intersects any polygon segments
  20844. function intersectsPolygon( a, b ) {
  20845. var p = a;
  20846. do {
  20847. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  20848. intersects( p, p.next, a, b ) ) {
  20849. return true;
  20850. }
  20851. p = p.next;
  20852. } while ( p !== a );
  20853. return false;
  20854. }
  20855. // check if a polygon diagonal is locally inside the polygon
  20856. function locallyInside( a, b ) {
  20857. return area( a.prev, a, a.next ) < 0 ?
  20858. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  20859. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  20860. }
  20861. // check if the middle point of a polygon diagonal is inside the polygon
  20862. function middleInside( a, b ) {
  20863. var p = a,
  20864. inside = false,
  20865. px = ( a.x + b.x ) / 2,
  20866. py = ( a.y + b.y ) / 2;
  20867. do {
  20868. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  20869. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) ) {
  20870. inside = ! inside;
  20871. }
  20872. p = p.next;
  20873. } while ( p !== a );
  20874. return inside;
  20875. }
  20876. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  20877. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  20878. function splitPolygon( a, b ) {
  20879. var a2 = new Node( a.i, a.x, a.y ),
  20880. b2 = new Node( b.i, b.x, b.y ),
  20881. an = a.next,
  20882. bp = b.prev;
  20883. a.next = b;
  20884. b.prev = a;
  20885. a2.next = an;
  20886. an.prev = a2;
  20887. b2.next = a2;
  20888. a2.prev = b2;
  20889. bp.next = b2;
  20890. b2.prev = bp;
  20891. return b2;
  20892. }
  20893. // create a node and optionally link it with previous one (in a circular doubly linked list)
  20894. function insertNode( i, x, y, last ) {
  20895. var p = new Node( i, x, y );
  20896. if ( ! last ) {
  20897. p.prev = p;
  20898. p.next = p;
  20899. } else {
  20900. p.next = last.next;
  20901. p.prev = last;
  20902. last.next.prev = p;
  20903. last.next = p;
  20904. }
  20905. return p;
  20906. }
  20907. function removeNode( p ) {
  20908. p.next.prev = p.prev;
  20909. p.prev.next = p.next;
  20910. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  20911. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  20912. }
  20913. function Node( i, x, y ) {
  20914. // vertice index in coordinates array
  20915. this.i = i;
  20916. // vertex coordinates
  20917. this.x = x;
  20918. this.y = y;
  20919. // previous and next vertice nodes in a polygon ring
  20920. this.prev = null;
  20921. this.next = null;
  20922. // z-order curve value
  20923. this.z = null;
  20924. // previous and next nodes in z-order
  20925. this.prevZ = null;
  20926. this.nextZ = null;
  20927. // indicates whether this is a steiner point
  20928. this.steiner = false;
  20929. }
  20930. function signedArea( data, start, end, dim ) {
  20931. var sum = 0;
  20932. for ( var i = start, j = end - dim; i < end; i += dim ) {
  20933. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  20934. j = i;
  20935. }
  20936. return sum;
  20937. }
  20938. /**
  20939. * @author zz85 / http://www.lab4games.net/zz85/blog
  20940. */
  20941. var ShapeUtils = {
  20942. // calculate area of the contour polygon
  20943. area: function ( contour ) {
  20944. var n = contour.length;
  20945. var a = 0.0;
  20946. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  20947. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  20948. }
  20949. return a * 0.5;
  20950. },
  20951. isClockWise: function ( pts ) {
  20952. return ShapeUtils.area( pts ) < 0;
  20953. },
  20954. triangulateShape: function ( contour, holes ) {
  20955. var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  20956. var holeIndices = []; // array of hole indices
  20957. var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  20958. removeDupEndPts( contour );
  20959. addContour( vertices, contour );
  20960. //
  20961. var holeIndex = contour.length;
  20962. holes.forEach( removeDupEndPts );
  20963. for ( var i = 0; i < holes.length; i ++ ) {
  20964. holeIndices.push( holeIndex );
  20965. holeIndex += holes[ i ].length;
  20966. addContour( vertices, holes[ i ] );
  20967. }
  20968. //
  20969. var triangles = Earcut.triangulate( vertices, holeIndices );
  20970. //
  20971. for ( var i = 0; i < triangles.length; i += 3 ) {
  20972. faces.push( triangles.slice( i, i + 3 ) );
  20973. }
  20974. return faces;
  20975. }
  20976. };
  20977. function removeDupEndPts( points ) {
  20978. var l = points.length;
  20979. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  20980. points.pop();
  20981. }
  20982. }
  20983. function addContour( vertices, contour ) {
  20984. for ( var i = 0; i < contour.length; i ++ ) {
  20985. vertices.push( contour[ i ].x );
  20986. vertices.push( contour[ i ].y );
  20987. }
  20988. }
  20989. /**
  20990. * @author zz85 / http://www.lab4games.net/zz85/blog
  20991. *
  20992. * Creates extruded geometry from a path shape.
  20993. *
  20994. * parameters = {
  20995. *
  20996. * curveSegments: <int>, // number of points on the curves
  20997. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  20998. * depth: <float>, // Depth to extrude the shape
  20999. *
  21000. * bevelEnabled: <bool>, // turn on bevel
  21001. * bevelThickness: <float>, // how deep into the original shape bevel goes
  21002. * bevelSize: <float>, // how far from shape outline is bevel
  21003. * bevelSegments: <int>, // number of bevel layers
  21004. *
  21005. * extrudePath: <THREE.Curve> // curve to extrude shape along
  21006. *
  21007. * UVGenerator: <Object> // object that provides UV generator functions
  21008. *
  21009. * }
  21010. */
  21011. // ExtrudeGeometry
  21012. function ExtrudeGeometry( shapes, options ) {
  21013. Geometry.call( this );
  21014. this.type = 'ExtrudeGeometry';
  21015. this.parameters = {
  21016. shapes: shapes,
  21017. options: options
  21018. };
  21019. this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
  21020. this.mergeVertices();
  21021. }
  21022. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  21023. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  21024. ExtrudeGeometry.prototype.toJSON = function () {
  21025. var data = Geometry.prototype.toJSON.call( this );
  21026. var shapes = this.parameters.shapes;
  21027. var options = this.parameters.options;
  21028. return toJSON( shapes, options, data );
  21029. };
  21030. // ExtrudeBufferGeometry
  21031. function ExtrudeBufferGeometry( shapes, options ) {
  21032. BufferGeometry.call( this );
  21033. this.type = 'ExtrudeBufferGeometry';
  21034. this.parameters = {
  21035. shapes: shapes,
  21036. options: options
  21037. };
  21038. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  21039. var scope = this;
  21040. var verticesArray = [];
  21041. var uvArray = [];
  21042. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  21043. var shape = shapes[ i ];
  21044. addShape( shape );
  21045. }
  21046. // build geometry
  21047. this.addAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  21048. this.addAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  21049. this.computeVertexNormals();
  21050. // functions
  21051. function addShape( shape ) {
  21052. var placeholder = [];
  21053. // options
  21054. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21055. var steps = options.steps !== undefined ? options.steps : 1;
  21056. var depth = options.depth !== undefined ? options.depth : 100;
  21057. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  21058. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  21059. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  21060. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21061. var extrudePath = options.extrudePath;
  21062. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  21063. // deprecated options
  21064. if ( options.amount !== undefined ) {
  21065. console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
  21066. depth = options.amount;
  21067. }
  21068. //
  21069. var extrudePts, extrudeByPath = false;
  21070. var splineTube, binormal, normal, position2;
  21071. if ( extrudePath ) {
  21072. extrudePts = extrudePath.getSpacedPoints( steps );
  21073. extrudeByPath = true;
  21074. bevelEnabled = false; // bevels not supported for path extrusion
  21075. // SETUP TNB variables
  21076. // TODO1 - have a .isClosed in spline?
  21077. splineTube = extrudePath.computeFrenetFrames( steps, false );
  21078. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21079. binormal = new Vector3();
  21080. normal = new Vector3();
  21081. position2 = new Vector3();
  21082. }
  21083. // Safeguards if bevels are not enabled
  21084. if ( ! bevelEnabled ) {
  21085. bevelSegments = 0;
  21086. bevelThickness = 0;
  21087. bevelSize = 0;
  21088. }
  21089. // Variables initialization
  21090. var ahole, h, hl; // looping of holes
  21091. var shapePoints = shape.extractPoints( curveSegments );
  21092. var vertices = shapePoints.shape;
  21093. var holes = shapePoints.holes;
  21094. var reverse = ! ShapeUtils.isClockWise( vertices );
  21095. if ( reverse ) {
  21096. vertices = vertices.reverse();
  21097. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  21098. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21099. ahole = holes[ h ];
  21100. if ( ShapeUtils.isClockWise( ahole ) ) {
  21101. holes[ h ] = ahole.reverse();
  21102. }
  21103. }
  21104. }
  21105. var faces = ShapeUtils.triangulateShape( vertices, holes );
  21106. /* Vertices */
  21107. var contour = vertices; // vertices has all points but contour has only points of circumference
  21108. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21109. ahole = holes[ h ];
  21110. vertices = vertices.concat( ahole );
  21111. }
  21112. function scalePt2( pt, vec, size ) {
  21113. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  21114. return vec.clone().multiplyScalar( size ).add( pt );
  21115. }
  21116. var b, bs, t, z,
  21117. vert, vlen = vertices.length,
  21118. face, flen = faces.length;
  21119. // Find directions for point movement
  21120. function getBevelVec( inPt, inPrev, inNext ) {
  21121. // computes for inPt the corresponding point inPt' on a new contour
  21122. // shifted by 1 unit (length of normalized vector) to the left
  21123. // if we walk along contour clockwise, this new contour is outside the old one
  21124. //
  21125. // inPt' is the intersection of the two lines parallel to the two
  21126. // adjacent edges of inPt at a distance of 1 unit on the left side.
  21127. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  21128. // good reading for geometry algorithms (here: line-line intersection)
  21129. // http://geomalgorithms.com/a05-_intersect-1.html
  21130. var v_prev_x = inPt.x - inPrev.x,
  21131. v_prev_y = inPt.y - inPrev.y;
  21132. var v_next_x = inNext.x - inPt.x,
  21133. v_next_y = inNext.y - inPt.y;
  21134. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  21135. // check for collinear edges
  21136. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21137. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  21138. // not collinear
  21139. // length of vectors for normalizing
  21140. var v_prev_len = Math.sqrt( v_prev_lensq );
  21141. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  21142. // shift adjacent points by unit vectors to the left
  21143. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  21144. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  21145. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  21146. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  21147. // scaling factor for v_prev to intersection point
  21148. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  21149. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  21150. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21151. // vector from inPt to intersection point
  21152. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  21153. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  21154. // Don't normalize!, otherwise sharp corners become ugly
  21155. // but prevent crazy spikes
  21156. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  21157. if ( v_trans_lensq <= 2 ) {
  21158. return new Vector2( v_trans_x, v_trans_y );
  21159. } else {
  21160. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  21161. }
  21162. } else {
  21163. // handle special case of collinear edges
  21164. var direction_eq = false; // assumes: opposite
  21165. if ( v_prev_x > Number.EPSILON ) {
  21166. if ( v_next_x > Number.EPSILON ) {
  21167. direction_eq = true;
  21168. }
  21169. } else {
  21170. if ( v_prev_x < - Number.EPSILON ) {
  21171. if ( v_next_x < - Number.EPSILON ) {
  21172. direction_eq = true;
  21173. }
  21174. } else {
  21175. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  21176. direction_eq = true;
  21177. }
  21178. }
  21179. }
  21180. if ( direction_eq ) {
  21181. // console.log("Warning: lines are a straight sequence");
  21182. v_trans_x = - v_prev_y;
  21183. v_trans_y = v_prev_x;
  21184. shrink_by = Math.sqrt( v_prev_lensq );
  21185. } else {
  21186. // console.log("Warning: lines are a straight spike");
  21187. v_trans_x = v_prev_x;
  21188. v_trans_y = v_prev_y;
  21189. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  21190. }
  21191. }
  21192. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  21193. }
  21194. var contourMovements = [];
  21195. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21196. if ( j === il ) j = 0;
  21197. if ( k === il ) k = 0;
  21198. // (j)---(i)---(k)
  21199. // console.log('i,j,k', i, j , k)
  21200. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21201. }
  21202. var holesMovements = [],
  21203. oneHoleMovements, verticesMovements = contourMovements.concat();
  21204. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21205. ahole = holes[ h ];
  21206. oneHoleMovements = [];
  21207. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21208. if ( j === il ) j = 0;
  21209. if ( k === il ) k = 0;
  21210. // (j)---(i)---(k)
  21211. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21212. }
  21213. holesMovements.push( oneHoleMovements );
  21214. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21215. }
  21216. // Loop bevelSegments, 1 for the front, 1 for the back
  21217. for ( b = 0; b < bevelSegments; b ++ ) {
  21218. //for ( b = bevelSegments; b > 0; b -- ) {
  21219. t = b / bevelSegments;
  21220. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21221. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  21222. // contract shape
  21223. for ( i = 0, il = contour.length; i < il; i ++ ) {
  21224. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21225. v( vert.x, vert.y, - z );
  21226. }
  21227. // expand holes
  21228. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21229. ahole = holes[ h ];
  21230. oneHoleMovements = holesMovements[ h ];
  21231. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  21232. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21233. v( vert.x, vert.y, - z );
  21234. }
  21235. }
  21236. }
  21237. bs = bevelSize;
  21238. // Back facing vertices
  21239. for ( i = 0; i < vlen; i ++ ) {
  21240. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21241. if ( ! extrudeByPath ) {
  21242. v( vert.x, vert.y, 0 );
  21243. } else {
  21244. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21245. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  21246. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  21247. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  21248. v( position2.x, position2.y, position2.z );
  21249. }
  21250. }
  21251. // Add stepped vertices...
  21252. // Including front facing vertices
  21253. var s;
  21254. for ( s = 1; s <= steps; s ++ ) {
  21255. for ( i = 0; i < vlen; i ++ ) {
  21256. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21257. if ( ! extrudeByPath ) {
  21258. v( vert.x, vert.y, depth / steps * s );
  21259. } else {
  21260. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21261. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  21262. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  21263. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  21264. v( position2.x, position2.y, position2.z );
  21265. }
  21266. }
  21267. }
  21268. // Add bevel segments planes
  21269. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21270. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  21271. t = b / bevelSegments;
  21272. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21273. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  21274. // contract shape
  21275. for ( i = 0, il = contour.length; i < il; i ++ ) {
  21276. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21277. v( vert.x, vert.y, depth + z );
  21278. }
  21279. // expand holes
  21280. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21281. ahole = holes[ h ];
  21282. oneHoleMovements = holesMovements[ h ];
  21283. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  21284. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21285. if ( ! extrudeByPath ) {
  21286. v( vert.x, vert.y, depth + z );
  21287. } else {
  21288. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  21289. }
  21290. }
  21291. }
  21292. }
  21293. /* Faces */
  21294. // Top and bottom faces
  21295. buildLidFaces();
  21296. // Sides faces
  21297. buildSideFaces();
  21298. ///// Internal functions
  21299. function buildLidFaces() {
  21300. var start = verticesArray.length / 3;
  21301. if ( bevelEnabled ) {
  21302. var layer = 0; // steps + 1
  21303. var offset = vlen * layer;
  21304. // Bottom faces
  21305. for ( i = 0; i < flen; i ++ ) {
  21306. face = faces[ i ];
  21307. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  21308. }
  21309. layer = steps + bevelSegments * 2;
  21310. offset = vlen * layer;
  21311. // Top faces
  21312. for ( i = 0; i < flen; i ++ ) {
  21313. face = faces[ i ];
  21314. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  21315. }
  21316. } else {
  21317. // Bottom faces
  21318. for ( i = 0; i < flen; i ++ ) {
  21319. face = faces[ i ];
  21320. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  21321. }
  21322. // Top faces
  21323. for ( i = 0; i < flen; i ++ ) {
  21324. face = faces[ i ];
  21325. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  21326. }
  21327. }
  21328. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  21329. }
  21330. // Create faces for the z-sides of the shape
  21331. function buildSideFaces() {
  21332. var start = verticesArray.length / 3;
  21333. var layeroffset = 0;
  21334. sidewalls( contour, layeroffset );
  21335. layeroffset += contour.length;
  21336. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21337. ahole = holes[ h ];
  21338. sidewalls( ahole, layeroffset );
  21339. //, true
  21340. layeroffset += ahole.length;
  21341. }
  21342. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  21343. }
  21344. function sidewalls( contour, layeroffset ) {
  21345. var j, k;
  21346. i = contour.length;
  21347. while ( -- i >= 0 ) {
  21348. j = i;
  21349. k = i - 1;
  21350. if ( k < 0 ) k = contour.length - 1;
  21351. //console.log('b', i,j, i-1, k,vertices.length);
  21352. var s = 0,
  21353. sl = steps + bevelSegments * 2;
  21354. for ( s = 0; s < sl; s ++ ) {
  21355. var slen1 = vlen * s;
  21356. var slen2 = vlen * ( s + 1 );
  21357. var a = layeroffset + j + slen1,
  21358. b = layeroffset + k + slen1,
  21359. c = layeroffset + k + slen2,
  21360. d = layeroffset + j + slen2;
  21361. f4( a, b, c, d );
  21362. }
  21363. }
  21364. }
  21365. function v( x, y, z ) {
  21366. placeholder.push( x );
  21367. placeholder.push( y );
  21368. placeholder.push( z );
  21369. }
  21370. function f3( a, b, c ) {
  21371. addVertex( a );
  21372. addVertex( b );
  21373. addVertex( c );
  21374. var nextIndex = verticesArray.length / 3;
  21375. var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21376. addUV( uvs[ 0 ] );
  21377. addUV( uvs[ 1 ] );
  21378. addUV( uvs[ 2 ] );
  21379. }
  21380. function f4( a, b, c, d ) {
  21381. addVertex( a );
  21382. addVertex( b );
  21383. addVertex( d );
  21384. addVertex( b );
  21385. addVertex( c );
  21386. addVertex( d );
  21387. var nextIndex = verticesArray.length / 3;
  21388. var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21389. addUV( uvs[ 0 ] );
  21390. addUV( uvs[ 1 ] );
  21391. addUV( uvs[ 3 ] );
  21392. addUV( uvs[ 1 ] );
  21393. addUV( uvs[ 2 ] );
  21394. addUV( uvs[ 3 ] );
  21395. }
  21396. function addVertex( index ) {
  21397. verticesArray.push( placeholder[ index * 3 + 0 ] );
  21398. verticesArray.push( placeholder[ index * 3 + 1 ] );
  21399. verticesArray.push( placeholder[ index * 3 + 2 ] );
  21400. }
  21401. function addUV( vector2 ) {
  21402. uvArray.push( vector2.x );
  21403. uvArray.push( vector2.y );
  21404. }
  21405. }
  21406. }
  21407. ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21408. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  21409. ExtrudeBufferGeometry.prototype.toJSON = function () {
  21410. var data = BufferGeometry.prototype.toJSON.call( this );
  21411. var shapes = this.parameters.shapes;
  21412. var options = this.parameters.options;
  21413. return toJSON( shapes, options, data );
  21414. };
  21415. //
  21416. var WorldUVGenerator = {
  21417. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  21418. var a_x = vertices[ indexA * 3 ];
  21419. var a_y = vertices[ indexA * 3 + 1 ];
  21420. var b_x = vertices[ indexB * 3 ];
  21421. var b_y = vertices[ indexB * 3 + 1 ];
  21422. var c_x = vertices[ indexC * 3 ];
  21423. var c_y = vertices[ indexC * 3 + 1 ];
  21424. return [
  21425. new Vector2( a_x, a_y ),
  21426. new Vector2( b_x, b_y ),
  21427. new Vector2( c_x, c_y )
  21428. ];
  21429. },
  21430. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  21431. var a_x = vertices[ indexA * 3 ];
  21432. var a_y = vertices[ indexA * 3 + 1 ];
  21433. var a_z = vertices[ indexA * 3 + 2 ];
  21434. var b_x = vertices[ indexB * 3 ];
  21435. var b_y = vertices[ indexB * 3 + 1 ];
  21436. var b_z = vertices[ indexB * 3 + 2 ];
  21437. var c_x = vertices[ indexC * 3 ];
  21438. var c_y = vertices[ indexC * 3 + 1 ];
  21439. var c_z = vertices[ indexC * 3 + 2 ];
  21440. var d_x = vertices[ indexD * 3 ];
  21441. var d_y = vertices[ indexD * 3 + 1 ];
  21442. var d_z = vertices[ indexD * 3 + 2 ];
  21443. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  21444. return [
  21445. new Vector2( a_x, 1 - a_z ),
  21446. new Vector2( b_x, 1 - b_z ),
  21447. new Vector2( c_x, 1 - c_z ),
  21448. new Vector2( d_x, 1 - d_z )
  21449. ];
  21450. } else {
  21451. return [
  21452. new Vector2( a_y, 1 - a_z ),
  21453. new Vector2( b_y, 1 - b_z ),
  21454. new Vector2( c_y, 1 - c_z ),
  21455. new Vector2( d_y, 1 - d_z )
  21456. ];
  21457. }
  21458. }
  21459. };
  21460. function toJSON( shapes, options, data ) {
  21461. //
  21462. data.shapes = [];
  21463. if ( Array.isArray( shapes ) ) {
  21464. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  21465. var shape = shapes[ i ];
  21466. data.shapes.push( shape.uuid );
  21467. }
  21468. } else {
  21469. data.shapes.push( shapes.uuid );
  21470. }
  21471. //
  21472. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  21473. return data;
  21474. }
  21475. /**
  21476. * @author zz85 / http://www.lab4games.net/zz85/blog
  21477. * @author alteredq / http://alteredqualia.com/
  21478. *
  21479. * Text = 3D Text
  21480. *
  21481. * parameters = {
  21482. * font: <THREE.Font>, // font
  21483. *
  21484. * size: <float>, // size of the text
  21485. * height: <float>, // thickness to extrude text
  21486. * curveSegments: <int>, // number of points on the curves
  21487. *
  21488. * bevelEnabled: <bool>, // turn on bevel
  21489. * bevelThickness: <float>, // how deep into text bevel goes
  21490. * bevelSize: <float> // how far from text outline is bevel
  21491. * }
  21492. */
  21493. // TextGeometry
  21494. function TextGeometry( text, parameters ) {
  21495. Geometry.call( this );
  21496. this.type = 'TextGeometry';
  21497. this.parameters = {
  21498. text: text,
  21499. parameters: parameters
  21500. };
  21501. this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
  21502. this.mergeVertices();
  21503. }
  21504. TextGeometry.prototype = Object.create( Geometry.prototype );
  21505. TextGeometry.prototype.constructor = TextGeometry;
  21506. // TextBufferGeometry
  21507. function TextBufferGeometry( text, parameters ) {
  21508. parameters = parameters || {};
  21509. var font = parameters.font;
  21510. if ( ! ( font && font.isFont ) ) {
  21511. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  21512. return new Geometry();
  21513. }
  21514. var shapes = font.generateShapes( text, parameters.size );
  21515. // translate parameters to ExtrudeGeometry API
  21516. parameters.depth = parameters.height !== undefined ? parameters.height : 50;
  21517. // defaults
  21518. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  21519. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  21520. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  21521. ExtrudeBufferGeometry.call( this, shapes, parameters );
  21522. this.type = 'TextBufferGeometry';
  21523. }
  21524. TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype );
  21525. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  21526. /**
  21527. * @author mrdoob / http://mrdoob.com/
  21528. * @author benaadams / https://twitter.com/ben_a_adams
  21529. * @author Mugen87 / https://github.com/Mugen87
  21530. */
  21531. // SphereGeometry
  21532. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  21533. Geometry.call( this );
  21534. this.type = 'SphereGeometry';
  21535. this.parameters = {
  21536. radius: radius,
  21537. widthSegments: widthSegments,
  21538. heightSegments: heightSegments,
  21539. phiStart: phiStart,
  21540. phiLength: phiLength,
  21541. thetaStart: thetaStart,
  21542. thetaLength: thetaLength
  21543. };
  21544. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  21545. this.mergeVertices();
  21546. }
  21547. SphereGeometry.prototype = Object.create( Geometry.prototype );
  21548. SphereGeometry.prototype.constructor = SphereGeometry;
  21549. // SphereBufferGeometry
  21550. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  21551. BufferGeometry.call( this );
  21552. this.type = 'SphereBufferGeometry';
  21553. this.parameters = {
  21554. radius: radius,
  21555. widthSegments: widthSegments,
  21556. heightSegments: heightSegments,
  21557. phiStart: phiStart,
  21558. phiLength: phiLength,
  21559. thetaStart: thetaStart,
  21560. thetaLength: thetaLength
  21561. };
  21562. radius = radius || 1;
  21563. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  21564. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  21565. phiStart = phiStart !== undefined ? phiStart : 0;
  21566. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  21567. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21568. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  21569. var thetaEnd = thetaStart + thetaLength;
  21570. var ix, iy;
  21571. var index = 0;
  21572. var grid = [];
  21573. var vertex = new Vector3();
  21574. var normal = new Vector3();
  21575. // buffers
  21576. var indices = [];
  21577. var vertices = [];
  21578. var normals = [];
  21579. var uvs = [];
  21580. // generate vertices, normals and uvs
  21581. for ( iy = 0; iy <= heightSegments; iy ++ ) {
  21582. var verticesRow = [];
  21583. var v = iy / heightSegments;
  21584. for ( ix = 0; ix <= widthSegments; ix ++ ) {
  21585. var u = ix / widthSegments;
  21586. // vertex
  21587. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21588. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  21589. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21590. vertices.push( vertex.x, vertex.y, vertex.z );
  21591. // normal
  21592. normal.set( vertex.x, vertex.y, vertex.z ).normalize();
  21593. normals.push( normal.x, normal.y, normal.z );
  21594. // uv
  21595. uvs.push( u, 1 - v );
  21596. verticesRow.push( index ++ );
  21597. }
  21598. grid.push( verticesRow );
  21599. }
  21600. // indices
  21601. for ( iy = 0; iy < heightSegments; iy ++ ) {
  21602. for ( ix = 0; ix < widthSegments; ix ++ ) {
  21603. var a = grid[ iy ][ ix + 1 ];
  21604. var b = grid[ iy ][ ix ];
  21605. var c = grid[ iy + 1 ][ ix ];
  21606. var d = grid[ iy + 1 ][ ix + 1 ];
  21607. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  21608. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  21609. }
  21610. }
  21611. // build geometry
  21612. this.setIndex( indices );
  21613. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21614. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21615. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21616. }
  21617. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21618. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  21619. /**
  21620. * @author Kaleb Murphy
  21621. * @author Mugen87 / https://github.com/Mugen87
  21622. */
  21623. // RingGeometry
  21624. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  21625. Geometry.call( this );
  21626. this.type = 'RingGeometry';
  21627. this.parameters = {
  21628. innerRadius: innerRadius,
  21629. outerRadius: outerRadius,
  21630. thetaSegments: thetaSegments,
  21631. phiSegments: phiSegments,
  21632. thetaStart: thetaStart,
  21633. thetaLength: thetaLength
  21634. };
  21635. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  21636. this.mergeVertices();
  21637. }
  21638. RingGeometry.prototype = Object.create( Geometry.prototype );
  21639. RingGeometry.prototype.constructor = RingGeometry;
  21640. // RingBufferGeometry
  21641. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  21642. BufferGeometry.call( this );
  21643. this.type = 'RingBufferGeometry';
  21644. this.parameters = {
  21645. innerRadius: innerRadius,
  21646. outerRadius: outerRadius,
  21647. thetaSegments: thetaSegments,
  21648. phiSegments: phiSegments,
  21649. thetaStart: thetaStart,
  21650. thetaLength: thetaLength
  21651. };
  21652. innerRadius = innerRadius || 0.5;
  21653. outerRadius = outerRadius || 1;
  21654. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21655. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  21656. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  21657. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  21658. // buffers
  21659. var indices = [];
  21660. var vertices = [];
  21661. var normals = [];
  21662. var uvs = [];
  21663. // some helper variables
  21664. var segment;
  21665. var radius = innerRadius;
  21666. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  21667. var vertex = new Vector3();
  21668. var uv = new Vector2();
  21669. var j, i;
  21670. // generate vertices, normals and uvs
  21671. for ( j = 0; j <= phiSegments; j ++ ) {
  21672. for ( i = 0; i <= thetaSegments; i ++ ) {
  21673. // values are generate from the inside of the ring to the outside
  21674. segment = thetaStart + i / thetaSegments * thetaLength;
  21675. // vertex
  21676. vertex.x = radius * Math.cos( segment );
  21677. vertex.y = radius * Math.sin( segment );
  21678. vertices.push( vertex.x, vertex.y, vertex.z );
  21679. // normal
  21680. normals.push( 0, 0, 1 );
  21681. // uv
  21682. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  21683. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  21684. uvs.push( uv.x, uv.y );
  21685. }
  21686. // increase the radius for next row of vertices
  21687. radius += radiusStep;
  21688. }
  21689. // indices
  21690. for ( j = 0; j < phiSegments; j ++ ) {
  21691. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  21692. for ( i = 0; i < thetaSegments; i ++ ) {
  21693. segment = i + thetaSegmentLevel;
  21694. var a = segment;
  21695. var b = segment + thetaSegments + 1;
  21696. var c = segment + thetaSegments + 2;
  21697. var d = segment + 1;
  21698. // faces
  21699. indices.push( a, b, d );
  21700. indices.push( b, c, d );
  21701. }
  21702. }
  21703. // build geometry
  21704. this.setIndex( indices );
  21705. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21706. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21707. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21708. }
  21709. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21710. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  21711. /**
  21712. * @author zz85 / https://github.com/zz85
  21713. * @author bhouston / http://clara.io
  21714. * @author Mugen87 / https://github.com/Mugen87
  21715. */
  21716. // LatheGeometry
  21717. function LatheGeometry( points, segments, phiStart, phiLength ) {
  21718. Geometry.call( this );
  21719. this.type = 'LatheGeometry';
  21720. this.parameters = {
  21721. points: points,
  21722. segments: segments,
  21723. phiStart: phiStart,
  21724. phiLength: phiLength
  21725. };
  21726. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  21727. this.mergeVertices();
  21728. }
  21729. LatheGeometry.prototype = Object.create( Geometry.prototype );
  21730. LatheGeometry.prototype.constructor = LatheGeometry;
  21731. // LatheBufferGeometry
  21732. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  21733. BufferGeometry.call( this );
  21734. this.type = 'LatheBufferGeometry';
  21735. this.parameters = {
  21736. points: points,
  21737. segments: segments,
  21738. phiStart: phiStart,
  21739. phiLength: phiLength
  21740. };
  21741. segments = Math.floor( segments ) || 12;
  21742. phiStart = phiStart || 0;
  21743. phiLength = phiLength || Math.PI * 2;
  21744. // clamp phiLength so it's in range of [ 0, 2PI ]
  21745. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  21746. // buffers
  21747. var indices = [];
  21748. var vertices = [];
  21749. var uvs = [];
  21750. // helper variables
  21751. var base;
  21752. var inverseSegments = 1.0 / segments;
  21753. var vertex = new Vector3();
  21754. var uv = new Vector2();
  21755. var i, j;
  21756. // generate vertices and uvs
  21757. for ( i = 0; i <= segments; i ++ ) {
  21758. var phi = phiStart + i * inverseSegments * phiLength;
  21759. var sin = Math.sin( phi );
  21760. var cos = Math.cos( phi );
  21761. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  21762. // vertex
  21763. vertex.x = points[ j ].x * sin;
  21764. vertex.y = points[ j ].y;
  21765. vertex.z = points[ j ].x * cos;
  21766. vertices.push( vertex.x, vertex.y, vertex.z );
  21767. // uv
  21768. uv.x = i / segments;
  21769. uv.y = j / ( points.length - 1 );
  21770. uvs.push( uv.x, uv.y );
  21771. }
  21772. }
  21773. // indices
  21774. for ( i = 0; i < segments; i ++ ) {
  21775. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  21776. base = j + i * points.length;
  21777. var a = base;
  21778. var b = base + points.length;
  21779. var c = base + points.length + 1;
  21780. var d = base + 1;
  21781. // faces
  21782. indices.push( a, b, d );
  21783. indices.push( b, c, d );
  21784. }
  21785. }
  21786. // build geometry
  21787. this.setIndex( indices );
  21788. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21789. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21790. // generate normals
  21791. this.computeVertexNormals();
  21792. // if the geometry is closed, we need to average the normals along the seam.
  21793. // because the corresponding vertices are identical (but still have different UVs).
  21794. if ( phiLength === Math.PI * 2 ) {
  21795. var normals = this.attributes.normal.array;
  21796. var n1 = new Vector3();
  21797. var n2 = new Vector3();
  21798. var n = new Vector3();
  21799. // this is the buffer offset for the last line of vertices
  21800. base = segments * points.length * 3;
  21801. for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  21802. // select the normal of the vertex in the first line
  21803. n1.x = normals[ j + 0 ];
  21804. n1.y = normals[ j + 1 ];
  21805. n1.z = normals[ j + 2 ];
  21806. // select the normal of the vertex in the last line
  21807. n2.x = normals[ base + j + 0 ];
  21808. n2.y = normals[ base + j + 1 ];
  21809. n2.z = normals[ base + j + 2 ];
  21810. // average normals
  21811. n.addVectors( n1, n2 ).normalize();
  21812. // assign the new values to both normals
  21813. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  21814. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  21815. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  21816. }
  21817. }
  21818. }
  21819. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21820. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  21821. /**
  21822. * @author jonobr1 / http://jonobr1.com
  21823. * @author Mugen87 / https://github.com/Mugen87
  21824. */
  21825. // ShapeGeometry
  21826. function ShapeGeometry( shapes, curveSegments ) {
  21827. Geometry.call( this );
  21828. this.type = 'ShapeGeometry';
  21829. if ( typeof curveSegments === 'object' ) {
  21830. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  21831. curveSegments = curveSegments.curveSegments;
  21832. }
  21833. this.parameters = {
  21834. shapes: shapes,
  21835. curveSegments: curveSegments
  21836. };
  21837. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  21838. this.mergeVertices();
  21839. }
  21840. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  21841. ShapeGeometry.prototype.constructor = ShapeGeometry;
  21842. ShapeGeometry.prototype.toJSON = function () {
  21843. var data = Geometry.prototype.toJSON.call( this );
  21844. var shapes = this.parameters.shapes;
  21845. return toJSON$1( shapes, data );
  21846. };
  21847. // ShapeBufferGeometry
  21848. function ShapeBufferGeometry( shapes, curveSegments ) {
  21849. BufferGeometry.call( this );
  21850. this.type = 'ShapeBufferGeometry';
  21851. this.parameters = {
  21852. shapes: shapes,
  21853. curveSegments: curveSegments
  21854. };
  21855. curveSegments = curveSegments || 12;
  21856. // buffers
  21857. var indices = [];
  21858. var vertices = [];
  21859. var normals = [];
  21860. var uvs = [];
  21861. // helper variables
  21862. var groupStart = 0;
  21863. var groupCount = 0;
  21864. // allow single and array values for "shapes" parameter
  21865. if ( Array.isArray( shapes ) === false ) {
  21866. addShape( shapes );
  21867. } else {
  21868. for ( var i = 0; i < shapes.length; i ++ ) {
  21869. addShape( shapes[ i ] );
  21870. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  21871. groupStart += groupCount;
  21872. groupCount = 0;
  21873. }
  21874. }
  21875. // build geometry
  21876. this.setIndex( indices );
  21877. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21878. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21879. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21880. // helper functions
  21881. function addShape( shape ) {
  21882. var i, l, shapeHole;
  21883. var indexOffset = vertices.length / 3;
  21884. var points = shape.extractPoints( curveSegments );
  21885. var shapeVertices = points.shape;
  21886. var shapeHoles = points.holes;
  21887. // check direction of vertices
  21888. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  21889. shapeVertices = shapeVertices.reverse();
  21890. // also check if holes are in the opposite direction
  21891. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21892. shapeHole = shapeHoles[ i ];
  21893. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  21894. shapeHoles[ i ] = shapeHole.reverse();
  21895. }
  21896. }
  21897. }
  21898. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  21899. // join vertices of inner and outer paths to a single array
  21900. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21901. shapeHole = shapeHoles[ i ];
  21902. shapeVertices = shapeVertices.concat( shapeHole );
  21903. }
  21904. // vertices, normals, uvs
  21905. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  21906. var vertex = shapeVertices[ i ];
  21907. vertices.push( vertex.x, vertex.y, 0 );
  21908. normals.push( 0, 0, 1 );
  21909. uvs.push( vertex.x, vertex.y ); // world uvs
  21910. }
  21911. // incides
  21912. for ( i = 0, l = faces.length; i < l; i ++ ) {
  21913. var face = faces[ i ];
  21914. var a = face[ 0 ] + indexOffset;
  21915. var b = face[ 1 ] + indexOffset;
  21916. var c = face[ 2 ] + indexOffset;
  21917. indices.push( a, b, c );
  21918. groupCount += 3;
  21919. }
  21920. }
  21921. }
  21922. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21923. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  21924. ShapeBufferGeometry.prototype.toJSON = function () {
  21925. var data = BufferGeometry.prototype.toJSON.call( this );
  21926. var shapes = this.parameters.shapes;
  21927. return toJSON$1( shapes, data );
  21928. };
  21929. //
  21930. function toJSON$1( shapes, data ) {
  21931. data.shapes = [];
  21932. if ( Array.isArray( shapes ) ) {
  21933. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  21934. var shape = shapes[ i ];
  21935. data.shapes.push( shape.uuid );
  21936. }
  21937. } else {
  21938. data.shapes.push( shapes.uuid );
  21939. }
  21940. return data;
  21941. }
  21942. /**
  21943. * @author WestLangley / http://github.com/WestLangley
  21944. * @author Mugen87 / https://github.com/Mugen87
  21945. */
  21946. function EdgesGeometry( geometry, thresholdAngle ) {
  21947. BufferGeometry.call( this );
  21948. this.type = 'EdgesGeometry';
  21949. this.parameters = {
  21950. thresholdAngle: thresholdAngle
  21951. };
  21952. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  21953. // buffer
  21954. var vertices = [];
  21955. // helper variables
  21956. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  21957. var edge = [ 0, 0 ], edges = {}, edge1, edge2;
  21958. var key, keys = [ 'a', 'b', 'c' ];
  21959. // prepare source geometry
  21960. var geometry2;
  21961. if ( geometry.isBufferGeometry ) {
  21962. geometry2 = new Geometry();
  21963. geometry2.fromBufferGeometry( geometry );
  21964. } else {
  21965. geometry2 = geometry.clone();
  21966. }
  21967. geometry2.mergeVertices();
  21968. geometry2.computeFaceNormals();
  21969. var sourceVertices = geometry2.vertices;
  21970. var faces = geometry2.faces;
  21971. // now create a data structure where each entry represents an edge with its adjoining faces
  21972. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21973. var face = faces[ i ];
  21974. for ( var j = 0; j < 3; j ++ ) {
  21975. edge1 = face[ keys[ j ] ];
  21976. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  21977. edge[ 0 ] = Math.min( edge1, edge2 );
  21978. edge[ 1 ] = Math.max( edge1, edge2 );
  21979. key = edge[ 0 ] + ',' + edge[ 1 ];
  21980. if ( edges[ key ] === undefined ) {
  21981. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };
  21982. } else {
  21983. edges[ key ].face2 = i;
  21984. }
  21985. }
  21986. }
  21987. // generate vertices
  21988. for ( key in edges ) {
  21989. var e = edges[ key ];
  21990. // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  21991. if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {
  21992. var vertex = sourceVertices[ e.index1 ];
  21993. vertices.push( vertex.x, vertex.y, vertex.z );
  21994. vertex = sourceVertices[ e.index2 ];
  21995. vertices.push( vertex.x, vertex.y, vertex.z );
  21996. }
  21997. }
  21998. // build geometry
  21999. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22000. }
  22001. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  22002. EdgesGeometry.prototype.constructor = EdgesGeometry;
  22003. /**
  22004. * @author mrdoob / http://mrdoob.com/
  22005. * @author Mugen87 / https://github.com/Mugen87
  22006. */
  22007. // CylinderGeometry
  22008. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  22009. Geometry.call( this );
  22010. this.type = 'CylinderGeometry';
  22011. this.parameters = {
  22012. radiusTop: radiusTop,
  22013. radiusBottom: radiusBottom,
  22014. height: height,
  22015. radialSegments: radialSegments,
  22016. heightSegments: heightSegments,
  22017. openEnded: openEnded,
  22018. thetaStart: thetaStart,
  22019. thetaLength: thetaLength
  22020. };
  22021. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  22022. this.mergeVertices();
  22023. }
  22024. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  22025. CylinderGeometry.prototype.constructor = CylinderGeometry;
  22026. // CylinderBufferGeometry
  22027. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  22028. BufferGeometry.call( this );
  22029. this.type = 'CylinderBufferGeometry';
  22030. this.parameters = {
  22031. radiusTop: radiusTop,
  22032. radiusBottom: radiusBottom,
  22033. height: height,
  22034. radialSegments: radialSegments,
  22035. heightSegments: heightSegments,
  22036. openEnded: openEnded,
  22037. thetaStart: thetaStart,
  22038. thetaLength: thetaLength
  22039. };
  22040. var scope = this;
  22041. radiusTop = radiusTop !== undefined ? radiusTop : 1;
  22042. radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
  22043. height = height || 1;
  22044. radialSegments = Math.floor( radialSegments ) || 8;
  22045. heightSegments = Math.floor( heightSegments ) || 1;
  22046. openEnded = openEnded !== undefined ? openEnded : false;
  22047. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  22048. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  22049. // buffers
  22050. var indices = [];
  22051. var vertices = [];
  22052. var normals = [];
  22053. var uvs = [];
  22054. // helper variables
  22055. var index = 0;
  22056. var indexArray = [];
  22057. var halfHeight = height / 2;
  22058. var groupStart = 0;
  22059. // generate geometry
  22060. generateTorso();
  22061. if ( openEnded === false ) {
  22062. if ( radiusTop > 0 ) generateCap( true );
  22063. if ( radiusBottom > 0 ) generateCap( false );
  22064. }
  22065. // build geometry
  22066. this.setIndex( indices );
  22067. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22068. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22069. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22070. function generateTorso() {
  22071. var x, y;
  22072. var normal = new Vector3();
  22073. var vertex = new Vector3();
  22074. var groupCount = 0;
  22075. // this will be used to calculate the normal
  22076. var slope = ( radiusBottom - radiusTop ) / height;
  22077. // generate vertices, normals and uvs
  22078. for ( y = 0; y <= heightSegments; y ++ ) {
  22079. var indexRow = [];
  22080. var v = y / heightSegments;
  22081. // calculate the radius of the current row
  22082. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22083. for ( x = 0; x <= radialSegments; x ++ ) {
  22084. var u = x / radialSegments;
  22085. var theta = u * thetaLength + thetaStart;
  22086. var sinTheta = Math.sin( theta );
  22087. var cosTheta = Math.cos( theta );
  22088. // vertex
  22089. vertex.x = radius * sinTheta;
  22090. vertex.y = - v * height + halfHeight;
  22091. vertex.z = radius * cosTheta;
  22092. vertices.push( vertex.x, vertex.y, vertex.z );
  22093. // normal
  22094. normal.set( sinTheta, slope, cosTheta ).normalize();
  22095. normals.push( normal.x, normal.y, normal.z );
  22096. // uv
  22097. uvs.push( u, 1 - v );
  22098. // save index of vertex in respective row
  22099. indexRow.push( index ++ );
  22100. }
  22101. // now save vertices of the row in our index array
  22102. indexArray.push( indexRow );
  22103. }
  22104. // generate indices
  22105. for ( x = 0; x < radialSegments; x ++ ) {
  22106. for ( y = 0; y < heightSegments; y ++ ) {
  22107. // we use the index array to access the correct indices
  22108. var a = indexArray[ y ][ x ];
  22109. var b = indexArray[ y + 1 ][ x ];
  22110. var c = indexArray[ y + 1 ][ x + 1 ];
  22111. var d = indexArray[ y ][ x + 1 ];
  22112. // faces
  22113. indices.push( a, b, d );
  22114. indices.push( b, c, d );
  22115. // update group counter
  22116. groupCount += 6;
  22117. }
  22118. }
  22119. // add a group to the geometry. this will ensure multi material support
  22120. scope.addGroup( groupStart, groupCount, 0 );
  22121. // calculate new start value for groups
  22122. groupStart += groupCount;
  22123. }
  22124. function generateCap( top ) {
  22125. var x, centerIndexStart, centerIndexEnd;
  22126. var uv = new Vector2();
  22127. var vertex = new Vector3();
  22128. var groupCount = 0;
  22129. var radius = ( top === true ) ? radiusTop : radiusBottom;
  22130. var sign = ( top === true ) ? 1 : - 1;
  22131. // save the index of the first center vertex
  22132. centerIndexStart = index;
  22133. // first we generate the center vertex data of the cap.
  22134. // because the geometry needs one set of uvs per face,
  22135. // we must generate a center vertex per face/segment
  22136. for ( x = 1; x <= radialSegments; x ++ ) {
  22137. // vertex
  22138. vertices.push( 0, halfHeight * sign, 0 );
  22139. // normal
  22140. normals.push( 0, sign, 0 );
  22141. // uv
  22142. uvs.push( 0.5, 0.5 );
  22143. // increase index
  22144. index ++;
  22145. }
  22146. // save the index of the last center vertex
  22147. centerIndexEnd = index;
  22148. // now we generate the surrounding vertices, normals and uvs
  22149. for ( x = 0; x <= radialSegments; x ++ ) {
  22150. var u = x / radialSegments;
  22151. var theta = u * thetaLength + thetaStart;
  22152. var cosTheta = Math.cos( theta );
  22153. var sinTheta = Math.sin( theta );
  22154. // vertex
  22155. vertex.x = radius * sinTheta;
  22156. vertex.y = halfHeight * sign;
  22157. vertex.z = radius * cosTheta;
  22158. vertices.push( vertex.x, vertex.y, vertex.z );
  22159. // normal
  22160. normals.push( 0, sign, 0 );
  22161. // uv
  22162. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22163. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22164. uvs.push( uv.x, uv.y );
  22165. // increase index
  22166. index ++;
  22167. }
  22168. // generate indices
  22169. for ( x = 0; x < radialSegments; x ++ ) {
  22170. var c = centerIndexStart + x;
  22171. var i = centerIndexEnd + x;
  22172. if ( top === true ) {
  22173. // face top
  22174. indices.push( i, i + 1, c );
  22175. } else {
  22176. // face bottom
  22177. indices.push( i + 1, i, c );
  22178. }
  22179. groupCount += 3;
  22180. }
  22181. // add a group to the geometry. this will ensure multi material support
  22182. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22183. // calculate new start value for groups
  22184. groupStart += groupCount;
  22185. }
  22186. }
  22187. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22188. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  22189. /**
  22190. * @author abelnation / http://github.com/abelnation
  22191. */
  22192. // ConeGeometry
  22193. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  22194. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22195. this.type = 'ConeGeometry';
  22196. this.parameters = {
  22197. radius: radius,
  22198. height: height,
  22199. radialSegments: radialSegments,
  22200. heightSegments: heightSegments,
  22201. openEnded: openEnded,
  22202. thetaStart: thetaStart,
  22203. thetaLength: thetaLength
  22204. };
  22205. }
  22206. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  22207. ConeGeometry.prototype.constructor = ConeGeometry;
  22208. // ConeBufferGeometry
  22209. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  22210. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22211. this.type = 'ConeBufferGeometry';
  22212. this.parameters = {
  22213. radius: radius,
  22214. height: height,
  22215. radialSegments: radialSegments,
  22216. heightSegments: heightSegments,
  22217. openEnded: openEnded,
  22218. thetaStart: thetaStart,
  22219. thetaLength: thetaLength
  22220. };
  22221. }
  22222. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  22223. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  22224. /**
  22225. * @author benaadams / https://twitter.com/ben_a_adams
  22226. * @author Mugen87 / https://github.com/Mugen87
  22227. * @author hughes
  22228. */
  22229. // CircleGeometry
  22230. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  22231. Geometry.call( this );
  22232. this.type = 'CircleGeometry';
  22233. this.parameters = {
  22234. radius: radius,
  22235. segments: segments,
  22236. thetaStart: thetaStart,
  22237. thetaLength: thetaLength
  22238. };
  22239. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  22240. this.mergeVertices();
  22241. }
  22242. CircleGeometry.prototype = Object.create( Geometry.prototype );
  22243. CircleGeometry.prototype.constructor = CircleGeometry;
  22244. // CircleBufferGeometry
  22245. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  22246. BufferGeometry.call( this );
  22247. this.type = 'CircleBufferGeometry';
  22248. this.parameters = {
  22249. radius: radius,
  22250. segments: segments,
  22251. thetaStart: thetaStart,
  22252. thetaLength: thetaLength
  22253. };
  22254. radius = radius || 1;
  22255. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  22256. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  22257. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  22258. // buffers
  22259. var indices = [];
  22260. var vertices = [];
  22261. var normals = [];
  22262. var uvs = [];
  22263. // helper variables
  22264. var i, s;
  22265. var vertex = new Vector3();
  22266. var uv = new Vector2();
  22267. // center point
  22268. vertices.push( 0, 0, 0 );
  22269. normals.push( 0, 0, 1 );
  22270. uvs.push( 0.5, 0.5 );
  22271. for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22272. var segment = thetaStart + s / segments * thetaLength;
  22273. // vertex
  22274. vertex.x = radius * Math.cos( segment );
  22275. vertex.y = radius * Math.sin( segment );
  22276. vertices.push( vertex.x, vertex.y, vertex.z );
  22277. // normal
  22278. normals.push( 0, 0, 1 );
  22279. // uvs
  22280. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22281. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22282. uvs.push( uv.x, uv.y );
  22283. }
  22284. // indices
  22285. for ( i = 1; i <= segments; i ++ ) {
  22286. indices.push( i, i + 1, 0 );
  22287. }
  22288. // build geometry
  22289. this.setIndex( indices );
  22290. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22291. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22292. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22293. }
  22294. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22295. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  22296. var Geometries = Object.freeze({
  22297. WireframeGeometry: WireframeGeometry,
  22298. ParametricGeometry: ParametricGeometry,
  22299. ParametricBufferGeometry: ParametricBufferGeometry,
  22300. TetrahedronGeometry: TetrahedronGeometry,
  22301. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  22302. OctahedronGeometry: OctahedronGeometry,
  22303. OctahedronBufferGeometry: OctahedronBufferGeometry,
  22304. IcosahedronGeometry: IcosahedronGeometry,
  22305. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  22306. DodecahedronGeometry: DodecahedronGeometry,
  22307. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  22308. PolyhedronGeometry: PolyhedronGeometry,
  22309. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  22310. TubeGeometry: TubeGeometry,
  22311. TubeBufferGeometry: TubeBufferGeometry,
  22312. TorusKnotGeometry: TorusKnotGeometry,
  22313. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  22314. TorusGeometry: TorusGeometry,
  22315. TorusBufferGeometry: TorusBufferGeometry,
  22316. TextGeometry: TextGeometry,
  22317. TextBufferGeometry: TextBufferGeometry,
  22318. SphereGeometry: SphereGeometry,
  22319. SphereBufferGeometry: SphereBufferGeometry,
  22320. RingGeometry: RingGeometry,
  22321. RingBufferGeometry: RingBufferGeometry,
  22322. PlaneGeometry: PlaneGeometry,
  22323. PlaneBufferGeometry: PlaneBufferGeometry,
  22324. LatheGeometry: LatheGeometry,
  22325. LatheBufferGeometry: LatheBufferGeometry,
  22326. ShapeGeometry: ShapeGeometry,
  22327. ShapeBufferGeometry: ShapeBufferGeometry,
  22328. ExtrudeGeometry: ExtrudeGeometry,
  22329. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  22330. EdgesGeometry: EdgesGeometry,
  22331. ConeGeometry: ConeGeometry,
  22332. ConeBufferGeometry: ConeBufferGeometry,
  22333. CylinderGeometry: CylinderGeometry,
  22334. CylinderBufferGeometry: CylinderBufferGeometry,
  22335. CircleGeometry: CircleGeometry,
  22336. CircleBufferGeometry: CircleBufferGeometry,
  22337. BoxGeometry: BoxGeometry,
  22338. BoxBufferGeometry: BoxBufferGeometry
  22339. });
  22340. /**
  22341. * @author mrdoob / http://mrdoob.com/
  22342. *
  22343. * parameters = {
  22344. * color: <THREE.Color>
  22345. * }
  22346. */
  22347. function ShadowMaterial( parameters ) {
  22348. Material.call( this );
  22349. this.type = 'ShadowMaterial';
  22350. this.color = new Color( 0x000000 );
  22351. this.transparent = true;
  22352. this.setValues( parameters );
  22353. }
  22354. ShadowMaterial.prototype = Object.create( Material.prototype );
  22355. ShadowMaterial.prototype.constructor = ShadowMaterial;
  22356. ShadowMaterial.prototype.isShadowMaterial = true;
  22357. ShadowMaterial.prototype.copy = function ( source ) {
  22358. Material.prototype.copy.call( this, source );
  22359. this.color.copy( source.color );
  22360. return this;
  22361. };
  22362. /**
  22363. * @author mrdoob / http://mrdoob.com/
  22364. */
  22365. function RawShaderMaterial( parameters ) {
  22366. ShaderMaterial.call( this, parameters );
  22367. this.type = 'RawShaderMaterial';
  22368. }
  22369. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  22370. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  22371. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  22372. /**
  22373. * @author WestLangley / http://github.com/WestLangley
  22374. *
  22375. * parameters = {
  22376. * color: <hex>,
  22377. * roughness: <float>,
  22378. * metalness: <float>,
  22379. * opacity: <float>,
  22380. *
  22381. * map: new THREE.Texture( <Image> ),
  22382. *
  22383. * lightMap: new THREE.Texture( <Image> ),
  22384. * lightMapIntensity: <float>
  22385. *
  22386. * aoMap: new THREE.Texture( <Image> ),
  22387. * aoMapIntensity: <float>
  22388. *
  22389. * emissive: <hex>,
  22390. * emissiveIntensity: <float>
  22391. * emissiveMap: new THREE.Texture( <Image> ),
  22392. *
  22393. * bumpMap: new THREE.Texture( <Image> ),
  22394. * bumpScale: <float>,
  22395. *
  22396. * normalMap: new THREE.Texture( <Image> ),
  22397. * normalMapType: THREE.TangentSpaceNormalMap,
  22398. * normalScale: <Vector2>,
  22399. *
  22400. * displacementMap: new THREE.Texture( <Image> ),
  22401. * displacementScale: <float>,
  22402. * displacementBias: <float>,
  22403. *
  22404. * roughnessMap: new THREE.Texture( <Image> ),
  22405. *
  22406. * metalnessMap: new THREE.Texture( <Image> ),
  22407. *
  22408. * alphaMap: new THREE.Texture( <Image> ),
  22409. *
  22410. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  22411. * envMapIntensity: <float>
  22412. *
  22413. * refractionRatio: <float>,
  22414. *
  22415. * wireframe: <boolean>,
  22416. * wireframeLinewidth: <float>,
  22417. *
  22418. * skinning: <bool>,
  22419. * morphTargets: <bool>,
  22420. * morphNormals: <bool>
  22421. * }
  22422. */
  22423. function MeshStandardMaterial( parameters ) {
  22424. Material.call( this );
  22425. this.defines = { 'STANDARD': '' };
  22426. this.type = 'MeshStandardMaterial';
  22427. this.color = new Color( 0xffffff ); // diffuse
  22428. this.roughness = 0.5;
  22429. this.metalness = 0.5;
  22430. this.map = null;
  22431. this.lightMap = null;
  22432. this.lightMapIntensity = 1.0;
  22433. this.aoMap = null;
  22434. this.aoMapIntensity = 1.0;
  22435. this.emissive = new Color( 0x000000 );
  22436. this.emissiveIntensity = 1.0;
  22437. this.emissiveMap = null;
  22438. this.bumpMap = null;
  22439. this.bumpScale = 1;
  22440. this.normalMap = null;
  22441. this.normalMapType = TangentSpaceNormalMap;
  22442. this.normalScale = new Vector2( 1, 1 );
  22443. this.displacementMap = null;
  22444. this.displacementScale = 1;
  22445. this.displacementBias = 0;
  22446. this.roughnessMap = null;
  22447. this.metalnessMap = null;
  22448. this.alphaMap = null;
  22449. this.envMap = null;
  22450. this.envMapIntensity = 1.0;
  22451. this.refractionRatio = 0.98;
  22452. this.wireframe = false;
  22453. this.wireframeLinewidth = 1;
  22454. this.wireframeLinecap = 'round';
  22455. this.wireframeLinejoin = 'round';
  22456. this.skinning = false;
  22457. this.morphTargets = false;
  22458. this.morphNormals = false;
  22459. this.setValues( parameters );
  22460. }
  22461. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  22462. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  22463. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  22464. MeshStandardMaterial.prototype.copy = function ( source ) {
  22465. Material.prototype.copy.call( this, source );
  22466. this.defines = { 'STANDARD': '' };
  22467. this.color.copy( source.color );
  22468. this.roughness = source.roughness;
  22469. this.metalness = source.metalness;
  22470. this.map = source.map;
  22471. this.lightMap = source.lightMap;
  22472. this.lightMapIntensity = source.lightMapIntensity;
  22473. this.aoMap = source.aoMap;
  22474. this.aoMapIntensity = source.aoMapIntensity;
  22475. this.emissive.copy( source.emissive );
  22476. this.emissiveMap = source.emissiveMap;
  22477. this.emissiveIntensity = source.emissiveIntensity;
  22478. this.bumpMap = source.bumpMap;
  22479. this.bumpScale = source.bumpScale;
  22480. this.normalMap = source.normalMap;
  22481. this.normalMapType = source.normalMapType;
  22482. this.normalScale.copy( source.normalScale );
  22483. this.displacementMap = source.displacementMap;
  22484. this.displacementScale = source.displacementScale;
  22485. this.displacementBias = source.displacementBias;
  22486. this.roughnessMap = source.roughnessMap;
  22487. this.metalnessMap = source.metalnessMap;
  22488. this.alphaMap = source.alphaMap;
  22489. this.envMap = source.envMap;
  22490. this.envMapIntensity = source.envMapIntensity;
  22491. this.refractionRatio = source.refractionRatio;
  22492. this.wireframe = source.wireframe;
  22493. this.wireframeLinewidth = source.wireframeLinewidth;
  22494. this.wireframeLinecap = source.wireframeLinecap;
  22495. this.wireframeLinejoin = source.wireframeLinejoin;
  22496. this.skinning = source.skinning;
  22497. this.morphTargets = source.morphTargets;
  22498. this.morphNormals = source.morphNormals;
  22499. return this;
  22500. };
  22501. /**
  22502. * @author WestLangley / http://github.com/WestLangley
  22503. *
  22504. * parameters = {
  22505. * reflectivity: <float>
  22506. * }
  22507. */
  22508. function MeshPhysicalMaterial( parameters ) {
  22509. MeshStandardMaterial.call( this );
  22510. this.defines = { 'PHYSICAL': '' };
  22511. this.type = 'MeshPhysicalMaterial';
  22512. this.reflectivity = 0.5; // maps to F0 = 0.04
  22513. this.clearCoat = 0.0;
  22514. this.clearCoatRoughness = 0.0;
  22515. this.setValues( parameters );
  22516. }
  22517. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  22518. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  22519. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  22520. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  22521. MeshStandardMaterial.prototype.copy.call( this, source );
  22522. this.defines = { 'PHYSICAL': '' };
  22523. this.reflectivity = source.reflectivity;
  22524. this.clearCoat = source.clearCoat;
  22525. this.clearCoatRoughness = source.clearCoatRoughness;
  22526. return this;
  22527. };
  22528. /**
  22529. * @author mrdoob / http://mrdoob.com/
  22530. * @author alteredq / http://alteredqualia.com/
  22531. *
  22532. * parameters = {
  22533. * color: <hex>,
  22534. * specular: <hex>,
  22535. * shininess: <float>,
  22536. * opacity: <float>,
  22537. *
  22538. * map: new THREE.Texture( <Image> ),
  22539. *
  22540. * lightMap: new THREE.Texture( <Image> ),
  22541. * lightMapIntensity: <float>
  22542. *
  22543. * aoMap: new THREE.Texture( <Image> ),
  22544. * aoMapIntensity: <float>
  22545. *
  22546. * emissive: <hex>,
  22547. * emissiveIntensity: <float>
  22548. * emissiveMap: new THREE.Texture( <Image> ),
  22549. *
  22550. * bumpMap: new THREE.Texture( <Image> ),
  22551. * bumpScale: <float>,
  22552. *
  22553. * normalMap: new THREE.Texture( <Image> ),
  22554. * normalMapType: THREE.TangentSpaceNormalMap,
  22555. * normalScale: <Vector2>,
  22556. *
  22557. * displacementMap: new THREE.Texture( <Image> ),
  22558. * displacementScale: <float>,
  22559. * displacementBias: <float>,
  22560. *
  22561. * specularMap: new THREE.Texture( <Image> ),
  22562. *
  22563. * alphaMap: new THREE.Texture( <Image> ),
  22564. *
  22565. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  22566. * combine: THREE.Multiply,
  22567. * reflectivity: <float>,
  22568. * refractionRatio: <float>,
  22569. *
  22570. * wireframe: <boolean>,
  22571. * wireframeLinewidth: <float>,
  22572. *
  22573. * skinning: <bool>,
  22574. * morphTargets: <bool>,
  22575. * morphNormals: <bool>
  22576. * }
  22577. */
  22578. function MeshPhongMaterial( parameters ) {
  22579. Material.call( this );
  22580. this.type = 'MeshPhongMaterial';
  22581. this.color = new Color( 0xffffff ); // diffuse
  22582. this.specular = new Color( 0x111111 );
  22583. this.shininess = 30;
  22584. this.map = null;
  22585. this.lightMap = null;
  22586. this.lightMapIntensity = 1.0;
  22587. this.aoMap = null;
  22588. this.aoMapIntensity = 1.0;
  22589. this.emissive = new Color( 0x000000 );
  22590. this.emissiveIntensity = 1.0;
  22591. this.emissiveMap = null;
  22592. this.bumpMap = null;
  22593. this.bumpScale = 1;
  22594. this.normalMap = null;
  22595. this.normalMapType = TangentSpaceNormalMap;
  22596. this.normalScale = new Vector2( 1, 1 );
  22597. this.displacementMap = null;
  22598. this.displacementScale = 1;
  22599. this.displacementBias = 0;
  22600. this.specularMap = null;
  22601. this.alphaMap = null;
  22602. this.envMap = null;
  22603. this.combine = MultiplyOperation;
  22604. this.reflectivity = 1;
  22605. this.refractionRatio = 0.98;
  22606. this.wireframe = false;
  22607. this.wireframeLinewidth = 1;
  22608. this.wireframeLinecap = 'round';
  22609. this.wireframeLinejoin = 'round';
  22610. this.skinning = false;
  22611. this.morphTargets = false;
  22612. this.morphNormals = false;
  22613. this.setValues( parameters );
  22614. }
  22615. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  22616. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  22617. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  22618. MeshPhongMaterial.prototype.copy = function ( source ) {
  22619. Material.prototype.copy.call( this, source );
  22620. this.color.copy( source.color );
  22621. this.specular.copy( source.specular );
  22622. this.shininess = source.shininess;
  22623. this.map = source.map;
  22624. this.lightMap = source.lightMap;
  22625. this.lightMapIntensity = source.lightMapIntensity;
  22626. this.aoMap = source.aoMap;
  22627. this.aoMapIntensity = source.aoMapIntensity;
  22628. this.emissive.copy( source.emissive );
  22629. this.emissiveMap = source.emissiveMap;
  22630. this.emissiveIntensity = source.emissiveIntensity;
  22631. this.bumpMap = source.bumpMap;
  22632. this.bumpScale = source.bumpScale;
  22633. this.normalMap = source.normalMap;
  22634. this.normalMapType = source.normalMapType;
  22635. this.normalScale.copy( source.normalScale );
  22636. this.displacementMap = source.displacementMap;
  22637. this.displacementScale = source.displacementScale;
  22638. this.displacementBias = source.displacementBias;
  22639. this.specularMap = source.specularMap;
  22640. this.alphaMap = source.alphaMap;
  22641. this.envMap = source.envMap;
  22642. this.combine = source.combine;
  22643. this.reflectivity = source.reflectivity;
  22644. this.refractionRatio = source.refractionRatio;
  22645. this.wireframe = source.wireframe;
  22646. this.wireframeLinewidth = source.wireframeLinewidth;
  22647. this.wireframeLinecap = source.wireframeLinecap;
  22648. this.wireframeLinejoin = source.wireframeLinejoin;
  22649. this.skinning = source.skinning;
  22650. this.morphTargets = source.morphTargets;
  22651. this.morphNormals = source.morphNormals;
  22652. return this;
  22653. };
  22654. /**
  22655. * @author takahirox / http://github.com/takahirox
  22656. *
  22657. * parameters = {
  22658. * gradientMap: new THREE.Texture( <Image> )
  22659. * }
  22660. */
  22661. function MeshToonMaterial( parameters ) {
  22662. MeshPhongMaterial.call( this );
  22663. this.defines = { 'TOON': '' };
  22664. this.type = 'MeshToonMaterial';
  22665. this.gradientMap = null;
  22666. this.setValues( parameters );
  22667. }
  22668. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  22669. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  22670. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  22671. MeshToonMaterial.prototype.copy = function ( source ) {
  22672. MeshPhongMaterial.prototype.copy.call( this, source );
  22673. this.gradientMap = source.gradientMap;
  22674. return this;
  22675. };
  22676. /**
  22677. * @author mrdoob / http://mrdoob.com/
  22678. * @author WestLangley / http://github.com/WestLangley
  22679. *
  22680. * parameters = {
  22681. * opacity: <float>,
  22682. *
  22683. * bumpMap: new THREE.Texture( <Image> ),
  22684. * bumpScale: <float>,
  22685. *
  22686. * normalMap: new THREE.Texture( <Image> ),
  22687. * normalMapType: THREE.TangentSpaceNormalMap,
  22688. * normalScale: <Vector2>,
  22689. *
  22690. * displacementMap: new THREE.Texture( <Image> ),
  22691. * displacementScale: <float>,
  22692. * displacementBias: <float>,
  22693. *
  22694. * wireframe: <boolean>,
  22695. * wireframeLinewidth: <float>
  22696. *
  22697. * skinning: <bool>,
  22698. * morphTargets: <bool>,
  22699. * morphNormals: <bool>
  22700. * }
  22701. */
  22702. function MeshNormalMaterial( parameters ) {
  22703. Material.call( this );
  22704. this.type = 'MeshNormalMaterial';
  22705. this.bumpMap = null;
  22706. this.bumpScale = 1;
  22707. this.normalMap = null;
  22708. this.normalMapType = TangentSpaceNormalMap;
  22709. this.normalScale = new Vector2( 1, 1 );
  22710. this.displacementMap = null;
  22711. this.displacementScale = 1;
  22712. this.displacementBias = 0;
  22713. this.wireframe = false;
  22714. this.wireframeLinewidth = 1;
  22715. this.fog = false;
  22716. this.lights = false;
  22717. this.skinning = false;
  22718. this.morphTargets = false;
  22719. this.morphNormals = false;
  22720. this.setValues( parameters );
  22721. }
  22722. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  22723. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  22724. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  22725. MeshNormalMaterial.prototype.copy = function ( source ) {
  22726. Material.prototype.copy.call( this, source );
  22727. this.bumpMap = source.bumpMap;
  22728. this.bumpScale = source.bumpScale;
  22729. this.normalMap = source.normalMap;
  22730. this.normalMapType = source.normalMapType;
  22731. this.normalScale.copy( source.normalScale );
  22732. this.displacementMap = source.displacementMap;
  22733. this.displacementScale = source.displacementScale;
  22734. this.displacementBias = source.displacementBias;
  22735. this.wireframe = source.wireframe;
  22736. this.wireframeLinewidth = source.wireframeLinewidth;
  22737. this.skinning = source.skinning;
  22738. this.morphTargets = source.morphTargets;
  22739. this.morphNormals = source.morphNormals;
  22740. return this;
  22741. };
  22742. /**
  22743. * @author mrdoob / http://mrdoob.com/
  22744. * @author alteredq / http://alteredqualia.com/
  22745. *
  22746. * parameters = {
  22747. * color: <hex>,
  22748. * opacity: <float>,
  22749. *
  22750. * map: new THREE.Texture( <Image> ),
  22751. *
  22752. * lightMap: new THREE.Texture( <Image> ),
  22753. * lightMapIntensity: <float>
  22754. *
  22755. * aoMap: new THREE.Texture( <Image> ),
  22756. * aoMapIntensity: <float>
  22757. *
  22758. * emissive: <hex>,
  22759. * emissiveIntensity: <float>
  22760. * emissiveMap: new THREE.Texture( <Image> ),
  22761. *
  22762. * specularMap: new THREE.Texture( <Image> ),
  22763. *
  22764. * alphaMap: new THREE.Texture( <Image> ),
  22765. *
  22766. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  22767. * combine: THREE.Multiply,
  22768. * reflectivity: <float>,
  22769. * refractionRatio: <float>,
  22770. *
  22771. * wireframe: <boolean>,
  22772. * wireframeLinewidth: <float>,
  22773. *
  22774. * skinning: <bool>,
  22775. * morphTargets: <bool>,
  22776. * morphNormals: <bool>
  22777. * }
  22778. */
  22779. function MeshLambertMaterial( parameters ) {
  22780. Material.call( this );
  22781. this.type = 'MeshLambertMaterial';
  22782. this.color = new Color( 0xffffff ); // diffuse
  22783. this.map = null;
  22784. this.lightMap = null;
  22785. this.lightMapIntensity = 1.0;
  22786. this.aoMap = null;
  22787. this.aoMapIntensity = 1.0;
  22788. this.emissive = new Color( 0x000000 );
  22789. this.emissiveIntensity = 1.0;
  22790. this.emissiveMap = null;
  22791. this.specularMap = null;
  22792. this.alphaMap = null;
  22793. this.envMap = null;
  22794. this.combine = MultiplyOperation;
  22795. this.reflectivity = 1;
  22796. this.refractionRatio = 0.98;
  22797. this.wireframe = false;
  22798. this.wireframeLinewidth = 1;
  22799. this.wireframeLinecap = 'round';
  22800. this.wireframeLinejoin = 'round';
  22801. this.skinning = false;
  22802. this.morphTargets = false;
  22803. this.morphNormals = false;
  22804. this.setValues( parameters );
  22805. }
  22806. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  22807. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  22808. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  22809. MeshLambertMaterial.prototype.copy = function ( source ) {
  22810. Material.prototype.copy.call( this, source );
  22811. this.color.copy( source.color );
  22812. this.map = source.map;
  22813. this.lightMap = source.lightMap;
  22814. this.lightMapIntensity = source.lightMapIntensity;
  22815. this.aoMap = source.aoMap;
  22816. this.aoMapIntensity = source.aoMapIntensity;
  22817. this.emissive.copy( source.emissive );
  22818. this.emissiveMap = source.emissiveMap;
  22819. this.emissiveIntensity = source.emissiveIntensity;
  22820. this.specularMap = source.specularMap;
  22821. this.alphaMap = source.alphaMap;
  22822. this.envMap = source.envMap;
  22823. this.combine = source.combine;
  22824. this.reflectivity = source.reflectivity;
  22825. this.refractionRatio = source.refractionRatio;
  22826. this.wireframe = source.wireframe;
  22827. this.wireframeLinewidth = source.wireframeLinewidth;
  22828. this.wireframeLinecap = source.wireframeLinecap;
  22829. this.wireframeLinejoin = source.wireframeLinejoin;
  22830. this.skinning = source.skinning;
  22831. this.morphTargets = source.morphTargets;
  22832. this.morphNormals = source.morphNormals;
  22833. return this;
  22834. };
  22835. /**
  22836. * @author WestLangley / http://github.com/WestLangley
  22837. *
  22838. * parameters = {
  22839. * color: <hex>,
  22840. * opacity: <float>,
  22841. *
  22842. * matcap: new THREE.Texture( <Image> ),
  22843. *
  22844. * map: new THREE.Texture( <Image> ),
  22845. *
  22846. * bumpMap: new THREE.Texture( <Image> ),
  22847. * bumpScale: <float>,
  22848. *
  22849. * normalMap: new THREE.Texture( <Image> ),
  22850. * normalMapType: THREE.TangentSpaceNormalMap,
  22851. * normalScale: <Vector2>,
  22852. *
  22853. * displacementMap: new THREE.Texture( <Image> ),
  22854. * displacementScale: <float>,
  22855. * displacementBias: <float>,
  22856. *
  22857. * alphaMap: new THREE.Texture( <Image> ),
  22858. *
  22859. * skinning: <bool>,
  22860. * morphTargets: <bool>,
  22861. * morphNormals: <bool>
  22862. * }
  22863. */
  22864. function MeshMatcapMaterial( parameters ) {
  22865. Material.call( this );
  22866. this.defines = { 'MATCAP': '' };
  22867. this.type = 'MeshMatcapMaterial';
  22868. this.color = new Color( 0xffffff ); // diffuse
  22869. this.matcap = null;
  22870. this.map = null;
  22871. this.bumpMap = null;
  22872. this.bumpScale = 1;
  22873. this.normalMap = null;
  22874. this.normalMapType = TangentSpaceNormalMap;
  22875. this.normalScale = new Vector2( 1, 1 );
  22876. this.displacementMap = null;
  22877. this.displacementScale = 1;
  22878. this.displacementBias = 0;
  22879. this.alphaMap = null;
  22880. this.skinning = false;
  22881. this.morphTargets = false;
  22882. this.morphNormals = false;
  22883. this.lights = false;
  22884. this.setValues( parameters );
  22885. // a matcap is required
  22886. if ( this.matcap === null ) {
  22887. var canvas = document.createElement( 'canvas' );
  22888. canvas.width = 1;
  22889. canvas.height = 1;
  22890. var context = canvas.getContext( '2d' );
  22891. context.fillStyle = '#fff';
  22892. context.fillRect( 0, 0, 1, 1 );
  22893. this.matcap = new THREE.CanvasTexture( canvas );
  22894. }
  22895. }
  22896. MeshMatcapMaterial.prototype = Object.create( Material.prototype );
  22897. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  22898. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  22899. MeshMatcapMaterial.prototype.copy = function ( source ) {
  22900. Material.prototype.copy.call( this, source );
  22901. this.defines = { 'MATCAP': '' };
  22902. this.color.copy( source.color );
  22903. this.matcap = source.matcap;
  22904. this.map = source.map;
  22905. this.bumpMap = source.bumpMap;
  22906. this.bumpScale = source.bumpScale;
  22907. this.normalMap = source.normalMap;
  22908. this.normalMapType = source.normalMapType;
  22909. this.normalScale.copy( source.normalScale );
  22910. this.displacementMap = source.displacementMap;
  22911. this.displacementScale = source.displacementScale;
  22912. this.displacementBias = source.displacementBias;
  22913. this.alphaMap = source.alphaMap;
  22914. this.skinning = source.skinning;
  22915. this.morphTargets = source.morphTargets;
  22916. this.morphNormals = source.morphNormals;
  22917. return this;
  22918. };
  22919. /**
  22920. * @author alteredq / http://alteredqualia.com/
  22921. *
  22922. * parameters = {
  22923. * color: <hex>,
  22924. * opacity: <float>,
  22925. *
  22926. * linewidth: <float>,
  22927. *
  22928. * scale: <float>,
  22929. * dashSize: <float>,
  22930. * gapSize: <float>
  22931. * }
  22932. */
  22933. function LineDashedMaterial( parameters ) {
  22934. LineBasicMaterial.call( this );
  22935. this.type = 'LineDashedMaterial';
  22936. this.scale = 1;
  22937. this.dashSize = 3;
  22938. this.gapSize = 1;
  22939. this.setValues( parameters );
  22940. }
  22941. LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype );
  22942. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  22943. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  22944. LineDashedMaterial.prototype.copy = function ( source ) {
  22945. LineBasicMaterial.prototype.copy.call( this, source );
  22946. this.scale = source.scale;
  22947. this.dashSize = source.dashSize;
  22948. this.gapSize = source.gapSize;
  22949. return this;
  22950. };
  22951. var Materials = Object.freeze({
  22952. ShadowMaterial: ShadowMaterial,
  22953. SpriteMaterial: SpriteMaterial,
  22954. RawShaderMaterial: RawShaderMaterial,
  22955. ShaderMaterial: ShaderMaterial,
  22956. PointsMaterial: PointsMaterial,
  22957. MeshPhysicalMaterial: MeshPhysicalMaterial,
  22958. MeshStandardMaterial: MeshStandardMaterial,
  22959. MeshPhongMaterial: MeshPhongMaterial,
  22960. MeshToonMaterial: MeshToonMaterial,
  22961. MeshNormalMaterial: MeshNormalMaterial,
  22962. MeshLambertMaterial: MeshLambertMaterial,
  22963. MeshDepthMaterial: MeshDepthMaterial,
  22964. MeshDistanceMaterial: MeshDistanceMaterial,
  22965. MeshBasicMaterial: MeshBasicMaterial,
  22966. MeshMatcapMaterial: MeshMatcapMaterial,
  22967. LineDashedMaterial: LineDashedMaterial,
  22968. LineBasicMaterial: LineBasicMaterial,
  22969. Material: Material
  22970. });
  22971. /**
  22972. * @author tschw
  22973. * @author Ben Houston / http://clara.io/
  22974. * @author David Sarno / http://lighthaus.us/
  22975. */
  22976. var AnimationUtils = {
  22977. // same as Array.prototype.slice, but also works on typed arrays
  22978. arraySlice: function ( array, from, to ) {
  22979. if ( AnimationUtils.isTypedArray( array ) ) {
  22980. // in ios9 array.subarray(from, undefined) will return empty array
  22981. // but array.subarray(from) or array.subarray(from, len) is correct
  22982. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  22983. }
  22984. return array.slice( from, to );
  22985. },
  22986. // converts an array to a specific type
  22987. convertArray: function ( array, type, forceClone ) {
  22988. if ( ! array || // let 'undefined' and 'null' pass
  22989. ! forceClone && array.constructor === type ) return array;
  22990. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  22991. return new type( array ); // create typed array
  22992. }
  22993. return Array.prototype.slice.call( array ); // create Array
  22994. },
  22995. isTypedArray: function ( object ) {
  22996. return ArrayBuffer.isView( object ) &&
  22997. ! ( object instanceof DataView );
  22998. },
  22999. // returns an array by which times and values can be sorted
  23000. getKeyframeOrder: function ( times ) {
  23001. function compareTime( i, j ) {
  23002. return times[ i ] - times[ j ];
  23003. }
  23004. var n = times.length;
  23005. var result = new Array( n );
  23006. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  23007. result.sort( compareTime );
  23008. return result;
  23009. },
  23010. // uses the array previously returned by 'getKeyframeOrder' to sort data
  23011. sortedArray: function ( values, stride, order ) {
  23012. var nValues = values.length;
  23013. var result = new values.constructor( nValues );
  23014. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  23015. var srcOffset = order[ i ] * stride;
  23016. for ( var j = 0; j !== stride; ++ j ) {
  23017. result[ dstOffset ++ ] = values[ srcOffset + j ];
  23018. }
  23019. }
  23020. return result;
  23021. },
  23022. // function for parsing AOS keyframe formats
  23023. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  23024. var i = 1, key = jsonKeys[ 0 ];
  23025. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  23026. key = jsonKeys[ i ++ ];
  23027. }
  23028. if ( key === undefined ) return; // no data
  23029. var value = key[ valuePropertyName ];
  23030. if ( value === undefined ) return; // no data
  23031. if ( Array.isArray( value ) ) {
  23032. do {
  23033. value = key[ valuePropertyName ];
  23034. if ( value !== undefined ) {
  23035. times.push( key.time );
  23036. values.push.apply( values, value ); // push all elements
  23037. }
  23038. key = jsonKeys[ i ++ ];
  23039. } while ( key !== undefined );
  23040. } else if ( value.toArray !== undefined ) {
  23041. // ...assume THREE.Math-ish
  23042. do {
  23043. value = key[ valuePropertyName ];
  23044. if ( value !== undefined ) {
  23045. times.push( key.time );
  23046. value.toArray( values, values.length );
  23047. }
  23048. key = jsonKeys[ i ++ ];
  23049. } while ( key !== undefined );
  23050. } else {
  23051. // otherwise push as-is
  23052. do {
  23053. value = key[ valuePropertyName ];
  23054. if ( value !== undefined ) {
  23055. times.push( key.time );
  23056. values.push( value );
  23057. }
  23058. key = jsonKeys[ i ++ ];
  23059. } while ( key !== undefined );
  23060. }
  23061. }
  23062. };
  23063. /**
  23064. * Abstract base class of interpolants over parametric samples.
  23065. *
  23066. * The parameter domain is one dimensional, typically the time or a path
  23067. * along a curve defined by the data.
  23068. *
  23069. * The sample values can have any dimensionality and derived classes may
  23070. * apply special interpretations to the data.
  23071. *
  23072. * This class provides the interval seek in a Template Method, deferring
  23073. * the actual interpolation to derived classes.
  23074. *
  23075. * Time complexity is O(1) for linear access crossing at most two points
  23076. * and O(log N) for random access, where N is the number of positions.
  23077. *
  23078. * References:
  23079. *
  23080. * http://www.oodesign.com/template-method-pattern.html
  23081. *
  23082. * @author tschw
  23083. */
  23084. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23085. this.parameterPositions = parameterPositions;
  23086. this._cachedIndex = 0;
  23087. this.resultBuffer = resultBuffer !== undefined ?
  23088. resultBuffer : new sampleValues.constructor( sampleSize );
  23089. this.sampleValues = sampleValues;
  23090. this.valueSize = sampleSize;
  23091. }
  23092. Object.assign( Interpolant.prototype, {
  23093. evaluate: function ( t ) {
  23094. var pp = this.parameterPositions,
  23095. i1 = this._cachedIndex,
  23096. t1 = pp[ i1 ],
  23097. t0 = pp[ i1 - 1 ];
  23098. validate_interval: {
  23099. seek: {
  23100. var right;
  23101. linear_scan: {
  23102. //- See http://jsperf.com/comparison-to-undefined/3
  23103. //- slower code:
  23104. //-
  23105. //- if ( t >= t1 || t1 === undefined ) {
  23106. forward_scan: if ( ! ( t < t1 ) ) {
  23107. for ( var giveUpAt = i1 + 2; ; ) {
  23108. if ( t1 === undefined ) {
  23109. if ( t < t0 ) break forward_scan;
  23110. // after end
  23111. i1 = pp.length;
  23112. this._cachedIndex = i1;
  23113. return this.afterEnd_( i1 - 1, t, t0 );
  23114. }
  23115. if ( i1 === giveUpAt ) break; // this loop
  23116. t0 = t1;
  23117. t1 = pp[ ++ i1 ];
  23118. if ( t < t1 ) {
  23119. // we have arrived at the sought interval
  23120. break seek;
  23121. }
  23122. }
  23123. // prepare binary search on the right side of the index
  23124. right = pp.length;
  23125. break linear_scan;
  23126. }
  23127. //- slower code:
  23128. //- if ( t < t0 || t0 === undefined ) {
  23129. if ( ! ( t >= t0 ) ) {
  23130. // looping?
  23131. var t1global = pp[ 1 ];
  23132. if ( t < t1global ) {
  23133. i1 = 2; // + 1, using the scan for the details
  23134. t0 = t1global;
  23135. }
  23136. // linear reverse scan
  23137. for ( var giveUpAt = i1 - 2; ; ) {
  23138. if ( t0 === undefined ) {
  23139. // before start
  23140. this._cachedIndex = 0;
  23141. return this.beforeStart_( 0, t, t1 );
  23142. }
  23143. if ( i1 === giveUpAt ) break; // this loop
  23144. t1 = t0;
  23145. t0 = pp[ -- i1 - 1 ];
  23146. if ( t >= t0 ) {
  23147. // we have arrived at the sought interval
  23148. break seek;
  23149. }
  23150. }
  23151. // prepare binary search on the left side of the index
  23152. right = i1;
  23153. i1 = 0;
  23154. break linear_scan;
  23155. }
  23156. // the interval is valid
  23157. break validate_interval;
  23158. } // linear scan
  23159. // binary search
  23160. while ( i1 < right ) {
  23161. var mid = ( i1 + right ) >>> 1;
  23162. if ( t < pp[ mid ] ) {
  23163. right = mid;
  23164. } else {
  23165. i1 = mid + 1;
  23166. }
  23167. }
  23168. t1 = pp[ i1 ];
  23169. t0 = pp[ i1 - 1 ];
  23170. // check boundary cases, again
  23171. if ( t0 === undefined ) {
  23172. this._cachedIndex = 0;
  23173. return this.beforeStart_( 0, t, t1 );
  23174. }
  23175. if ( t1 === undefined ) {
  23176. i1 = pp.length;
  23177. this._cachedIndex = i1;
  23178. return this.afterEnd_( i1 - 1, t0, t );
  23179. }
  23180. } // seek
  23181. this._cachedIndex = i1;
  23182. this.intervalChanged_( i1, t0, t1 );
  23183. } // validate_interval
  23184. return this.interpolate_( i1, t0, t, t1 );
  23185. },
  23186. settings: null, // optional, subclass-specific settings structure
  23187. // Note: The indirection allows central control of many interpolants.
  23188. // --- Protected interface
  23189. DefaultSettings_: {},
  23190. getSettings_: function () {
  23191. return this.settings || this.DefaultSettings_;
  23192. },
  23193. copySampleValue_: function ( index ) {
  23194. // copies a sample value to the result buffer
  23195. var result = this.resultBuffer,
  23196. values = this.sampleValues,
  23197. stride = this.valueSize,
  23198. offset = index * stride;
  23199. for ( var i = 0; i !== stride; ++ i ) {
  23200. result[ i ] = values[ offset + i ];
  23201. }
  23202. return result;
  23203. },
  23204. // Template methods for derived classes:
  23205. interpolate_: function ( /* i1, t0, t, t1 */ ) {
  23206. throw new Error( 'call to abstract method' );
  23207. // implementations shall return this.resultBuffer
  23208. },
  23209. intervalChanged_: function ( /* i1, t0, t1 */ ) {
  23210. // empty
  23211. }
  23212. } );
  23213. //!\ DECLARE ALIAS AFTER assign prototype !
  23214. Object.assign( Interpolant.prototype, {
  23215. //( 0, t, t0 ), returns this.resultBuffer
  23216. beforeStart_: Interpolant.prototype.copySampleValue_,
  23217. //( N-1, tN-1, t ), returns this.resultBuffer
  23218. afterEnd_: Interpolant.prototype.copySampleValue_,
  23219. } );
  23220. /**
  23221. * Fast and simple cubic spline interpolant.
  23222. *
  23223. * It was derived from a Hermitian construction setting the first derivative
  23224. * at each sample position to the linear slope between neighboring positions
  23225. * over their parameter interval.
  23226. *
  23227. * @author tschw
  23228. */
  23229. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23230. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  23231. this._weightPrev = - 0;
  23232. this._offsetPrev = - 0;
  23233. this._weightNext = - 0;
  23234. this._offsetNext = - 0;
  23235. }
  23236. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  23237. constructor: CubicInterpolant,
  23238. DefaultSettings_: {
  23239. endingStart: ZeroCurvatureEnding,
  23240. endingEnd: ZeroCurvatureEnding
  23241. },
  23242. intervalChanged_: function ( i1, t0, t1 ) {
  23243. var pp = this.parameterPositions,
  23244. iPrev = i1 - 2,
  23245. iNext = i1 + 1,
  23246. tPrev = pp[ iPrev ],
  23247. tNext = pp[ iNext ];
  23248. if ( tPrev === undefined ) {
  23249. switch ( this.getSettings_().endingStart ) {
  23250. case ZeroSlopeEnding:
  23251. // f'(t0) = 0
  23252. iPrev = i1;
  23253. tPrev = 2 * t0 - t1;
  23254. break;
  23255. case WrapAroundEnding:
  23256. // use the other end of the curve
  23257. iPrev = pp.length - 2;
  23258. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  23259. break;
  23260. default: // ZeroCurvatureEnding
  23261. // f''(t0) = 0 a.k.a. Natural Spline
  23262. iPrev = i1;
  23263. tPrev = t1;
  23264. }
  23265. }
  23266. if ( tNext === undefined ) {
  23267. switch ( this.getSettings_().endingEnd ) {
  23268. case ZeroSlopeEnding:
  23269. // f'(tN) = 0
  23270. iNext = i1;
  23271. tNext = 2 * t1 - t0;
  23272. break;
  23273. case WrapAroundEnding:
  23274. // use the other end of the curve
  23275. iNext = 1;
  23276. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  23277. break;
  23278. default: // ZeroCurvatureEnding
  23279. // f''(tN) = 0, a.k.a. Natural Spline
  23280. iNext = i1 - 1;
  23281. tNext = t0;
  23282. }
  23283. }
  23284. var halfDt = ( t1 - t0 ) * 0.5,
  23285. stride = this.valueSize;
  23286. this._weightPrev = halfDt / ( t0 - tPrev );
  23287. this._weightNext = halfDt / ( tNext - t1 );
  23288. this._offsetPrev = iPrev * stride;
  23289. this._offsetNext = iNext * stride;
  23290. },
  23291. interpolate_: function ( i1, t0, t, t1 ) {
  23292. var result = this.resultBuffer,
  23293. values = this.sampleValues,
  23294. stride = this.valueSize,
  23295. o1 = i1 * stride, o0 = o1 - stride,
  23296. oP = this._offsetPrev, oN = this._offsetNext,
  23297. wP = this._weightPrev, wN = this._weightNext,
  23298. p = ( t - t0 ) / ( t1 - t0 ),
  23299. pp = p * p,
  23300. ppp = pp * p;
  23301. // evaluate polynomials
  23302. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  23303. var s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  23304. var s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  23305. var sN = wN * ppp - wN * pp;
  23306. // combine data linearly
  23307. for ( var i = 0; i !== stride; ++ i ) {
  23308. result[ i ] =
  23309. sP * values[ oP + i ] +
  23310. s0 * values[ o0 + i ] +
  23311. s1 * values[ o1 + i ] +
  23312. sN * values[ oN + i ];
  23313. }
  23314. return result;
  23315. }
  23316. } );
  23317. /**
  23318. * @author tschw
  23319. */
  23320. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23321. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  23322. }
  23323. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  23324. constructor: LinearInterpolant,
  23325. interpolate_: function ( i1, t0, t, t1 ) {
  23326. var result = this.resultBuffer,
  23327. values = this.sampleValues,
  23328. stride = this.valueSize,
  23329. offset1 = i1 * stride,
  23330. offset0 = offset1 - stride,
  23331. weight1 = ( t - t0 ) / ( t1 - t0 ),
  23332. weight0 = 1 - weight1;
  23333. for ( var i = 0; i !== stride; ++ i ) {
  23334. result[ i ] =
  23335. values[ offset0 + i ] * weight0 +
  23336. values[ offset1 + i ] * weight1;
  23337. }
  23338. return result;
  23339. }
  23340. } );
  23341. /**
  23342. *
  23343. * Interpolant that evaluates to the sample value at the position preceeding
  23344. * the parameter.
  23345. *
  23346. * @author tschw
  23347. */
  23348. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23349. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  23350. }
  23351. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  23352. constructor: DiscreteInterpolant,
  23353. interpolate_: function ( i1 /*, t0, t, t1 */ ) {
  23354. return this.copySampleValue_( i1 - 1 );
  23355. }
  23356. } );
  23357. /**
  23358. *
  23359. * A timed sequence of keyframes for a specific property.
  23360. *
  23361. *
  23362. * @author Ben Houston / http://clara.io/
  23363. * @author David Sarno / http://lighthaus.us/
  23364. * @author tschw
  23365. */
  23366. function KeyframeTrack( name, times, values, interpolation ) {
  23367. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  23368. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  23369. this.name = name;
  23370. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  23371. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  23372. this.setInterpolation( interpolation || this.DefaultInterpolation );
  23373. }
  23374. // Static methods
  23375. Object.assign( KeyframeTrack, {
  23376. // Serialization (in static context, because of constructor invocation
  23377. // and automatic invocation of .toJSON):
  23378. toJSON: function ( track ) {
  23379. var trackType = track.constructor;
  23380. var json;
  23381. // derived classes can define a static toJSON method
  23382. if ( trackType.toJSON !== undefined ) {
  23383. json = trackType.toJSON( track );
  23384. } else {
  23385. // by default, we assume the data can be serialized as-is
  23386. json = {
  23387. 'name': track.name,
  23388. 'times': AnimationUtils.convertArray( track.times, Array ),
  23389. 'values': AnimationUtils.convertArray( track.values, Array )
  23390. };
  23391. var interpolation = track.getInterpolation();
  23392. if ( interpolation !== track.DefaultInterpolation ) {
  23393. json.interpolation = interpolation;
  23394. }
  23395. }
  23396. json.type = track.ValueTypeName; // mandatory
  23397. return json;
  23398. }
  23399. } );
  23400. Object.assign( KeyframeTrack.prototype, {
  23401. constructor: KeyframeTrack,
  23402. TimeBufferType: Float32Array,
  23403. ValueBufferType: Float32Array,
  23404. DefaultInterpolation: InterpolateLinear,
  23405. InterpolantFactoryMethodDiscrete: function ( result ) {
  23406. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  23407. },
  23408. InterpolantFactoryMethodLinear: function ( result ) {
  23409. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23410. },
  23411. InterpolantFactoryMethodSmooth: function ( result ) {
  23412. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  23413. },
  23414. setInterpolation: function ( interpolation ) {
  23415. var factoryMethod;
  23416. switch ( interpolation ) {
  23417. case InterpolateDiscrete:
  23418. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  23419. break;
  23420. case InterpolateLinear:
  23421. factoryMethod = this.InterpolantFactoryMethodLinear;
  23422. break;
  23423. case InterpolateSmooth:
  23424. factoryMethod = this.InterpolantFactoryMethodSmooth;
  23425. break;
  23426. }
  23427. if ( factoryMethod === undefined ) {
  23428. var message = "unsupported interpolation for " +
  23429. this.ValueTypeName + " keyframe track named " + this.name;
  23430. if ( this.createInterpolant === undefined ) {
  23431. // fall back to default, unless the default itself is messed up
  23432. if ( interpolation !== this.DefaultInterpolation ) {
  23433. this.setInterpolation( this.DefaultInterpolation );
  23434. } else {
  23435. throw new Error( message ); // fatal, in this case
  23436. }
  23437. }
  23438. console.warn( 'THREE.KeyframeTrack:', message );
  23439. return this;
  23440. }
  23441. this.createInterpolant = factoryMethod;
  23442. return this;
  23443. },
  23444. getInterpolation: function () {
  23445. switch ( this.createInterpolant ) {
  23446. case this.InterpolantFactoryMethodDiscrete:
  23447. return InterpolateDiscrete;
  23448. case this.InterpolantFactoryMethodLinear:
  23449. return InterpolateLinear;
  23450. case this.InterpolantFactoryMethodSmooth:
  23451. return InterpolateSmooth;
  23452. }
  23453. },
  23454. getValueSize: function () {
  23455. return this.values.length / this.times.length;
  23456. },
  23457. // move all keyframes either forwards or backwards in time
  23458. shift: function ( timeOffset ) {
  23459. if ( timeOffset !== 0.0 ) {
  23460. var times = this.times;
  23461. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  23462. times[ i ] += timeOffset;
  23463. }
  23464. }
  23465. return this;
  23466. },
  23467. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  23468. scale: function ( timeScale ) {
  23469. if ( timeScale !== 1.0 ) {
  23470. var times = this.times;
  23471. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  23472. times[ i ] *= timeScale;
  23473. }
  23474. }
  23475. return this;
  23476. },
  23477. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  23478. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  23479. trim: function ( startTime, endTime ) {
  23480. var times = this.times,
  23481. nKeys = times.length,
  23482. from = 0,
  23483. to = nKeys - 1;
  23484. while ( from !== nKeys && times[ from ] < startTime ) {
  23485. ++ from;
  23486. }
  23487. while ( to !== - 1 && times[ to ] > endTime ) {
  23488. -- to;
  23489. }
  23490. ++ to; // inclusive -> exclusive bound
  23491. if ( from !== 0 || to !== nKeys ) {
  23492. // empty tracks are forbidden, so keep at least one keyframe
  23493. if ( from >= to ) to = Math.max( to, 1 ), from = to - 1;
  23494. var stride = this.getValueSize();
  23495. this.times = AnimationUtils.arraySlice( times, from, to );
  23496. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  23497. }
  23498. return this;
  23499. },
  23500. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  23501. validate: function () {
  23502. var valid = true;
  23503. var valueSize = this.getValueSize();
  23504. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  23505. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  23506. valid = false;
  23507. }
  23508. var times = this.times,
  23509. values = this.values,
  23510. nKeys = times.length;
  23511. if ( nKeys === 0 ) {
  23512. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  23513. valid = false;
  23514. }
  23515. var prevTime = null;
  23516. for ( var i = 0; i !== nKeys; i ++ ) {
  23517. var currTime = times[ i ];
  23518. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  23519. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  23520. valid = false;
  23521. break;
  23522. }
  23523. if ( prevTime !== null && prevTime > currTime ) {
  23524. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  23525. valid = false;
  23526. break;
  23527. }
  23528. prevTime = currTime;
  23529. }
  23530. if ( values !== undefined ) {
  23531. if ( AnimationUtils.isTypedArray( values ) ) {
  23532. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  23533. var value = values[ i ];
  23534. if ( isNaN( value ) ) {
  23535. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  23536. valid = false;
  23537. break;
  23538. }
  23539. }
  23540. }
  23541. }
  23542. return valid;
  23543. },
  23544. // removes equivalent sequential keys as common in morph target sequences
  23545. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  23546. optimize: function () {
  23547. var times = this.times,
  23548. values = this.values,
  23549. stride = this.getValueSize(),
  23550. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  23551. writeIndex = 1,
  23552. lastIndex = times.length - 1;
  23553. for ( var i = 1; i < lastIndex; ++ i ) {
  23554. var keep = false;
  23555. var time = times[ i ];
  23556. var timeNext = times[ i + 1 ];
  23557. // remove adjacent keyframes scheduled at the same time
  23558. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  23559. if ( ! smoothInterpolation ) {
  23560. // remove unnecessary keyframes same as their neighbors
  23561. var offset = i * stride,
  23562. offsetP = offset - stride,
  23563. offsetN = offset + stride;
  23564. for ( var j = 0; j !== stride; ++ j ) {
  23565. var value = values[ offset + j ];
  23566. if ( value !== values[ offsetP + j ] ||
  23567. value !== values[ offsetN + j ] ) {
  23568. keep = true;
  23569. break;
  23570. }
  23571. }
  23572. } else {
  23573. keep = true;
  23574. }
  23575. }
  23576. // in-place compaction
  23577. if ( keep ) {
  23578. if ( i !== writeIndex ) {
  23579. times[ writeIndex ] = times[ i ];
  23580. var readOffset = i * stride,
  23581. writeOffset = writeIndex * stride;
  23582. for ( var j = 0; j !== stride; ++ j ) {
  23583. values[ writeOffset + j ] = values[ readOffset + j ];
  23584. }
  23585. }
  23586. ++ writeIndex;
  23587. }
  23588. }
  23589. // flush last keyframe (compaction looks ahead)
  23590. if ( lastIndex > 0 ) {
  23591. times[ writeIndex ] = times[ lastIndex ];
  23592. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  23593. values[ writeOffset + j ] = values[ readOffset + j ];
  23594. }
  23595. ++ writeIndex;
  23596. }
  23597. if ( writeIndex !== times.length ) {
  23598. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  23599. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  23600. }
  23601. return this;
  23602. }
  23603. } );
  23604. /**
  23605. *
  23606. * A Track of Boolean keyframe values.
  23607. *
  23608. *
  23609. * @author Ben Houston / http://clara.io/
  23610. * @author David Sarno / http://lighthaus.us/
  23611. * @author tschw
  23612. */
  23613. function BooleanKeyframeTrack( name, times, values ) {
  23614. KeyframeTrack.call( this, name, times, values );
  23615. }
  23616. BooleanKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  23617. constructor: BooleanKeyframeTrack,
  23618. ValueTypeName: 'bool',
  23619. ValueBufferType: Array,
  23620. DefaultInterpolation: InterpolateDiscrete,
  23621. InterpolantFactoryMethodLinear: undefined,
  23622. InterpolantFactoryMethodSmooth: undefined
  23623. // Note: Actually this track could have a optimized / compressed
  23624. // representation of a single value and a custom interpolant that
  23625. // computes "firstValue ^ isOdd( index )".
  23626. } );
  23627. /**
  23628. *
  23629. * A Track of keyframe values that represent color.
  23630. *
  23631. *
  23632. * @author Ben Houston / http://clara.io/
  23633. * @author David Sarno / http://lighthaus.us/
  23634. * @author tschw
  23635. */
  23636. function ColorKeyframeTrack( name, times, values, interpolation ) {
  23637. KeyframeTrack.call( this, name, times, values, interpolation );
  23638. }
  23639. ColorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  23640. constructor: ColorKeyframeTrack,
  23641. ValueTypeName: 'color'
  23642. // ValueBufferType is inherited
  23643. // DefaultInterpolation is inherited
  23644. // Note: Very basic implementation and nothing special yet.
  23645. // However, this is the place for color space parameterization.
  23646. } );
  23647. /**
  23648. *
  23649. * A Track of numeric keyframe values.
  23650. *
  23651. * @author Ben Houston / http://clara.io/
  23652. * @author David Sarno / http://lighthaus.us/
  23653. * @author tschw
  23654. */
  23655. function NumberKeyframeTrack( name, times, values, interpolation ) {
  23656. KeyframeTrack.call( this, name, times, values, interpolation );
  23657. }
  23658. NumberKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  23659. constructor: NumberKeyframeTrack,
  23660. ValueTypeName: 'number'
  23661. // ValueBufferType is inherited
  23662. // DefaultInterpolation is inherited
  23663. } );
  23664. /**
  23665. * Spherical linear unit quaternion interpolant.
  23666. *
  23667. * @author tschw
  23668. */
  23669. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23670. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  23671. }
  23672. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  23673. constructor: QuaternionLinearInterpolant,
  23674. interpolate_: function ( i1, t0, t, t1 ) {
  23675. var result = this.resultBuffer,
  23676. values = this.sampleValues,
  23677. stride = this.valueSize,
  23678. offset = i1 * stride,
  23679. alpha = ( t - t0 ) / ( t1 - t0 );
  23680. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  23681. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  23682. }
  23683. return result;
  23684. }
  23685. } );
  23686. /**
  23687. *
  23688. * A Track of quaternion keyframe values.
  23689. *
  23690. * @author Ben Houston / http://clara.io/
  23691. * @author David Sarno / http://lighthaus.us/
  23692. * @author tschw
  23693. */
  23694. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  23695. KeyframeTrack.call( this, name, times, values, interpolation );
  23696. }
  23697. QuaternionKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  23698. constructor: QuaternionKeyframeTrack,
  23699. ValueTypeName: 'quaternion',
  23700. // ValueBufferType is inherited
  23701. DefaultInterpolation: InterpolateLinear,
  23702. InterpolantFactoryMethodLinear: function ( result ) {
  23703. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23704. },
  23705. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  23706. } );
  23707. /**
  23708. *
  23709. * A Track that interpolates Strings
  23710. *
  23711. *
  23712. * @author Ben Houston / http://clara.io/
  23713. * @author David Sarno / http://lighthaus.us/
  23714. * @author tschw
  23715. */
  23716. function StringKeyframeTrack( name, times, values, interpolation ) {
  23717. KeyframeTrack.call( this, name, times, values, interpolation );
  23718. }
  23719. StringKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  23720. constructor: StringKeyframeTrack,
  23721. ValueTypeName: 'string',
  23722. ValueBufferType: Array,
  23723. DefaultInterpolation: InterpolateDiscrete,
  23724. InterpolantFactoryMethodLinear: undefined,
  23725. InterpolantFactoryMethodSmooth: undefined
  23726. } );
  23727. /**
  23728. *
  23729. * A Track of vectored keyframe values.
  23730. *
  23731. *
  23732. * @author Ben Houston / http://clara.io/
  23733. * @author David Sarno / http://lighthaus.us/
  23734. * @author tschw
  23735. */
  23736. function VectorKeyframeTrack( name, times, values, interpolation ) {
  23737. KeyframeTrack.call( this, name, times, values, interpolation );
  23738. }
  23739. VectorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  23740. constructor: VectorKeyframeTrack,
  23741. ValueTypeName: 'vector'
  23742. // ValueBufferType is inherited
  23743. // DefaultInterpolation is inherited
  23744. } );
  23745. /**
  23746. *
  23747. * Reusable set of Tracks that represent an animation.
  23748. *
  23749. * @author Ben Houston / http://clara.io/
  23750. * @author David Sarno / http://lighthaus.us/
  23751. */
  23752. function AnimationClip( name, duration, tracks ) {
  23753. this.name = name;
  23754. this.tracks = tracks;
  23755. this.duration = ( duration !== undefined ) ? duration : - 1;
  23756. this.uuid = _Math.generateUUID();
  23757. // this means it should figure out its duration by scanning the tracks
  23758. if ( this.duration < 0 ) {
  23759. this.resetDuration();
  23760. }
  23761. }
  23762. function getTrackTypeForValueTypeName( typeName ) {
  23763. switch ( typeName.toLowerCase() ) {
  23764. case 'scalar':
  23765. case 'double':
  23766. case 'float':
  23767. case 'number':
  23768. case 'integer':
  23769. return NumberKeyframeTrack;
  23770. case 'vector':
  23771. case 'vector2':
  23772. case 'vector3':
  23773. case 'vector4':
  23774. return VectorKeyframeTrack;
  23775. case 'color':
  23776. return ColorKeyframeTrack;
  23777. case 'quaternion':
  23778. return QuaternionKeyframeTrack;
  23779. case 'bool':
  23780. case 'boolean':
  23781. return BooleanKeyframeTrack;
  23782. case 'string':
  23783. return StringKeyframeTrack;
  23784. }
  23785. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  23786. }
  23787. function parseKeyframeTrack( json ) {
  23788. if ( json.type === undefined ) {
  23789. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  23790. }
  23791. var trackType = getTrackTypeForValueTypeName( json.type );
  23792. if ( json.times === undefined ) {
  23793. var times = [], values = [];
  23794. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  23795. json.times = times;
  23796. json.values = values;
  23797. }
  23798. // derived classes can define a static parse method
  23799. if ( trackType.parse !== undefined ) {
  23800. return trackType.parse( json );
  23801. } else {
  23802. // by default, we assume a constructor compatible with the base
  23803. return new trackType( json.name, json.times, json.values, json.interpolation );
  23804. }
  23805. }
  23806. Object.assign( AnimationClip, {
  23807. parse: function ( json ) {
  23808. var tracks = [],
  23809. jsonTracks = json.tracks,
  23810. frameTime = 1.0 / ( json.fps || 1.0 );
  23811. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  23812. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  23813. }
  23814. return new AnimationClip( json.name, json.duration, tracks );
  23815. },
  23816. toJSON: function ( clip ) {
  23817. var tracks = [],
  23818. clipTracks = clip.tracks;
  23819. var json = {
  23820. 'name': clip.name,
  23821. 'duration': clip.duration,
  23822. 'tracks': tracks,
  23823. 'uuid': clip.uuid
  23824. };
  23825. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  23826. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  23827. }
  23828. return json;
  23829. },
  23830. CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
  23831. var numMorphTargets = morphTargetSequence.length;
  23832. var tracks = [];
  23833. for ( var i = 0; i < numMorphTargets; i ++ ) {
  23834. var times = [];
  23835. var values = [];
  23836. times.push(
  23837. ( i + numMorphTargets - 1 ) % numMorphTargets,
  23838. i,
  23839. ( i + 1 ) % numMorphTargets );
  23840. values.push( 0, 1, 0 );
  23841. var order = AnimationUtils.getKeyframeOrder( times );
  23842. times = AnimationUtils.sortedArray( times, 1, order );
  23843. values = AnimationUtils.sortedArray( values, 1, order );
  23844. // if there is a key at the first frame, duplicate it as the
  23845. // last frame as well for perfect loop.
  23846. if ( ! noLoop && times[ 0 ] === 0 ) {
  23847. times.push( numMorphTargets );
  23848. values.push( values[ 0 ] );
  23849. }
  23850. tracks.push(
  23851. new NumberKeyframeTrack(
  23852. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  23853. times, values
  23854. ).scale( 1.0 / fps ) );
  23855. }
  23856. return new AnimationClip( name, - 1, tracks );
  23857. },
  23858. findByName: function ( objectOrClipArray, name ) {
  23859. var clipArray = objectOrClipArray;
  23860. if ( ! Array.isArray( objectOrClipArray ) ) {
  23861. var o = objectOrClipArray;
  23862. clipArray = o.geometry && o.geometry.animations || o.animations;
  23863. }
  23864. for ( var i = 0; i < clipArray.length; i ++ ) {
  23865. if ( clipArray[ i ].name === name ) {
  23866. return clipArray[ i ];
  23867. }
  23868. }
  23869. return null;
  23870. },
  23871. CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
  23872. var animationToMorphTargets = {};
  23873. // tested with https://regex101.com/ on trick sequences
  23874. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  23875. var pattern = /^([\w-]*?)([\d]+)$/;
  23876. // sort morph target names into animation groups based
  23877. // patterns like Walk_001, Walk_002, Run_001, Run_002
  23878. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  23879. var morphTarget = morphTargets[ i ];
  23880. var parts = morphTarget.name.match( pattern );
  23881. if ( parts && parts.length > 1 ) {
  23882. var name = parts[ 1 ];
  23883. var animationMorphTargets = animationToMorphTargets[ name ];
  23884. if ( ! animationMorphTargets ) {
  23885. animationToMorphTargets[ name ] = animationMorphTargets = [];
  23886. }
  23887. animationMorphTargets.push( morphTarget );
  23888. }
  23889. }
  23890. var clips = [];
  23891. for ( var name in animationToMorphTargets ) {
  23892. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  23893. }
  23894. return clips;
  23895. },
  23896. // parse the animation.hierarchy format
  23897. parseAnimation: function ( animation, bones ) {
  23898. if ( ! animation ) {
  23899. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  23900. return null;
  23901. }
  23902. var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  23903. // only return track if there are actually keys.
  23904. if ( animationKeys.length !== 0 ) {
  23905. var times = [];
  23906. var values = [];
  23907. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  23908. // empty keys are filtered out, so check again
  23909. if ( times.length !== 0 ) {
  23910. destTracks.push( new trackType( trackName, times, values ) );
  23911. }
  23912. }
  23913. };
  23914. var tracks = [];
  23915. var clipName = animation.name || 'default';
  23916. // automatic length determination in AnimationClip.
  23917. var duration = animation.length || - 1;
  23918. var fps = animation.fps || 30;
  23919. var hierarchyTracks = animation.hierarchy || [];
  23920. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  23921. var animationKeys = hierarchyTracks[ h ].keys;
  23922. // skip empty tracks
  23923. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  23924. // process morph targets
  23925. if ( animationKeys[ 0 ].morphTargets ) {
  23926. // figure out all morph targets used in this track
  23927. var morphTargetNames = {};
  23928. for ( var k = 0; k < animationKeys.length; k ++ ) {
  23929. if ( animationKeys[ k ].morphTargets ) {
  23930. for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  23931. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  23932. }
  23933. }
  23934. }
  23935. // create a track for each morph target with all zero
  23936. // morphTargetInfluences except for the keys in which
  23937. // the morphTarget is named.
  23938. for ( var morphTargetName in morphTargetNames ) {
  23939. var times = [];
  23940. var values = [];
  23941. for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  23942. var animationKey = animationKeys[ k ];
  23943. times.push( animationKey.time );
  23944. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  23945. }
  23946. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  23947. }
  23948. duration = morphTargetNames.length * ( fps || 1.0 );
  23949. } else {
  23950. // ...assume skeletal animation
  23951. var boneName = '.bones[' + bones[ h ].name + ']';
  23952. addNonemptyTrack(
  23953. VectorKeyframeTrack, boneName + '.position',
  23954. animationKeys, 'pos', tracks );
  23955. addNonemptyTrack(
  23956. QuaternionKeyframeTrack, boneName + '.quaternion',
  23957. animationKeys, 'rot', tracks );
  23958. addNonemptyTrack(
  23959. VectorKeyframeTrack, boneName + '.scale',
  23960. animationKeys, 'scl', tracks );
  23961. }
  23962. }
  23963. if ( tracks.length === 0 ) {
  23964. return null;
  23965. }
  23966. var clip = new AnimationClip( clipName, duration, tracks );
  23967. return clip;
  23968. }
  23969. } );
  23970. Object.assign( AnimationClip.prototype, {
  23971. resetDuration: function () {
  23972. var tracks = this.tracks, duration = 0;
  23973. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  23974. var track = this.tracks[ i ];
  23975. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  23976. }
  23977. this.duration = duration;
  23978. return this;
  23979. },
  23980. trim: function () {
  23981. for ( var i = 0; i < this.tracks.length; i ++ ) {
  23982. this.tracks[ i ].trim( 0, this.duration );
  23983. }
  23984. return this;
  23985. },
  23986. validate: function () {
  23987. var valid = true;
  23988. for ( var i = 0; i < this.tracks.length; i ++ ) {
  23989. valid = valid && this.tracks[ i ].validate();
  23990. }
  23991. return valid;
  23992. },
  23993. optimize: function () {
  23994. for ( var i = 0; i < this.tracks.length; i ++ ) {
  23995. this.tracks[ i ].optimize();
  23996. }
  23997. return this;
  23998. }
  23999. } );
  24000. /**
  24001. * @author mrdoob / http://mrdoob.com/
  24002. */
  24003. var Cache = {
  24004. enabled: false,
  24005. files: {},
  24006. add: function ( key, file ) {
  24007. if ( this.enabled === false ) return;
  24008. // console.log( 'THREE.Cache', 'Adding key:', key );
  24009. this.files[ key ] = file;
  24010. },
  24011. get: function ( key ) {
  24012. if ( this.enabled === false ) return;
  24013. // console.log( 'THREE.Cache', 'Checking key:', key );
  24014. return this.files[ key ];
  24015. },
  24016. remove: function ( key ) {
  24017. delete this.files[ key ];
  24018. },
  24019. clear: function () {
  24020. this.files = {};
  24021. }
  24022. };
  24023. /**
  24024. * @author mrdoob / http://mrdoob.com/
  24025. */
  24026. function LoadingManager( onLoad, onProgress, onError ) {
  24027. var scope = this;
  24028. var isLoading = false;
  24029. var itemsLoaded = 0;
  24030. var itemsTotal = 0;
  24031. var urlModifier = undefined;
  24032. // Refer to #5689 for the reason why we don't set .onStart
  24033. // in the constructor
  24034. this.onStart = undefined;
  24035. this.onLoad = onLoad;
  24036. this.onProgress = onProgress;
  24037. this.onError = onError;
  24038. this.itemStart = function ( url ) {
  24039. itemsTotal ++;
  24040. if ( isLoading === false ) {
  24041. if ( scope.onStart !== undefined ) {
  24042. scope.onStart( url, itemsLoaded, itemsTotal );
  24043. }
  24044. }
  24045. isLoading = true;
  24046. };
  24047. this.itemEnd = function ( url ) {
  24048. itemsLoaded ++;
  24049. if ( scope.onProgress !== undefined ) {
  24050. scope.onProgress( url, itemsLoaded, itemsTotal );
  24051. }
  24052. if ( itemsLoaded === itemsTotal ) {
  24053. isLoading = false;
  24054. if ( scope.onLoad !== undefined ) {
  24055. scope.onLoad();
  24056. }
  24057. }
  24058. };
  24059. this.itemError = function ( url ) {
  24060. if ( scope.onError !== undefined ) {
  24061. scope.onError( url );
  24062. }
  24063. };
  24064. this.resolveURL = function ( url ) {
  24065. if ( urlModifier ) {
  24066. return urlModifier( url );
  24067. }
  24068. return url;
  24069. };
  24070. this.setURLModifier = function ( transform ) {
  24071. urlModifier = transform;
  24072. return this;
  24073. };
  24074. }
  24075. var DefaultLoadingManager = new LoadingManager();
  24076. /**
  24077. * @author mrdoob / http://mrdoob.com/
  24078. */
  24079. var loading = {};
  24080. function FileLoader( manager ) {
  24081. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24082. }
  24083. Object.assign( FileLoader.prototype, {
  24084. load: function ( url, onLoad, onProgress, onError ) {
  24085. if ( url === undefined ) url = '';
  24086. if ( this.path !== undefined ) url = this.path + url;
  24087. url = this.manager.resolveURL( url );
  24088. var scope = this;
  24089. var cached = Cache.get( url );
  24090. if ( cached !== undefined ) {
  24091. scope.manager.itemStart( url );
  24092. setTimeout( function () {
  24093. if ( onLoad ) onLoad( cached );
  24094. scope.manager.itemEnd( url );
  24095. }, 0 );
  24096. return cached;
  24097. }
  24098. // Check if request is duplicate
  24099. if ( loading[ url ] !== undefined ) {
  24100. loading[ url ].push( {
  24101. onLoad: onLoad,
  24102. onProgress: onProgress,
  24103. onError: onError
  24104. } );
  24105. return;
  24106. }
  24107. // Check for data: URI
  24108. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  24109. var dataUriRegexResult = url.match( dataUriRegex );
  24110. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  24111. if ( dataUriRegexResult ) {
  24112. var mimeType = dataUriRegexResult[ 1 ];
  24113. var isBase64 = !! dataUriRegexResult[ 2 ];
  24114. var data = dataUriRegexResult[ 3 ];
  24115. data = decodeURIComponent( data );
  24116. if ( isBase64 ) data = atob( data );
  24117. try {
  24118. var response;
  24119. var responseType = ( this.responseType || '' ).toLowerCase();
  24120. switch ( responseType ) {
  24121. case 'arraybuffer':
  24122. case 'blob':
  24123. var view = new Uint8Array( data.length );
  24124. for ( var i = 0; i < data.length; i ++ ) {
  24125. view[ i ] = data.charCodeAt( i );
  24126. }
  24127. if ( responseType === 'blob' ) {
  24128. response = new Blob( [ view.buffer ], { type: mimeType } );
  24129. } else {
  24130. response = view.buffer;
  24131. }
  24132. break;
  24133. case 'document':
  24134. var parser = new DOMParser();
  24135. response = parser.parseFromString( data, mimeType );
  24136. break;
  24137. case 'json':
  24138. response = JSON.parse( data );
  24139. break;
  24140. default: // 'text' or other
  24141. response = data;
  24142. break;
  24143. }
  24144. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  24145. setTimeout( function () {
  24146. if ( onLoad ) onLoad( response );
  24147. scope.manager.itemEnd( url );
  24148. }, 0 );
  24149. } catch ( error ) {
  24150. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  24151. setTimeout( function () {
  24152. if ( onError ) onError( error );
  24153. scope.manager.itemError( url );
  24154. scope.manager.itemEnd( url );
  24155. }, 0 );
  24156. }
  24157. } else {
  24158. // Initialise array for duplicate requests
  24159. loading[ url ] = [];
  24160. loading[ url ].push( {
  24161. onLoad: onLoad,
  24162. onProgress: onProgress,
  24163. onError: onError
  24164. } );
  24165. var request = new XMLHttpRequest();
  24166. request.open( 'GET', url, true );
  24167. request.addEventListener( 'load', function ( event ) {
  24168. var response = this.response;
  24169. Cache.add( url, response );
  24170. var callbacks = loading[ url ];
  24171. delete loading[ url ];
  24172. if ( this.status === 200 || this.status === 0 ) {
  24173. // Some browsers return HTTP Status 0 when using non-http protocol
  24174. // e.g. 'file://' or 'data://'. Handle as success.
  24175. if ( this.status === 0 ) console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  24176. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  24177. var callback = callbacks[ i ];
  24178. if ( callback.onLoad ) callback.onLoad( response );
  24179. }
  24180. scope.manager.itemEnd( url );
  24181. } else {
  24182. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  24183. var callback = callbacks[ i ];
  24184. if ( callback.onError ) callback.onError( event );
  24185. }
  24186. scope.manager.itemError( url );
  24187. scope.manager.itemEnd( url );
  24188. }
  24189. }, false );
  24190. request.addEventListener( 'progress', function ( event ) {
  24191. var callbacks = loading[ url ];
  24192. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  24193. var callback = callbacks[ i ];
  24194. if ( callback.onProgress ) callback.onProgress( event );
  24195. }
  24196. }, false );
  24197. request.addEventListener( 'error', function ( event ) {
  24198. var callbacks = loading[ url ];
  24199. delete loading[ url ];
  24200. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  24201. var callback = callbacks[ i ];
  24202. if ( callback.onError ) callback.onError( event );
  24203. }
  24204. scope.manager.itemError( url );
  24205. scope.manager.itemEnd( url );
  24206. }, false );
  24207. request.addEventListener( 'abort', function ( event ) {
  24208. var callbacks = loading[ url ];
  24209. delete loading[ url ];
  24210. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  24211. var callback = callbacks[ i ];
  24212. if ( callback.onError ) callback.onError( event );
  24213. }
  24214. scope.manager.itemError( url );
  24215. scope.manager.itemEnd( url );
  24216. }, false );
  24217. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  24218. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  24219. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  24220. for ( var header in this.requestHeader ) {
  24221. request.setRequestHeader( header, this.requestHeader[ header ] );
  24222. }
  24223. request.send( null );
  24224. }
  24225. scope.manager.itemStart( url );
  24226. return request;
  24227. },
  24228. setPath: function ( value ) {
  24229. this.path = value;
  24230. return this;
  24231. },
  24232. setResponseType: function ( value ) {
  24233. this.responseType = value;
  24234. return this;
  24235. },
  24236. setWithCredentials: function ( value ) {
  24237. this.withCredentials = value;
  24238. return this;
  24239. },
  24240. setMimeType: function ( value ) {
  24241. this.mimeType = value;
  24242. return this;
  24243. },
  24244. setRequestHeader: function ( value ) {
  24245. this.requestHeader = value;
  24246. return this;
  24247. }
  24248. } );
  24249. /**
  24250. * @author bhouston / http://clara.io/
  24251. */
  24252. function AnimationLoader( manager ) {
  24253. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24254. }
  24255. Object.assign( AnimationLoader.prototype, {
  24256. load: function ( url, onLoad, onProgress, onError ) {
  24257. var scope = this;
  24258. var loader = new FileLoader( scope.manager );
  24259. loader.setPath( scope.path );
  24260. loader.load( url, function ( text ) {
  24261. onLoad( scope.parse( JSON.parse( text ) ) );
  24262. }, onProgress, onError );
  24263. },
  24264. parse: function ( json, onLoad ) {
  24265. var animations = [];
  24266. for ( var i = 0; i < json.length; i ++ ) {
  24267. var clip = AnimationClip.parse( json[ i ] );
  24268. animations.push( clip );
  24269. }
  24270. onLoad( animations );
  24271. },
  24272. setPath: function ( value ) {
  24273. this.path = value;
  24274. return this;
  24275. }
  24276. } );
  24277. /**
  24278. * @author mrdoob / http://mrdoob.com/
  24279. *
  24280. * Abstract Base class to block based textures loader (dds, pvr, ...)
  24281. */
  24282. function CompressedTextureLoader( manager ) {
  24283. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24284. // override in sub classes
  24285. this._parser = null;
  24286. }
  24287. Object.assign( CompressedTextureLoader.prototype, {
  24288. load: function ( url, onLoad, onProgress, onError ) {
  24289. var scope = this;
  24290. var images = [];
  24291. var texture = new CompressedTexture();
  24292. texture.image = images;
  24293. var loader = new FileLoader( this.manager );
  24294. loader.setPath( this.path );
  24295. loader.setResponseType( 'arraybuffer' );
  24296. function loadTexture( i ) {
  24297. loader.load( url[ i ], function ( buffer ) {
  24298. var texDatas = scope._parser( buffer, true );
  24299. images[ i ] = {
  24300. width: texDatas.width,
  24301. height: texDatas.height,
  24302. format: texDatas.format,
  24303. mipmaps: texDatas.mipmaps
  24304. };
  24305. loaded += 1;
  24306. if ( loaded === 6 ) {
  24307. if ( texDatas.mipmapCount === 1 )
  24308. texture.minFilter = LinearFilter;
  24309. texture.format = texDatas.format;
  24310. texture.needsUpdate = true;
  24311. if ( onLoad ) onLoad( texture );
  24312. }
  24313. }, onProgress, onError );
  24314. }
  24315. if ( Array.isArray( url ) ) {
  24316. var loaded = 0;
  24317. for ( var i = 0, il = url.length; i < il; ++ i ) {
  24318. loadTexture( i );
  24319. }
  24320. } else {
  24321. // compressed cubemap texture stored in a single DDS file
  24322. loader.load( url, function ( buffer ) {
  24323. var texDatas = scope._parser( buffer, true );
  24324. if ( texDatas.isCubemap ) {
  24325. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  24326. for ( var f = 0; f < faces; f ++ ) {
  24327. images[ f ] = { mipmaps: [] };
  24328. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  24329. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  24330. images[ f ].format = texDatas.format;
  24331. images[ f ].width = texDatas.width;
  24332. images[ f ].height = texDatas.height;
  24333. }
  24334. }
  24335. } else {
  24336. texture.image.width = texDatas.width;
  24337. texture.image.height = texDatas.height;
  24338. texture.mipmaps = texDatas.mipmaps;
  24339. }
  24340. if ( texDatas.mipmapCount === 1 ) {
  24341. texture.minFilter = LinearFilter;
  24342. }
  24343. texture.format = texDatas.format;
  24344. texture.needsUpdate = true;
  24345. if ( onLoad ) onLoad( texture );
  24346. }, onProgress, onError );
  24347. }
  24348. return texture;
  24349. },
  24350. setPath: function ( value ) {
  24351. this.path = value;
  24352. return this;
  24353. }
  24354. } );
  24355. /**
  24356. * @author Nikos M. / https://github.com/foo123/
  24357. *
  24358. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  24359. */
  24360. function DataTextureLoader( manager ) {
  24361. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24362. // override in sub classes
  24363. this._parser = null;
  24364. }
  24365. Object.assign( DataTextureLoader.prototype, {
  24366. load: function ( url, onLoad, onProgress, onError ) {
  24367. var scope = this;
  24368. var texture = new DataTexture();
  24369. var loader = new FileLoader( this.manager );
  24370. loader.setResponseType( 'arraybuffer' );
  24371. loader.setPath( this.path );
  24372. loader.load( url, function ( buffer ) {
  24373. var texData = scope._parser( buffer );
  24374. if ( ! texData ) return;
  24375. if ( texData.image !== undefined ) {
  24376. texture.image = texData.image;
  24377. } else if ( texData.data !== undefined ) {
  24378. texture.image.width = texData.width;
  24379. texture.image.height = texData.height;
  24380. texture.image.data = texData.data;
  24381. }
  24382. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  24383. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  24384. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  24385. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearMipMapLinearFilter;
  24386. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  24387. if ( texData.format !== undefined ) {
  24388. texture.format = texData.format;
  24389. }
  24390. if ( texData.type !== undefined ) {
  24391. texture.type = texData.type;
  24392. }
  24393. if ( texData.mipmaps !== undefined ) {
  24394. texture.mipmaps = texData.mipmaps;
  24395. }
  24396. if ( texData.mipmapCount === 1 ) {
  24397. texture.minFilter = LinearFilter;
  24398. }
  24399. texture.needsUpdate = true;
  24400. if ( onLoad ) onLoad( texture, texData );
  24401. }, onProgress, onError );
  24402. return texture;
  24403. },
  24404. setPath: function ( value ) {
  24405. this.path = value;
  24406. return this;
  24407. }
  24408. } );
  24409. /**
  24410. * @author mrdoob / http://mrdoob.com/
  24411. */
  24412. function ImageLoader( manager ) {
  24413. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24414. }
  24415. Object.assign( ImageLoader.prototype, {
  24416. crossOrigin: 'anonymous',
  24417. load: function ( url, onLoad, onProgress, onError ) {
  24418. if ( url === undefined ) url = '';
  24419. if ( this.path !== undefined ) url = this.path + url;
  24420. url = this.manager.resolveURL( url );
  24421. var scope = this;
  24422. var cached = Cache.get( url );
  24423. if ( cached !== undefined ) {
  24424. scope.manager.itemStart( url );
  24425. setTimeout( function () {
  24426. if ( onLoad ) onLoad( cached );
  24427. scope.manager.itemEnd( url );
  24428. }, 0 );
  24429. return cached;
  24430. }
  24431. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  24432. function onImageLoad() {
  24433. image.removeEventListener( 'load', onImageLoad, false );
  24434. image.removeEventListener( 'error', onImageError, false );
  24435. Cache.add( url, this );
  24436. if ( onLoad ) onLoad( this );
  24437. scope.manager.itemEnd( url );
  24438. }
  24439. function onImageError( event ) {
  24440. image.removeEventListener( 'load', onImageLoad, false );
  24441. image.removeEventListener( 'error', onImageError, false );
  24442. if ( onError ) onError( event );
  24443. scope.manager.itemError( url );
  24444. scope.manager.itemEnd( url );
  24445. }
  24446. image.addEventListener( 'load', onImageLoad, false );
  24447. image.addEventListener( 'error', onImageError, false );
  24448. if ( url.substr( 0, 5 ) !== 'data:' ) {
  24449. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  24450. }
  24451. scope.manager.itemStart( url );
  24452. image.src = url;
  24453. return image;
  24454. },
  24455. setCrossOrigin: function ( value ) {
  24456. this.crossOrigin = value;
  24457. return this;
  24458. },
  24459. setPath: function ( value ) {
  24460. this.path = value;
  24461. return this;
  24462. }
  24463. } );
  24464. /**
  24465. * @author mrdoob / http://mrdoob.com/
  24466. */
  24467. function CubeTextureLoader( manager ) {
  24468. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24469. }
  24470. Object.assign( CubeTextureLoader.prototype, {
  24471. crossOrigin: 'anonymous',
  24472. load: function ( urls, onLoad, onProgress, onError ) {
  24473. var texture = new CubeTexture();
  24474. var loader = new ImageLoader( this.manager );
  24475. loader.setCrossOrigin( this.crossOrigin );
  24476. loader.setPath( this.path );
  24477. var loaded = 0;
  24478. function loadTexture( i ) {
  24479. loader.load( urls[ i ], function ( image ) {
  24480. texture.images[ i ] = image;
  24481. loaded ++;
  24482. if ( loaded === 6 ) {
  24483. texture.needsUpdate = true;
  24484. if ( onLoad ) onLoad( texture );
  24485. }
  24486. }, undefined, onError );
  24487. }
  24488. for ( var i = 0; i < urls.length; ++ i ) {
  24489. loadTexture( i );
  24490. }
  24491. return texture;
  24492. },
  24493. setCrossOrigin: function ( value ) {
  24494. this.crossOrigin = value;
  24495. return this;
  24496. },
  24497. setPath: function ( value ) {
  24498. this.path = value;
  24499. return this;
  24500. }
  24501. } );
  24502. /**
  24503. * @author mrdoob / http://mrdoob.com/
  24504. */
  24505. function TextureLoader( manager ) {
  24506. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24507. }
  24508. Object.assign( TextureLoader.prototype, {
  24509. crossOrigin: 'anonymous',
  24510. load: function ( url, onLoad, onProgress, onError ) {
  24511. var texture = new Texture();
  24512. var loader = new ImageLoader( this.manager );
  24513. loader.setCrossOrigin( this.crossOrigin );
  24514. loader.setPath( this.path );
  24515. loader.load( url, function ( image ) {
  24516. texture.image = image;
  24517. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  24518. var isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  24519. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  24520. texture.needsUpdate = true;
  24521. if ( onLoad !== undefined ) {
  24522. onLoad( texture );
  24523. }
  24524. }, onProgress, onError );
  24525. return texture;
  24526. },
  24527. setCrossOrigin: function ( value ) {
  24528. this.crossOrigin = value;
  24529. return this;
  24530. },
  24531. setPath: function ( value ) {
  24532. this.path = value;
  24533. return this;
  24534. }
  24535. } );
  24536. /**
  24537. * @author zz85 / http://www.lab4games.net/zz85/blog
  24538. * Extensible curve object
  24539. *
  24540. * Some common of curve methods:
  24541. * .getPoint( t, optionalTarget ), .getTangent( t )
  24542. * .getPointAt( u, optionalTarget ), .getTangentAt( u )
  24543. * .getPoints(), .getSpacedPoints()
  24544. * .getLength()
  24545. * .updateArcLengths()
  24546. *
  24547. * This following curves inherit from THREE.Curve:
  24548. *
  24549. * -- 2D curves --
  24550. * THREE.ArcCurve
  24551. * THREE.CubicBezierCurve
  24552. * THREE.EllipseCurve
  24553. * THREE.LineCurve
  24554. * THREE.QuadraticBezierCurve
  24555. * THREE.SplineCurve
  24556. *
  24557. * -- 3D curves --
  24558. * THREE.CatmullRomCurve3
  24559. * THREE.CubicBezierCurve3
  24560. * THREE.LineCurve3
  24561. * THREE.QuadraticBezierCurve3
  24562. *
  24563. * A series of curves can be represented as a THREE.CurvePath.
  24564. *
  24565. **/
  24566. /**************************************************************
  24567. * Abstract Curve base class
  24568. **************************************************************/
  24569. function Curve() {
  24570. this.type = 'Curve';
  24571. this.arcLengthDivisions = 200;
  24572. }
  24573. Object.assign( Curve.prototype, {
  24574. // Virtual base class method to overwrite and implement in subclasses
  24575. // - t [0 .. 1]
  24576. getPoint: function ( /* t, optionalTarget */ ) {
  24577. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  24578. return null;
  24579. },
  24580. // Get point at relative position in curve according to arc length
  24581. // - u [0 .. 1]
  24582. getPointAt: function ( u, optionalTarget ) {
  24583. var t = this.getUtoTmapping( u );
  24584. return this.getPoint( t, optionalTarget );
  24585. },
  24586. // Get sequence of points using getPoint( t )
  24587. getPoints: function ( divisions ) {
  24588. if ( divisions === undefined ) divisions = 5;
  24589. var points = [];
  24590. for ( var d = 0; d <= divisions; d ++ ) {
  24591. points.push( this.getPoint( d / divisions ) );
  24592. }
  24593. return points;
  24594. },
  24595. // Get sequence of points using getPointAt( u )
  24596. getSpacedPoints: function ( divisions ) {
  24597. if ( divisions === undefined ) divisions = 5;
  24598. var points = [];
  24599. for ( var d = 0; d <= divisions; d ++ ) {
  24600. points.push( this.getPointAt( d / divisions ) );
  24601. }
  24602. return points;
  24603. },
  24604. // Get total curve arc length
  24605. getLength: function () {
  24606. var lengths = this.getLengths();
  24607. return lengths[ lengths.length - 1 ];
  24608. },
  24609. // Get list of cumulative segment lengths
  24610. getLengths: function ( divisions ) {
  24611. if ( divisions === undefined ) divisions = this.arcLengthDivisions;
  24612. if ( this.cacheArcLengths &&
  24613. ( this.cacheArcLengths.length === divisions + 1 ) &&
  24614. ! this.needsUpdate ) {
  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. // binary search for the index with largest value smaller than target u distance
  24646. var low = 0, high = il - 1, comparison;
  24647. while ( low <= high ) {
  24648. 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
  24649. comparison = arcLengths[ i ] - targetArcLength;
  24650. if ( comparison < 0 ) {
  24651. low = i + 1;
  24652. } else if ( comparison > 0 ) {
  24653. high = i - 1;
  24654. } else {
  24655. high = i;
  24656. break;
  24657. // DONE
  24658. }
  24659. }
  24660. i = high;
  24661. if ( arcLengths[ i ] === targetArcLength ) {
  24662. return i / ( il - 1 );
  24663. }
  24664. // we could get finer grain at lengths, or use simple interpolation between two points
  24665. var lengthBefore = arcLengths[ i ];
  24666. var lengthAfter = arcLengths[ i + 1 ];
  24667. var segmentLength = lengthAfter - lengthBefore;
  24668. // determine where we are between the 'before' and 'after' points
  24669. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  24670. // add that fractional amount to t
  24671. var t = ( i + segmentFraction ) / ( il - 1 );
  24672. return t;
  24673. },
  24674. // Returns a unit vector tangent at t
  24675. // In case any sub curve does not implement its tangent derivation,
  24676. // 2 points a small delta apart will be used to find its gradient
  24677. // which seems to give a reasonable approximation
  24678. getTangent: function ( t ) {
  24679. var delta = 0.0001;
  24680. var t1 = t - delta;
  24681. var t2 = t + delta;
  24682. // Capping in case of danger
  24683. if ( t1 < 0 ) t1 = 0;
  24684. if ( t2 > 1 ) t2 = 1;
  24685. var pt1 = this.getPoint( t1 );
  24686. var pt2 = this.getPoint( t2 );
  24687. var vec = pt2.clone().sub( pt1 );
  24688. return vec.normalize();
  24689. },
  24690. getTangentAt: function ( u ) {
  24691. var t = this.getUtoTmapping( u );
  24692. return this.getTangent( t );
  24693. },
  24694. computeFrenetFrames: function ( segments, closed ) {
  24695. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  24696. var normal = new Vector3();
  24697. var tangents = [];
  24698. var normals = [];
  24699. var binormals = [];
  24700. var vec = new Vector3();
  24701. var mat = new Matrix4();
  24702. var i, u, theta;
  24703. // compute the tangent vectors for each segment on the curve
  24704. for ( i = 0; i <= segments; i ++ ) {
  24705. u = i / segments;
  24706. tangents[ i ] = this.getTangentAt( u );
  24707. tangents[ i ].normalize();
  24708. }
  24709. // select an initial normal vector perpendicular to the first tangent vector,
  24710. // and in the direction of the minimum tangent xyz component
  24711. normals[ 0 ] = new Vector3();
  24712. binormals[ 0 ] = new Vector3();
  24713. var min = Number.MAX_VALUE;
  24714. var tx = Math.abs( tangents[ 0 ].x );
  24715. var ty = Math.abs( tangents[ 0 ].y );
  24716. var tz = Math.abs( tangents[ 0 ].z );
  24717. if ( tx <= min ) {
  24718. min = tx;
  24719. normal.set( 1, 0, 0 );
  24720. }
  24721. if ( ty <= min ) {
  24722. min = ty;
  24723. normal.set( 0, 1, 0 );
  24724. }
  24725. if ( tz <= min ) {
  24726. normal.set( 0, 0, 1 );
  24727. }
  24728. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  24729. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  24730. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  24731. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  24732. for ( i = 1; i <= segments; i ++ ) {
  24733. normals[ i ] = normals[ i - 1 ].clone();
  24734. binormals[ i ] = binormals[ i - 1 ].clone();
  24735. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  24736. if ( vec.length() > Number.EPSILON ) {
  24737. vec.normalize();
  24738. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  24739. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  24740. }
  24741. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  24742. }
  24743. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  24744. if ( closed === true ) {
  24745. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  24746. theta /= segments;
  24747. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  24748. theta = - theta;
  24749. }
  24750. for ( i = 1; i <= segments; i ++ ) {
  24751. // twist a little...
  24752. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  24753. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  24754. }
  24755. }
  24756. return {
  24757. tangents: tangents,
  24758. normals: normals,
  24759. binormals: binormals
  24760. };
  24761. },
  24762. clone: function () {
  24763. return new this.constructor().copy( this );
  24764. },
  24765. copy: function ( source ) {
  24766. this.arcLengthDivisions = source.arcLengthDivisions;
  24767. return this;
  24768. },
  24769. toJSON: function () {
  24770. var data = {
  24771. metadata: {
  24772. version: 4.5,
  24773. type: 'Curve',
  24774. generator: 'Curve.toJSON'
  24775. }
  24776. };
  24777. data.arcLengthDivisions = this.arcLengthDivisions;
  24778. data.type = this.type;
  24779. return data;
  24780. },
  24781. fromJSON: function ( json ) {
  24782. this.arcLengthDivisions = json.arcLengthDivisions;
  24783. return this;
  24784. }
  24785. } );
  24786. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24787. Curve.call( this );
  24788. this.type = 'EllipseCurve';
  24789. this.aX = aX || 0;
  24790. this.aY = aY || 0;
  24791. this.xRadius = xRadius || 1;
  24792. this.yRadius = yRadius || 1;
  24793. this.aStartAngle = aStartAngle || 0;
  24794. this.aEndAngle = aEndAngle || 2 * Math.PI;
  24795. this.aClockwise = aClockwise || false;
  24796. this.aRotation = aRotation || 0;
  24797. }
  24798. EllipseCurve.prototype = Object.create( Curve.prototype );
  24799. EllipseCurve.prototype.constructor = EllipseCurve;
  24800. EllipseCurve.prototype.isEllipseCurve = true;
  24801. EllipseCurve.prototype.getPoint = function ( t, optionalTarget ) {
  24802. var point = optionalTarget || new Vector2();
  24803. var twoPi = Math.PI * 2;
  24804. var deltaAngle = this.aEndAngle - this.aStartAngle;
  24805. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  24806. // ensures that deltaAngle is 0 .. 2 PI
  24807. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  24808. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  24809. if ( deltaAngle < Number.EPSILON ) {
  24810. if ( samePoints ) {
  24811. deltaAngle = 0;
  24812. } else {
  24813. deltaAngle = twoPi;
  24814. }
  24815. }
  24816. if ( this.aClockwise === true && ! samePoints ) {
  24817. if ( deltaAngle === twoPi ) {
  24818. deltaAngle = - twoPi;
  24819. } else {
  24820. deltaAngle = deltaAngle - twoPi;
  24821. }
  24822. }
  24823. var angle = this.aStartAngle + t * deltaAngle;
  24824. var x = this.aX + this.xRadius * Math.cos( angle );
  24825. var y = this.aY + this.yRadius * Math.sin( angle );
  24826. if ( this.aRotation !== 0 ) {
  24827. var cos = Math.cos( this.aRotation );
  24828. var sin = Math.sin( this.aRotation );
  24829. var tx = x - this.aX;
  24830. var ty = y - this.aY;
  24831. // Rotate the point about the center of the ellipse.
  24832. x = tx * cos - ty * sin + this.aX;
  24833. y = tx * sin + ty * cos + this.aY;
  24834. }
  24835. return point.set( x, y );
  24836. };
  24837. EllipseCurve.prototype.copy = function ( source ) {
  24838. Curve.prototype.copy.call( this, source );
  24839. this.aX = source.aX;
  24840. this.aY = source.aY;
  24841. this.xRadius = source.xRadius;
  24842. this.yRadius = source.yRadius;
  24843. this.aStartAngle = source.aStartAngle;
  24844. this.aEndAngle = source.aEndAngle;
  24845. this.aClockwise = source.aClockwise;
  24846. this.aRotation = source.aRotation;
  24847. return this;
  24848. };
  24849. EllipseCurve.prototype.toJSON = function () {
  24850. var data = Curve.prototype.toJSON.call( this );
  24851. data.aX = this.aX;
  24852. data.aY = this.aY;
  24853. data.xRadius = this.xRadius;
  24854. data.yRadius = this.yRadius;
  24855. data.aStartAngle = this.aStartAngle;
  24856. data.aEndAngle = this.aEndAngle;
  24857. data.aClockwise = this.aClockwise;
  24858. data.aRotation = this.aRotation;
  24859. return data;
  24860. };
  24861. EllipseCurve.prototype.fromJSON = function ( json ) {
  24862. Curve.prototype.fromJSON.call( this, json );
  24863. this.aX = json.aX;
  24864. this.aY = json.aY;
  24865. this.xRadius = json.xRadius;
  24866. this.yRadius = json.yRadius;
  24867. this.aStartAngle = json.aStartAngle;
  24868. this.aEndAngle = json.aEndAngle;
  24869. this.aClockwise = json.aClockwise;
  24870. this.aRotation = json.aRotation;
  24871. return this;
  24872. };
  24873. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24874. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24875. this.type = 'ArcCurve';
  24876. }
  24877. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  24878. ArcCurve.prototype.constructor = ArcCurve;
  24879. ArcCurve.prototype.isArcCurve = true;
  24880. /**
  24881. * @author zz85 https://github.com/zz85
  24882. *
  24883. * Centripetal CatmullRom Curve - which is useful for avoiding
  24884. * cusps and self-intersections in non-uniform catmull rom curves.
  24885. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  24886. *
  24887. * curve.type accepts centripetal(default), chordal and catmullrom
  24888. * curve.tension is used for catmullrom which defaults to 0.5
  24889. */
  24890. /*
  24891. Based on an optimized c++ solution in
  24892. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  24893. - http://ideone.com/NoEbVM
  24894. This CubicPoly class could be used for reusing some variables and calculations,
  24895. but for three.js curve use, it could be possible inlined and flatten into a single function call
  24896. which can be placed in CurveUtils.
  24897. */
  24898. function CubicPoly() {
  24899. var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  24900. /*
  24901. * Compute coefficients for a cubic polynomial
  24902. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  24903. * such that
  24904. * p(0) = x0, p(1) = x1
  24905. * and
  24906. * p'(0) = t0, p'(1) = t1.
  24907. */
  24908. function init( x0, x1, t0, t1 ) {
  24909. c0 = x0;
  24910. c1 = t0;
  24911. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  24912. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  24913. }
  24914. return {
  24915. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  24916. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  24917. },
  24918. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  24919. // compute tangents when parameterized in [t1,t2]
  24920. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  24921. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  24922. // rescale tangents for parametrization in [0,1]
  24923. t1 *= dt1;
  24924. t2 *= dt1;
  24925. init( x1, x2, t1, t2 );
  24926. },
  24927. calc: function ( t ) {
  24928. var t2 = t * t;
  24929. var t3 = t2 * t;
  24930. return c0 + c1 * t + c2 * t2 + c3 * t3;
  24931. }
  24932. };
  24933. }
  24934. //
  24935. var tmp = new Vector3();
  24936. var px = new CubicPoly();
  24937. var py = new CubicPoly();
  24938. var pz = new CubicPoly();
  24939. function CatmullRomCurve3( points, closed, curveType, tension ) {
  24940. Curve.call( this );
  24941. this.type = 'CatmullRomCurve3';
  24942. this.points = points || [];
  24943. this.closed = closed || false;
  24944. this.curveType = curveType || 'centripetal';
  24945. this.tension = tension || 0.5;
  24946. }
  24947. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  24948. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  24949. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  24950. CatmullRomCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  24951. var point = optionalTarget || new Vector3();
  24952. var points = this.points;
  24953. var l = points.length;
  24954. var p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  24955. var intPoint = Math.floor( p );
  24956. var weight = p - intPoint;
  24957. if ( this.closed ) {
  24958. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  24959. } else if ( weight === 0 && intPoint === l - 1 ) {
  24960. intPoint = l - 2;
  24961. weight = 1;
  24962. }
  24963. var p0, p1, p2, p3; // 4 points
  24964. if ( this.closed || intPoint > 0 ) {
  24965. p0 = points[ ( intPoint - 1 ) % l ];
  24966. } else {
  24967. // extrapolate first point
  24968. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  24969. p0 = tmp;
  24970. }
  24971. p1 = points[ intPoint % l ];
  24972. p2 = points[ ( intPoint + 1 ) % l ];
  24973. if ( this.closed || intPoint + 2 < l ) {
  24974. p3 = points[ ( intPoint + 2 ) % l ];
  24975. } else {
  24976. // extrapolate last point
  24977. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  24978. p3 = tmp;
  24979. }
  24980. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  24981. // init Centripetal / Chordal Catmull-Rom
  24982. var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  24983. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  24984. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  24985. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  24986. // safety check for repeated points
  24987. if ( dt1 < 1e-4 ) dt1 = 1.0;
  24988. if ( dt0 < 1e-4 ) dt0 = dt1;
  24989. if ( dt2 < 1e-4 ) dt2 = dt1;
  24990. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  24991. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  24992. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  24993. } else if ( this.curveType === 'catmullrom' ) {
  24994. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  24995. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  24996. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  24997. }
  24998. point.set(
  24999. px.calc( weight ),
  25000. py.calc( weight ),
  25001. pz.calc( weight )
  25002. );
  25003. return point;
  25004. };
  25005. CatmullRomCurve3.prototype.copy = function ( source ) {
  25006. Curve.prototype.copy.call( this, source );
  25007. this.points = [];
  25008. for ( var i = 0, l = source.points.length; i < l; i ++ ) {
  25009. var point = source.points[ i ];
  25010. this.points.push( point.clone() );
  25011. }
  25012. this.closed = source.closed;
  25013. this.curveType = source.curveType;
  25014. this.tension = source.tension;
  25015. return this;
  25016. };
  25017. CatmullRomCurve3.prototype.toJSON = function () {
  25018. var data = Curve.prototype.toJSON.call( this );
  25019. data.points = [];
  25020. for ( var i = 0, l = this.points.length; i < l; i ++ ) {
  25021. var point = this.points[ i ];
  25022. data.points.push( point.toArray() );
  25023. }
  25024. data.closed = this.closed;
  25025. data.curveType = this.curveType;
  25026. data.tension = this.tension;
  25027. return data;
  25028. };
  25029. CatmullRomCurve3.prototype.fromJSON = function ( json ) {
  25030. Curve.prototype.fromJSON.call( this, json );
  25031. this.points = [];
  25032. for ( var i = 0, l = json.points.length; i < l; i ++ ) {
  25033. var point = json.points[ i ];
  25034. this.points.push( new Vector3().fromArray( point ) );
  25035. }
  25036. this.closed = json.closed;
  25037. this.curveType = json.curveType;
  25038. this.tension = json.tension;
  25039. return this;
  25040. };
  25041. /**
  25042. * @author zz85 / http://www.lab4games.net/zz85/blog
  25043. *
  25044. * Bezier Curves formulas obtained from
  25045. * http://en.wikipedia.org/wiki/Bézier_curve
  25046. */
  25047. function CatmullRom( t, p0, p1, p2, p3 ) {
  25048. var v0 = ( p2 - p0 ) * 0.5;
  25049. var v1 = ( p3 - p1 ) * 0.5;
  25050. var t2 = t * t;
  25051. var t3 = t * t2;
  25052. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  25053. }
  25054. //
  25055. function QuadraticBezierP0( t, p ) {
  25056. var k = 1 - t;
  25057. return k * k * p;
  25058. }
  25059. function QuadraticBezierP1( t, p ) {
  25060. return 2 * ( 1 - t ) * t * p;
  25061. }
  25062. function QuadraticBezierP2( t, p ) {
  25063. return t * t * p;
  25064. }
  25065. function QuadraticBezier( t, p0, p1, p2 ) {
  25066. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  25067. QuadraticBezierP2( t, p2 );
  25068. }
  25069. //
  25070. function CubicBezierP0( t, p ) {
  25071. var k = 1 - t;
  25072. return k * k * k * p;
  25073. }
  25074. function CubicBezierP1( t, p ) {
  25075. var k = 1 - t;
  25076. return 3 * k * k * t * p;
  25077. }
  25078. function CubicBezierP2( t, p ) {
  25079. return 3 * ( 1 - t ) * t * t * p;
  25080. }
  25081. function CubicBezierP3( t, p ) {
  25082. return t * t * t * p;
  25083. }
  25084. function CubicBezier( t, p0, p1, p2, p3 ) {
  25085. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  25086. CubicBezierP3( t, p3 );
  25087. }
  25088. function CubicBezierCurve( v0, v1, v2, v3 ) {
  25089. Curve.call( this );
  25090. this.type = 'CubicBezierCurve';
  25091. this.v0 = v0 || new Vector2();
  25092. this.v1 = v1 || new Vector2();
  25093. this.v2 = v2 || new Vector2();
  25094. this.v3 = v3 || new Vector2();
  25095. }
  25096. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  25097. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  25098. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  25099. CubicBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {
  25100. var point = optionalTarget || new Vector2();
  25101. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  25102. point.set(
  25103. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  25104. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  25105. );
  25106. return point;
  25107. };
  25108. CubicBezierCurve.prototype.copy = function ( source ) {
  25109. Curve.prototype.copy.call( this, source );
  25110. this.v0.copy( source.v0 );
  25111. this.v1.copy( source.v1 );
  25112. this.v2.copy( source.v2 );
  25113. this.v3.copy( source.v3 );
  25114. return this;
  25115. };
  25116. CubicBezierCurve.prototype.toJSON = function () {
  25117. var data = Curve.prototype.toJSON.call( this );
  25118. data.v0 = this.v0.toArray();
  25119. data.v1 = this.v1.toArray();
  25120. data.v2 = this.v2.toArray();
  25121. data.v3 = this.v3.toArray();
  25122. return data;
  25123. };
  25124. CubicBezierCurve.prototype.fromJSON = function ( json ) {
  25125. Curve.prototype.fromJSON.call( this, json );
  25126. this.v0.fromArray( json.v0 );
  25127. this.v1.fromArray( json.v1 );
  25128. this.v2.fromArray( json.v2 );
  25129. this.v3.fromArray( json.v3 );
  25130. return this;
  25131. };
  25132. function CubicBezierCurve3( v0, v1, v2, v3 ) {
  25133. Curve.call( this );
  25134. this.type = 'CubicBezierCurve3';
  25135. this.v0 = v0 || new Vector3();
  25136. this.v1 = v1 || new Vector3();
  25137. this.v2 = v2 || new Vector3();
  25138. this.v3 = v3 || new Vector3();
  25139. }
  25140. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  25141. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  25142. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  25143. CubicBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  25144. var point = optionalTarget || new Vector3();
  25145. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  25146. point.set(
  25147. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  25148. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  25149. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  25150. );
  25151. return point;
  25152. };
  25153. CubicBezierCurve3.prototype.copy = function ( source ) {
  25154. Curve.prototype.copy.call( this, source );
  25155. this.v0.copy( source.v0 );
  25156. this.v1.copy( source.v1 );
  25157. this.v2.copy( source.v2 );
  25158. this.v3.copy( source.v3 );
  25159. return this;
  25160. };
  25161. CubicBezierCurve3.prototype.toJSON = function () {
  25162. var data = Curve.prototype.toJSON.call( this );
  25163. data.v0 = this.v0.toArray();
  25164. data.v1 = this.v1.toArray();
  25165. data.v2 = this.v2.toArray();
  25166. data.v3 = this.v3.toArray();
  25167. return data;
  25168. };
  25169. CubicBezierCurve3.prototype.fromJSON = function ( json ) {
  25170. Curve.prototype.fromJSON.call( this, json );
  25171. this.v0.fromArray( json.v0 );
  25172. this.v1.fromArray( json.v1 );
  25173. this.v2.fromArray( json.v2 );
  25174. this.v3.fromArray( json.v3 );
  25175. return this;
  25176. };
  25177. function LineCurve( v1, v2 ) {
  25178. Curve.call( this );
  25179. this.type = 'LineCurve';
  25180. this.v1 = v1 || new Vector2();
  25181. this.v2 = v2 || new Vector2();
  25182. }
  25183. LineCurve.prototype = Object.create( Curve.prototype );
  25184. LineCurve.prototype.constructor = LineCurve;
  25185. LineCurve.prototype.isLineCurve = true;
  25186. LineCurve.prototype.getPoint = function ( t, optionalTarget ) {
  25187. var point = optionalTarget || new Vector2();
  25188. if ( t === 1 ) {
  25189. point.copy( this.v2 );
  25190. } else {
  25191. point.copy( this.v2 ).sub( this.v1 );
  25192. point.multiplyScalar( t ).add( this.v1 );
  25193. }
  25194. return point;
  25195. };
  25196. // Line curve is linear, so we can overwrite default getPointAt
  25197. LineCurve.prototype.getPointAt = function ( u, optionalTarget ) {
  25198. return this.getPoint( u, optionalTarget );
  25199. };
  25200. LineCurve.prototype.getTangent = function ( /* t */ ) {
  25201. var tangent = this.v2.clone().sub( this.v1 );
  25202. return tangent.normalize();
  25203. };
  25204. LineCurve.prototype.copy = function ( source ) {
  25205. Curve.prototype.copy.call( this, source );
  25206. this.v1.copy( source.v1 );
  25207. this.v2.copy( source.v2 );
  25208. return this;
  25209. };
  25210. LineCurve.prototype.toJSON = function () {
  25211. var data = Curve.prototype.toJSON.call( this );
  25212. data.v1 = this.v1.toArray();
  25213. data.v2 = this.v2.toArray();
  25214. return data;
  25215. };
  25216. LineCurve.prototype.fromJSON = function ( json ) {
  25217. Curve.prototype.fromJSON.call( this, json );
  25218. this.v1.fromArray( json.v1 );
  25219. this.v2.fromArray( json.v2 );
  25220. return this;
  25221. };
  25222. function LineCurve3( v1, v2 ) {
  25223. Curve.call( this );
  25224. this.type = 'LineCurve3';
  25225. this.v1 = v1 || new Vector3();
  25226. this.v2 = v2 || new Vector3();
  25227. }
  25228. LineCurve3.prototype = Object.create( Curve.prototype );
  25229. LineCurve3.prototype.constructor = LineCurve3;
  25230. LineCurve3.prototype.isLineCurve3 = true;
  25231. LineCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  25232. var point = optionalTarget || new Vector3();
  25233. if ( t === 1 ) {
  25234. point.copy( this.v2 );
  25235. } else {
  25236. point.copy( this.v2 ).sub( this.v1 );
  25237. point.multiplyScalar( t ).add( this.v1 );
  25238. }
  25239. return point;
  25240. };
  25241. // Line curve is linear, so we can overwrite default getPointAt
  25242. LineCurve3.prototype.getPointAt = function ( u, optionalTarget ) {
  25243. return this.getPoint( u, optionalTarget );
  25244. };
  25245. LineCurve3.prototype.copy = function ( source ) {
  25246. Curve.prototype.copy.call( this, source );
  25247. this.v1.copy( source.v1 );
  25248. this.v2.copy( source.v2 );
  25249. return this;
  25250. };
  25251. LineCurve3.prototype.toJSON = function () {
  25252. var data = Curve.prototype.toJSON.call( this );
  25253. data.v1 = this.v1.toArray();
  25254. data.v2 = this.v2.toArray();
  25255. return data;
  25256. };
  25257. LineCurve3.prototype.fromJSON = function ( json ) {
  25258. Curve.prototype.fromJSON.call( this, json );
  25259. this.v1.fromArray( json.v1 );
  25260. this.v2.fromArray( json.v2 );
  25261. return this;
  25262. };
  25263. function QuadraticBezierCurve( v0, v1, v2 ) {
  25264. Curve.call( this );
  25265. this.type = 'QuadraticBezierCurve';
  25266. this.v0 = v0 || new Vector2();
  25267. this.v1 = v1 || new Vector2();
  25268. this.v2 = v2 || new Vector2();
  25269. }
  25270. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  25271. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  25272. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  25273. QuadraticBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {
  25274. var point = optionalTarget || new Vector2();
  25275. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  25276. point.set(
  25277. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  25278. QuadraticBezier( t, v0.y, v1.y, v2.y )
  25279. );
  25280. return point;
  25281. };
  25282. QuadraticBezierCurve.prototype.copy = function ( source ) {
  25283. Curve.prototype.copy.call( this, source );
  25284. this.v0.copy( source.v0 );
  25285. this.v1.copy( source.v1 );
  25286. this.v2.copy( source.v2 );
  25287. return this;
  25288. };
  25289. QuadraticBezierCurve.prototype.toJSON = function () {
  25290. var data = Curve.prototype.toJSON.call( this );
  25291. data.v0 = this.v0.toArray();
  25292. data.v1 = this.v1.toArray();
  25293. data.v2 = this.v2.toArray();
  25294. return data;
  25295. };
  25296. QuadraticBezierCurve.prototype.fromJSON = function ( json ) {
  25297. Curve.prototype.fromJSON.call( this, json );
  25298. this.v0.fromArray( json.v0 );
  25299. this.v1.fromArray( json.v1 );
  25300. this.v2.fromArray( json.v2 );
  25301. return this;
  25302. };
  25303. function QuadraticBezierCurve3( v0, v1, v2 ) {
  25304. Curve.call( this );
  25305. this.type = 'QuadraticBezierCurve3';
  25306. this.v0 = v0 || new Vector3();
  25307. this.v1 = v1 || new Vector3();
  25308. this.v2 = v2 || new Vector3();
  25309. }
  25310. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  25311. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  25312. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  25313. QuadraticBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  25314. var point = optionalTarget || new Vector3();
  25315. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  25316. point.set(
  25317. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  25318. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  25319. QuadraticBezier( t, v0.z, v1.z, v2.z )
  25320. );
  25321. return point;
  25322. };
  25323. QuadraticBezierCurve3.prototype.copy = function ( source ) {
  25324. Curve.prototype.copy.call( this, source );
  25325. this.v0.copy( source.v0 );
  25326. this.v1.copy( source.v1 );
  25327. this.v2.copy( source.v2 );
  25328. return this;
  25329. };
  25330. QuadraticBezierCurve3.prototype.toJSON = function () {
  25331. var data = Curve.prototype.toJSON.call( this );
  25332. data.v0 = this.v0.toArray();
  25333. data.v1 = this.v1.toArray();
  25334. data.v2 = this.v2.toArray();
  25335. return data;
  25336. };
  25337. QuadraticBezierCurve3.prototype.fromJSON = function ( json ) {
  25338. Curve.prototype.fromJSON.call( this, json );
  25339. this.v0.fromArray( json.v0 );
  25340. this.v1.fromArray( json.v1 );
  25341. this.v2.fromArray( json.v2 );
  25342. return this;
  25343. };
  25344. function SplineCurve( points /* array of Vector2 */ ) {
  25345. Curve.call( this );
  25346. this.type = 'SplineCurve';
  25347. this.points = points || [];
  25348. }
  25349. SplineCurve.prototype = Object.create( Curve.prototype );
  25350. SplineCurve.prototype.constructor = SplineCurve;
  25351. SplineCurve.prototype.isSplineCurve = true;
  25352. SplineCurve.prototype.getPoint = function ( t, optionalTarget ) {
  25353. var point = optionalTarget || new Vector2();
  25354. var points = this.points;
  25355. var p = ( points.length - 1 ) * t;
  25356. var intPoint = Math.floor( p );
  25357. var weight = p - intPoint;
  25358. var p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  25359. var p1 = points[ intPoint ];
  25360. var p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  25361. var p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  25362. point.set(
  25363. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  25364. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  25365. );
  25366. return point;
  25367. };
  25368. SplineCurve.prototype.copy = function ( source ) {
  25369. Curve.prototype.copy.call( this, source );
  25370. this.points = [];
  25371. for ( var i = 0, l = source.points.length; i < l; i ++ ) {
  25372. var point = source.points[ i ];
  25373. this.points.push( point.clone() );
  25374. }
  25375. return this;
  25376. };
  25377. SplineCurve.prototype.toJSON = function () {
  25378. var data = Curve.prototype.toJSON.call( this );
  25379. data.points = [];
  25380. for ( var i = 0, l = this.points.length; i < l; i ++ ) {
  25381. var point = this.points[ i ];
  25382. data.points.push( point.toArray() );
  25383. }
  25384. return data;
  25385. };
  25386. SplineCurve.prototype.fromJSON = function ( json ) {
  25387. Curve.prototype.fromJSON.call( this, json );
  25388. this.points = [];
  25389. for ( var i = 0, l = json.points.length; i < l; i ++ ) {
  25390. var point = json.points[ i ];
  25391. this.points.push( new Vector2().fromArray( point ) );
  25392. }
  25393. return this;
  25394. };
  25395. var Curves = Object.freeze({
  25396. ArcCurve: ArcCurve,
  25397. CatmullRomCurve3: CatmullRomCurve3,
  25398. CubicBezierCurve: CubicBezierCurve,
  25399. CubicBezierCurve3: CubicBezierCurve3,
  25400. EllipseCurve: EllipseCurve,
  25401. LineCurve: LineCurve,
  25402. LineCurve3: LineCurve3,
  25403. QuadraticBezierCurve: QuadraticBezierCurve,
  25404. QuadraticBezierCurve3: QuadraticBezierCurve3,
  25405. SplineCurve: SplineCurve
  25406. });
  25407. /**
  25408. * @author zz85 / http://www.lab4games.net/zz85/blog
  25409. *
  25410. **/
  25411. /**************************************************************
  25412. * Curved Path - a curve path is simply a array of connected
  25413. * curves, but retains the api of a curve
  25414. **************************************************************/
  25415. function CurvePath() {
  25416. Curve.call( this );
  25417. this.type = 'CurvePath';
  25418. this.curves = [];
  25419. this.autoClose = false; // Automatically closes the path
  25420. }
  25421. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  25422. constructor: CurvePath,
  25423. add: function ( curve ) {
  25424. this.curves.push( curve );
  25425. },
  25426. closePath: function () {
  25427. // Add a line curve if start and end of lines are not connected
  25428. var startPoint = this.curves[ 0 ].getPoint( 0 );
  25429. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  25430. if ( ! startPoint.equals( endPoint ) ) {
  25431. this.curves.push( new LineCurve( endPoint, startPoint ) );
  25432. }
  25433. },
  25434. // To get accurate point with reference to
  25435. // entire path distance at time t,
  25436. // following has to be done:
  25437. // 1. Length of each sub path have to be known
  25438. // 2. Locate and identify type of curve
  25439. // 3. Get t for the curve
  25440. // 4. Return curve.getPointAt(t')
  25441. getPoint: function ( t ) {
  25442. var d = t * this.getLength();
  25443. var curveLengths = this.getCurveLengths();
  25444. var i = 0;
  25445. // To think about boundaries points.
  25446. while ( i < curveLengths.length ) {
  25447. if ( curveLengths[ i ] >= d ) {
  25448. var diff = curveLengths[ i ] - d;
  25449. var curve = this.curves[ i ];
  25450. var segmentLength = curve.getLength();
  25451. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  25452. return curve.getPointAt( u );
  25453. }
  25454. i ++;
  25455. }
  25456. return null;
  25457. // loop where sum != 0, sum > d , sum+1 <d
  25458. },
  25459. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  25460. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  25461. // getPoint() depends on getLength
  25462. getLength: function () {
  25463. var lens = this.getCurveLengths();
  25464. return lens[ lens.length - 1 ];
  25465. },
  25466. // cacheLengths must be recalculated.
  25467. updateArcLengths: function () {
  25468. this.needsUpdate = true;
  25469. this.cacheLengths = null;
  25470. this.getCurveLengths();
  25471. },
  25472. // Compute lengths and cache them
  25473. // We cannot overwrite getLengths() because UtoT mapping uses it.
  25474. getCurveLengths: function () {
  25475. // We use cache values if curves and cache array are same length
  25476. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  25477. return this.cacheLengths;
  25478. }
  25479. // Get length of sub-curve
  25480. // Push sums into cached array
  25481. var lengths = [], sums = 0;
  25482. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  25483. sums += this.curves[ i ].getLength();
  25484. lengths.push( sums );
  25485. }
  25486. this.cacheLengths = lengths;
  25487. return lengths;
  25488. },
  25489. getSpacedPoints: function ( divisions ) {
  25490. if ( divisions === undefined ) divisions = 40;
  25491. var points = [];
  25492. for ( var i = 0; i <= divisions; i ++ ) {
  25493. points.push( this.getPoint( i / divisions ) );
  25494. }
  25495. if ( this.autoClose ) {
  25496. points.push( points[ 0 ] );
  25497. }
  25498. return points;
  25499. },
  25500. getPoints: function ( divisions ) {
  25501. divisions = divisions || 12;
  25502. var points = [], last;
  25503. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  25504. var curve = curves[ i ];
  25505. var resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
  25506. : ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
  25507. : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
  25508. : divisions;
  25509. var pts = curve.getPoints( resolution );
  25510. for ( var j = 0; j < pts.length; j ++ ) {
  25511. var point = pts[ j ];
  25512. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  25513. points.push( point );
  25514. last = point;
  25515. }
  25516. }
  25517. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  25518. points.push( points[ 0 ] );
  25519. }
  25520. return points;
  25521. },
  25522. copy: function ( source ) {
  25523. Curve.prototype.copy.call( this, source );
  25524. this.curves = [];
  25525. for ( var i = 0, l = source.curves.length; i < l; i ++ ) {
  25526. var curve = source.curves[ i ];
  25527. this.curves.push( curve.clone() );
  25528. }
  25529. this.autoClose = source.autoClose;
  25530. return this;
  25531. },
  25532. toJSON: function () {
  25533. var data = Curve.prototype.toJSON.call( this );
  25534. data.autoClose = this.autoClose;
  25535. data.curves = [];
  25536. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  25537. var curve = this.curves[ i ];
  25538. data.curves.push( curve.toJSON() );
  25539. }
  25540. return data;
  25541. },
  25542. fromJSON: function ( json ) {
  25543. Curve.prototype.fromJSON.call( this, json );
  25544. this.autoClose = json.autoClose;
  25545. this.curves = [];
  25546. for ( var i = 0, l = json.curves.length; i < l; i ++ ) {
  25547. var curve = json.curves[ i ];
  25548. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  25549. }
  25550. return this;
  25551. }
  25552. } );
  25553. /**
  25554. * @author zz85 / http://www.lab4games.net/zz85/blog
  25555. * Creates free form 2d path using series of points, lines or curves.
  25556. **/
  25557. function Path( points ) {
  25558. CurvePath.call( this );
  25559. this.type = 'Path';
  25560. this.currentPoint = new Vector2();
  25561. if ( points ) {
  25562. this.setFromPoints( points );
  25563. }
  25564. }
  25565. Path.prototype = Object.assign( Object.create( CurvePath.prototype ), {
  25566. constructor: Path,
  25567. setFromPoints: function ( points ) {
  25568. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  25569. for ( var i = 1, l = points.length; i < l; i ++ ) {
  25570. this.lineTo( points[ i ].x, points[ i ].y );
  25571. }
  25572. },
  25573. moveTo: function ( x, y ) {
  25574. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  25575. },
  25576. lineTo: function ( x, y ) {
  25577. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  25578. this.curves.push( curve );
  25579. this.currentPoint.set( x, y );
  25580. },
  25581. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  25582. var curve = new QuadraticBezierCurve(
  25583. this.currentPoint.clone(),
  25584. new Vector2( aCPx, aCPy ),
  25585. new Vector2( aX, aY )
  25586. );
  25587. this.curves.push( curve );
  25588. this.currentPoint.set( aX, aY );
  25589. },
  25590. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  25591. var curve = new CubicBezierCurve(
  25592. this.currentPoint.clone(),
  25593. new Vector2( aCP1x, aCP1y ),
  25594. new Vector2( aCP2x, aCP2y ),
  25595. new Vector2( aX, aY )
  25596. );
  25597. this.curves.push( curve );
  25598. this.currentPoint.set( aX, aY );
  25599. },
  25600. splineThru: function ( pts /*Array of Vector*/ ) {
  25601. var npts = [ this.currentPoint.clone() ].concat( pts );
  25602. var curve = new SplineCurve( npts );
  25603. this.curves.push( curve );
  25604. this.currentPoint.copy( pts[ pts.length - 1 ] );
  25605. },
  25606. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25607. var x0 = this.currentPoint.x;
  25608. var y0 = this.currentPoint.y;
  25609. this.absarc( aX + x0, aY + y0, aRadius,
  25610. aStartAngle, aEndAngle, aClockwise );
  25611. },
  25612. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25613. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  25614. },
  25615. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25616. var x0 = this.currentPoint.x;
  25617. var y0 = this.currentPoint.y;
  25618. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25619. },
  25620. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25621. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25622. if ( this.curves.length > 0 ) {
  25623. // if a previous curve is present, attempt to join
  25624. var firstPoint = curve.getPoint( 0 );
  25625. if ( ! firstPoint.equals( this.currentPoint ) ) {
  25626. this.lineTo( firstPoint.x, firstPoint.y );
  25627. }
  25628. }
  25629. this.curves.push( curve );
  25630. var lastPoint = curve.getPoint( 1 );
  25631. this.currentPoint.copy( lastPoint );
  25632. },
  25633. copy: function ( source ) {
  25634. CurvePath.prototype.copy.call( this, source );
  25635. this.currentPoint.copy( source.currentPoint );
  25636. return this;
  25637. },
  25638. toJSON: function () {
  25639. var data = CurvePath.prototype.toJSON.call( this );
  25640. data.currentPoint = this.currentPoint.toArray();
  25641. return data;
  25642. },
  25643. fromJSON: function ( json ) {
  25644. CurvePath.prototype.fromJSON.call( this, json );
  25645. this.currentPoint.fromArray( json.currentPoint );
  25646. return this;
  25647. }
  25648. } );
  25649. /**
  25650. * @author zz85 / http://www.lab4games.net/zz85/blog
  25651. * Defines a 2d shape plane using paths.
  25652. **/
  25653. // STEP 1 Create a path.
  25654. // STEP 2 Turn path into shape.
  25655. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  25656. // STEP 3a - Extract points from each shape, turn to vertices
  25657. // STEP 3b - Triangulate each shape, add faces.
  25658. function Shape( points ) {
  25659. Path.call( this, points );
  25660. this.uuid = _Math.generateUUID();
  25661. this.type = 'Shape';
  25662. this.holes = [];
  25663. }
  25664. Shape.prototype = Object.assign( Object.create( Path.prototype ), {
  25665. constructor: Shape,
  25666. getPointsHoles: function ( divisions ) {
  25667. var holesPts = [];
  25668. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  25669. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  25670. }
  25671. return holesPts;
  25672. },
  25673. // get points of shape and holes (keypoints based on segments parameter)
  25674. extractPoints: function ( divisions ) {
  25675. return {
  25676. shape: this.getPoints( divisions ),
  25677. holes: this.getPointsHoles( divisions )
  25678. };
  25679. },
  25680. copy: function ( source ) {
  25681. Path.prototype.copy.call( this, source );
  25682. this.holes = [];
  25683. for ( var i = 0, l = source.holes.length; i < l; i ++ ) {
  25684. var hole = source.holes[ i ];
  25685. this.holes.push( hole.clone() );
  25686. }
  25687. return this;
  25688. },
  25689. toJSON: function () {
  25690. var data = Path.prototype.toJSON.call( this );
  25691. data.uuid = this.uuid;
  25692. data.holes = [];
  25693. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  25694. var hole = this.holes[ i ];
  25695. data.holes.push( hole.toJSON() );
  25696. }
  25697. return data;
  25698. },
  25699. fromJSON: function ( json ) {
  25700. Path.prototype.fromJSON.call( this, json );
  25701. this.uuid = json.uuid;
  25702. this.holes = [];
  25703. for ( var i = 0, l = json.holes.length; i < l; i ++ ) {
  25704. var hole = json.holes[ i ];
  25705. this.holes.push( new Path().fromJSON( hole ) );
  25706. }
  25707. return this;
  25708. }
  25709. } );
  25710. /**
  25711. * @author mrdoob / http://mrdoob.com/
  25712. * @author alteredq / http://alteredqualia.com/
  25713. */
  25714. function Light( color, intensity ) {
  25715. Object3D.call( this );
  25716. this.type = 'Light';
  25717. this.color = new Color( color );
  25718. this.intensity = intensity !== undefined ? intensity : 1;
  25719. this.receiveShadow = undefined;
  25720. }
  25721. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  25722. constructor: Light,
  25723. isLight: true,
  25724. copy: function ( source ) {
  25725. Object3D.prototype.copy.call( this, source );
  25726. this.color.copy( source.color );
  25727. this.intensity = source.intensity;
  25728. return this;
  25729. },
  25730. toJSON: function ( meta ) {
  25731. var data = Object3D.prototype.toJSON.call( this, meta );
  25732. data.object.color = this.color.getHex();
  25733. data.object.intensity = this.intensity;
  25734. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  25735. if ( this.distance !== undefined ) data.object.distance = this.distance;
  25736. if ( this.angle !== undefined ) data.object.angle = this.angle;
  25737. if ( this.decay !== undefined ) data.object.decay = this.decay;
  25738. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  25739. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  25740. return data;
  25741. }
  25742. } );
  25743. /**
  25744. * @author alteredq / http://alteredqualia.com/
  25745. */
  25746. function HemisphereLight( skyColor, groundColor, intensity ) {
  25747. Light.call( this, skyColor, intensity );
  25748. this.type = 'HemisphereLight';
  25749. this.castShadow = undefined;
  25750. this.position.copy( Object3D.DefaultUp );
  25751. this.updateMatrix();
  25752. this.groundColor = new Color( groundColor );
  25753. }
  25754. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  25755. constructor: HemisphereLight,
  25756. isHemisphereLight: true,
  25757. copy: function ( source ) {
  25758. Light.prototype.copy.call( this, source );
  25759. this.groundColor.copy( source.groundColor );
  25760. return this;
  25761. }
  25762. } );
  25763. /**
  25764. * @author mrdoob / http://mrdoob.com/
  25765. */
  25766. function LightShadow( camera ) {
  25767. this.camera = camera;
  25768. this.bias = 0;
  25769. this.radius = 1;
  25770. this.mapSize = new Vector2( 512, 512 );
  25771. this.map = null;
  25772. this.matrix = new Matrix4();
  25773. }
  25774. Object.assign( LightShadow.prototype, {
  25775. copy: function ( source ) {
  25776. this.camera = source.camera.clone();
  25777. this.bias = source.bias;
  25778. this.radius = source.radius;
  25779. this.mapSize.copy( source.mapSize );
  25780. return this;
  25781. },
  25782. clone: function () {
  25783. return new this.constructor().copy( this );
  25784. },
  25785. toJSON: function () {
  25786. var object = {};
  25787. if ( this.bias !== 0 ) object.bias = this.bias;
  25788. if ( this.radius !== 1 ) object.radius = this.radius;
  25789. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  25790. object.camera = this.camera.toJSON( false ).object;
  25791. delete object.camera.matrix;
  25792. return object;
  25793. }
  25794. } );
  25795. /**
  25796. * @author mrdoob / http://mrdoob.com/
  25797. */
  25798. function SpotLightShadow() {
  25799. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  25800. }
  25801. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  25802. constructor: SpotLightShadow,
  25803. isSpotLightShadow: true,
  25804. update: function ( light ) {
  25805. var camera = this.camera;
  25806. var fov = _Math.RAD2DEG * 2 * light.angle;
  25807. var aspect = this.mapSize.width / this.mapSize.height;
  25808. var far = light.distance || camera.far;
  25809. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  25810. camera.fov = fov;
  25811. camera.aspect = aspect;
  25812. camera.far = far;
  25813. camera.updateProjectionMatrix();
  25814. }
  25815. }
  25816. } );
  25817. /**
  25818. * @author alteredq / http://alteredqualia.com/
  25819. */
  25820. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  25821. Light.call( this, color, intensity );
  25822. this.type = 'SpotLight';
  25823. this.position.copy( Object3D.DefaultUp );
  25824. this.updateMatrix();
  25825. this.target = new Object3D();
  25826. Object.defineProperty( this, 'power', {
  25827. get: function () {
  25828. // intensity = power per solid angle.
  25829. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  25830. return this.intensity * Math.PI;
  25831. },
  25832. set: function ( power ) {
  25833. // intensity = power per solid angle.
  25834. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  25835. this.intensity = power / Math.PI;
  25836. }
  25837. } );
  25838. this.distance = ( distance !== undefined ) ? distance : 0;
  25839. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  25840. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  25841. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  25842. this.shadow = new SpotLightShadow();
  25843. }
  25844. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  25845. constructor: SpotLight,
  25846. isSpotLight: true,
  25847. copy: function ( source ) {
  25848. Light.prototype.copy.call( this, source );
  25849. this.distance = source.distance;
  25850. this.angle = source.angle;
  25851. this.penumbra = source.penumbra;
  25852. this.decay = source.decay;
  25853. this.target = source.target.clone();
  25854. this.shadow = source.shadow.clone();
  25855. return this;
  25856. }
  25857. } );
  25858. /**
  25859. * @author mrdoob / http://mrdoob.com/
  25860. */
  25861. function PointLight( color, intensity, distance, decay ) {
  25862. Light.call( this, color, intensity );
  25863. this.type = 'PointLight';
  25864. Object.defineProperty( this, 'power', {
  25865. get: function () {
  25866. // intensity = power per solid angle.
  25867. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  25868. return this.intensity * 4 * Math.PI;
  25869. },
  25870. set: function ( power ) {
  25871. // intensity = power per solid angle.
  25872. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  25873. this.intensity = power / ( 4 * Math.PI );
  25874. }
  25875. } );
  25876. this.distance = ( distance !== undefined ) ? distance : 0;
  25877. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  25878. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  25879. }
  25880. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  25881. constructor: PointLight,
  25882. isPointLight: true,
  25883. copy: function ( source ) {
  25884. Light.prototype.copy.call( this, source );
  25885. this.distance = source.distance;
  25886. this.decay = source.decay;
  25887. this.shadow = source.shadow.clone();
  25888. return this;
  25889. }
  25890. } );
  25891. /**
  25892. * @author alteredq / http://alteredqualia.com/
  25893. * @author arose / http://github.com/arose
  25894. */
  25895. function OrthographicCamera( left, right, top, bottom, near, far ) {
  25896. Camera.call( this );
  25897. this.type = 'OrthographicCamera';
  25898. this.zoom = 1;
  25899. this.view = null;
  25900. this.left = ( left !== undefined ) ? left : - 1;
  25901. this.right = ( right !== undefined ) ? right : 1;
  25902. this.top = ( top !== undefined ) ? top : 1;
  25903. this.bottom = ( bottom !== undefined ) ? bottom : - 1;
  25904. this.near = ( near !== undefined ) ? near : 0.1;
  25905. this.far = ( far !== undefined ) ? far : 2000;
  25906. this.updateProjectionMatrix();
  25907. }
  25908. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  25909. constructor: OrthographicCamera,
  25910. isOrthographicCamera: true,
  25911. copy: function ( source, recursive ) {
  25912. Camera.prototype.copy.call( this, source, recursive );
  25913. this.left = source.left;
  25914. this.right = source.right;
  25915. this.top = source.top;
  25916. this.bottom = source.bottom;
  25917. this.near = source.near;
  25918. this.far = source.far;
  25919. this.zoom = source.zoom;
  25920. this.view = source.view === null ? null : Object.assign( {}, source.view );
  25921. return this;
  25922. },
  25923. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  25924. if ( this.view === null ) {
  25925. this.view = {
  25926. enabled: true,
  25927. fullWidth: 1,
  25928. fullHeight: 1,
  25929. offsetX: 0,
  25930. offsetY: 0,
  25931. width: 1,
  25932. height: 1
  25933. };
  25934. }
  25935. this.view.enabled = true;
  25936. this.view.fullWidth = fullWidth;
  25937. this.view.fullHeight = fullHeight;
  25938. this.view.offsetX = x;
  25939. this.view.offsetY = y;
  25940. this.view.width = width;
  25941. this.view.height = height;
  25942. this.updateProjectionMatrix();
  25943. },
  25944. clearViewOffset: function () {
  25945. if ( this.view !== null ) {
  25946. this.view.enabled = false;
  25947. }
  25948. this.updateProjectionMatrix();
  25949. },
  25950. updateProjectionMatrix: function () {
  25951. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  25952. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  25953. var cx = ( this.right + this.left ) / 2;
  25954. var cy = ( this.top + this.bottom ) / 2;
  25955. var left = cx - dx;
  25956. var right = cx + dx;
  25957. var top = cy + dy;
  25958. var bottom = cy - dy;
  25959. if ( this.view !== null && this.view.enabled ) {
  25960. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  25961. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  25962. var scaleW = ( this.right - this.left ) / this.view.width;
  25963. var scaleH = ( this.top - this.bottom ) / this.view.height;
  25964. left += scaleW * ( this.view.offsetX / zoomW );
  25965. right = left + scaleW * ( this.view.width / zoomW );
  25966. top -= scaleH * ( this.view.offsetY / zoomH );
  25967. bottom = top - scaleH * ( this.view.height / zoomH );
  25968. }
  25969. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  25970. this.projectionMatrixInverse.getInverse( this.projectionMatrix );
  25971. },
  25972. toJSON: function ( meta ) {
  25973. var data = Object3D.prototype.toJSON.call( this, meta );
  25974. data.object.zoom = this.zoom;
  25975. data.object.left = this.left;
  25976. data.object.right = this.right;
  25977. data.object.top = this.top;
  25978. data.object.bottom = this.bottom;
  25979. data.object.near = this.near;
  25980. data.object.far = this.far;
  25981. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  25982. return data;
  25983. }
  25984. } );
  25985. /**
  25986. * @author mrdoob / http://mrdoob.com/
  25987. */
  25988. function DirectionalLightShadow( ) {
  25989. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  25990. }
  25991. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  25992. constructor: DirectionalLightShadow
  25993. } );
  25994. /**
  25995. * @author mrdoob / http://mrdoob.com/
  25996. * @author alteredq / http://alteredqualia.com/
  25997. */
  25998. function DirectionalLight( color, intensity ) {
  25999. Light.call( this, color, intensity );
  26000. this.type = 'DirectionalLight';
  26001. this.position.copy( Object3D.DefaultUp );
  26002. this.updateMatrix();
  26003. this.target = new Object3D();
  26004. this.shadow = new DirectionalLightShadow();
  26005. }
  26006. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  26007. constructor: DirectionalLight,
  26008. isDirectionalLight: true,
  26009. copy: function ( source ) {
  26010. Light.prototype.copy.call( this, source );
  26011. this.target = source.target.clone();
  26012. this.shadow = source.shadow.clone();
  26013. return this;
  26014. }
  26015. } );
  26016. /**
  26017. * @author mrdoob / http://mrdoob.com/
  26018. */
  26019. function AmbientLight( color, intensity ) {
  26020. Light.call( this, color, intensity );
  26021. this.type = 'AmbientLight';
  26022. this.castShadow = undefined;
  26023. }
  26024. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  26025. constructor: AmbientLight,
  26026. isAmbientLight: true
  26027. } );
  26028. /**
  26029. * @author abelnation / http://github.com/abelnation
  26030. */
  26031. function RectAreaLight( color, intensity, width, height ) {
  26032. Light.call( this, color, intensity );
  26033. this.type = 'RectAreaLight';
  26034. this.width = ( width !== undefined ) ? width : 10;
  26035. this.height = ( height !== undefined ) ? height : 10;
  26036. }
  26037. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  26038. constructor: RectAreaLight,
  26039. isRectAreaLight: true,
  26040. copy: function ( source ) {
  26041. Light.prototype.copy.call( this, source );
  26042. this.width = source.width;
  26043. this.height = source.height;
  26044. return this;
  26045. },
  26046. toJSON: function ( meta ) {
  26047. var data = Light.prototype.toJSON.call( this, meta );
  26048. data.object.width = this.width;
  26049. data.object.height = this.height;
  26050. return data;
  26051. }
  26052. } );
  26053. /**
  26054. * @author mrdoob / http://mrdoob.com/
  26055. */
  26056. function MaterialLoader( manager ) {
  26057. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  26058. this.textures = {};
  26059. }
  26060. Object.assign( MaterialLoader.prototype, {
  26061. load: function ( url, onLoad, onProgress, onError ) {
  26062. var scope = this;
  26063. var loader = new FileLoader( scope.manager );
  26064. loader.setPath( scope.path );
  26065. loader.load( url, function ( text ) {
  26066. onLoad( scope.parse( JSON.parse( text ) ) );
  26067. }, onProgress, onError );
  26068. },
  26069. parse: function ( json ) {
  26070. var textures = this.textures;
  26071. function getTexture( name ) {
  26072. if ( textures[ name ] === undefined ) {
  26073. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  26074. }
  26075. return textures[ name ];
  26076. }
  26077. var material = new Materials[ json.type ]();
  26078. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  26079. if ( json.name !== undefined ) material.name = json.name;
  26080. if ( json.color !== undefined ) material.color.setHex( json.color );
  26081. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  26082. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  26083. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  26084. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  26085. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  26086. if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat;
  26087. if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness;
  26088. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  26089. if ( json.fog !== undefined ) material.fog = json.fog;
  26090. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  26091. if ( json.blending !== undefined ) material.blending = json.blending;
  26092. if ( json.combine !== undefined ) material.combine = json.combine;
  26093. if ( json.side !== undefined ) material.side = json.side;
  26094. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  26095. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  26096. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  26097. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  26098. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  26099. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  26100. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  26101. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  26102. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  26103. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  26104. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  26105. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  26106. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  26107. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  26108. if ( json.scale !== undefined ) material.scale = json.scale;
  26109. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  26110. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  26111. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  26112. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  26113. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  26114. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  26115. if ( json.visible !== undefined ) material.visible = json.visible;
  26116. if ( json.userData !== undefined ) material.userData = json.userData;
  26117. // Shader Material
  26118. if ( json.uniforms !== undefined ) {
  26119. for ( var name in json.uniforms ) {
  26120. var uniform = json.uniforms[ name ];
  26121. material.uniforms[ name ] = {};
  26122. switch ( uniform.type ) {
  26123. case 't':
  26124. material.uniforms[ name ].value = getTexture( uniform.value );
  26125. break;
  26126. case 'c':
  26127. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  26128. break;
  26129. case 'v2':
  26130. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  26131. break;
  26132. case 'v3':
  26133. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  26134. break;
  26135. case 'v4':
  26136. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  26137. break;
  26138. case 'm4':
  26139. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  26140. break;
  26141. default:
  26142. material.uniforms[ name ].value = uniform.value;
  26143. }
  26144. }
  26145. }
  26146. if ( json.defines !== undefined ) material.defines = json.defines;
  26147. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  26148. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  26149. // Deprecated
  26150. if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
  26151. // for PointsMaterial
  26152. if ( json.size !== undefined ) material.size = json.size;
  26153. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  26154. // maps
  26155. if ( json.map !== undefined ) material.map = getTexture( json.map );
  26156. if ( json.alphaMap !== undefined ) {
  26157. material.alphaMap = getTexture( json.alphaMap );
  26158. material.transparent = true;
  26159. }
  26160. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  26161. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  26162. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  26163. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  26164. if ( json.normalScale !== undefined ) {
  26165. var normalScale = json.normalScale;
  26166. if ( Array.isArray( normalScale ) === false ) {
  26167. // Blender exporter used to export a scalar. See #7459
  26168. normalScale = [ normalScale, normalScale ];
  26169. }
  26170. material.normalScale = new Vector2().fromArray( normalScale );
  26171. }
  26172. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  26173. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  26174. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  26175. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  26176. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  26177. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  26178. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  26179. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  26180. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  26181. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  26182. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  26183. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  26184. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  26185. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  26186. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  26187. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  26188. return material;
  26189. },
  26190. setPath: function ( value ) {
  26191. this.path = value;
  26192. return this;
  26193. },
  26194. setTextures: function ( value ) {
  26195. this.textures = value;
  26196. return this;
  26197. }
  26198. } );
  26199. /**
  26200. * @author Don McCurdy / https://www.donmccurdy.com
  26201. */
  26202. var LoaderUtils = {
  26203. decodeText: function ( array ) {
  26204. if ( typeof TextDecoder !== 'undefined' ) {
  26205. return new TextDecoder().decode( array );
  26206. }
  26207. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  26208. // throws a "maximum call stack size exceeded" error for large arrays.
  26209. var s = '';
  26210. for ( var i = 0, il = array.length; i < il; i ++ ) {
  26211. // Implicitly assumes little-endian.
  26212. s += String.fromCharCode( array[ i ] );
  26213. }
  26214. // Merges multi-byte utf-8 characters.
  26215. return decodeURIComponent( escape( s ) );
  26216. },
  26217. extractUrlBase: function ( url ) {
  26218. var index = url.lastIndexOf( '/' );
  26219. if ( index === - 1 ) return './';
  26220. return url.substr( 0, index + 1 );
  26221. }
  26222. };
  26223. /**
  26224. * @author mrdoob / http://mrdoob.com/
  26225. */
  26226. function BufferGeometryLoader( manager ) {
  26227. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  26228. }
  26229. Object.assign( BufferGeometryLoader.prototype, {
  26230. load: function ( url, onLoad, onProgress, onError ) {
  26231. var scope = this;
  26232. var loader = new FileLoader( scope.manager );
  26233. loader.setPath( scope.path );
  26234. loader.load( url, function ( text ) {
  26235. onLoad( scope.parse( JSON.parse( text ) ) );
  26236. }, onProgress, onError );
  26237. },
  26238. parse: function ( json ) {
  26239. var geometry = new BufferGeometry();
  26240. var index = json.data.index;
  26241. if ( index !== undefined ) {
  26242. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  26243. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  26244. }
  26245. var attributes = json.data.attributes;
  26246. for ( var key in attributes ) {
  26247. var attribute = attributes[ key ];
  26248. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  26249. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  26250. }
  26251. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  26252. if ( groups !== undefined ) {
  26253. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  26254. var group = groups[ i ];
  26255. geometry.addGroup( group.start, group.count, group.materialIndex );
  26256. }
  26257. }
  26258. var boundingSphere = json.data.boundingSphere;
  26259. if ( boundingSphere !== undefined ) {
  26260. var center = new Vector3();
  26261. if ( boundingSphere.center !== undefined ) {
  26262. center.fromArray( boundingSphere.center );
  26263. }
  26264. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  26265. }
  26266. if ( json.name ) geometry.name = json.name;
  26267. if ( json.userData ) geometry.userData = json.userData;
  26268. return geometry;
  26269. },
  26270. setPath: function ( value ) {
  26271. this.path = value;
  26272. return this;
  26273. }
  26274. } );
  26275. var TYPED_ARRAYS = {
  26276. Int8Array: Int8Array,
  26277. Uint8Array: Uint8Array,
  26278. // Workaround for IE11 pre KB2929437. See #11440
  26279. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  26280. Int16Array: Int16Array,
  26281. Uint16Array: Uint16Array,
  26282. Int32Array: Int32Array,
  26283. Uint32Array: Uint32Array,
  26284. Float32Array: Float32Array,
  26285. Float64Array: Float64Array
  26286. };
  26287. /**
  26288. * @author alteredq / http://alteredqualia.com/
  26289. */
  26290. function Loader() {}
  26291. Loader.Handlers = {
  26292. handlers: [],
  26293. add: function ( regex, loader ) {
  26294. this.handlers.push( regex, loader );
  26295. },
  26296. get: function ( file ) {
  26297. var handlers = this.handlers;
  26298. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  26299. var regex = handlers[ i ];
  26300. var loader = handlers[ i + 1 ];
  26301. if ( regex.test( file ) ) {
  26302. return loader;
  26303. }
  26304. }
  26305. return null;
  26306. }
  26307. };
  26308. Object.assign( Loader.prototype, {
  26309. crossOrigin: 'anonymous',
  26310. onLoadStart: function () {},
  26311. onLoadProgress: function () {},
  26312. onLoadComplete: function () {},
  26313. initMaterials: function ( materials, texturePath, crossOrigin ) {
  26314. var array = [];
  26315. for ( var i = 0; i < materials.length; ++ i ) {
  26316. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  26317. }
  26318. return array;
  26319. },
  26320. createMaterial: ( function () {
  26321. var BlendingMode = {
  26322. NoBlending: NoBlending,
  26323. NormalBlending: NormalBlending,
  26324. AdditiveBlending: AdditiveBlending,
  26325. SubtractiveBlending: SubtractiveBlending,
  26326. MultiplyBlending: MultiplyBlending,
  26327. CustomBlending: CustomBlending
  26328. };
  26329. var color = new Color();
  26330. var textureLoader = new TextureLoader();
  26331. var materialLoader = new MaterialLoader();
  26332. return function createMaterial( m, texturePath, crossOrigin ) {
  26333. // convert from old material format
  26334. var textures = {};
  26335. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  26336. var fullPath = texturePath + path;
  26337. var loader = Loader.Handlers.get( fullPath );
  26338. var texture;
  26339. if ( loader !== null ) {
  26340. texture = loader.load( fullPath );
  26341. } else {
  26342. textureLoader.setCrossOrigin( crossOrigin );
  26343. texture = textureLoader.load( fullPath );
  26344. }
  26345. if ( repeat !== undefined ) {
  26346. texture.repeat.fromArray( repeat );
  26347. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  26348. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  26349. }
  26350. if ( offset !== undefined ) {
  26351. texture.offset.fromArray( offset );
  26352. }
  26353. if ( wrap !== undefined ) {
  26354. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  26355. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  26356. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  26357. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  26358. }
  26359. if ( anisotropy !== undefined ) {
  26360. texture.anisotropy = anisotropy;
  26361. }
  26362. var uuid = _Math.generateUUID();
  26363. textures[ uuid ] = texture;
  26364. return uuid;
  26365. }
  26366. //
  26367. var json = {
  26368. uuid: _Math.generateUUID(),
  26369. type: 'MeshLambertMaterial'
  26370. };
  26371. for ( var name in m ) {
  26372. var value = m[ name ];
  26373. switch ( name ) {
  26374. case 'DbgColor':
  26375. case 'DbgIndex':
  26376. case 'opticalDensity':
  26377. case 'illumination':
  26378. break;
  26379. case 'DbgName':
  26380. json.name = value;
  26381. break;
  26382. case 'blending':
  26383. json.blending = BlendingMode[ value ];
  26384. break;
  26385. case 'colorAmbient':
  26386. case 'mapAmbient':
  26387. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  26388. break;
  26389. case 'colorDiffuse':
  26390. json.color = color.fromArray( value ).getHex();
  26391. break;
  26392. case 'colorSpecular':
  26393. json.specular = color.fromArray( value ).getHex();
  26394. break;
  26395. case 'colorEmissive':
  26396. json.emissive = color.fromArray( value ).getHex();
  26397. break;
  26398. case 'specularCoef':
  26399. json.shininess = value;
  26400. break;
  26401. case 'shading':
  26402. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  26403. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  26404. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  26405. break;
  26406. case 'mapDiffuse':
  26407. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  26408. break;
  26409. case 'mapDiffuseRepeat':
  26410. case 'mapDiffuseOffset':
  26411. case 'mapDiffuseWrap':
  26412. case 'mapDiffuseAnisotropy':
  26413. break;
  26414. case 'mapEmissive':
  26415. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  26416. break;
  26417. case 'mapEmissiveRepeat':
  26418. case 'mapEmissiveOffset':
  26419. case 'mapEmissiveWrap':
  26420. case 'mapEmissiveAnisotropy':
  26421. break;
  26422. case 'mapLight':
  26423. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  26424. break;
  26425. case 'mapLightRepeat':
  26426. case 'mapLightOffset':
  26427. case 'mapLightWrap':
  26428. case 'mapLightAnisotropy':
  26429. break;
  26430. case 'mapAO':
  26431. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  26432. break;
  26433. case 'mapAORepeat':
  26434. case 'mapAOOffset':
  26435. case 'mapAOWrap':
  26436. case 'mapAOAnisotropy':
  26437. break;
  26438. case 'mapBump':
  26439. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  26440. break;
  26441. case 'mapBumpScale':
  26442. json.bumpScale = value;
  26443. break;
  26444. case 'mapBumpRepeat':
  26445. case 'mapBumpOffset':
  26446. case 'mapBumpWrap':
  26447. case 'mapBumpAnisotropy':
  26448. break;
  26449. case 'mapNormal':
  26450. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  26451. break;
  26452. case 'mapNormalFactor':
  26453. json.normalScale = value;
  26454. break;
  26455. case 'mapNormalRepeat':
  26456. case 'mapNormalOffset':
  26457. case 'mapNormalWrap':
  26458. case 'mapNormalAnisotropy':
  26459. break;
  26460. case 'mapSpecular':
  26461. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  26462. break;
  26463. case 'mapSpecularRepeat':
  26464. case 'mapSpecularOffset':
  26465. case 'mapSpecularWrap':
  26466. case 'mapSpecularAnisotropy':
  26467. break;
  26468. case 'mapMetalness':
  26469. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  26470. break;
  26471. case 'mapMetalnessRepeat':
  26472. case 'mapMetalnessOffset':
  26473. case 'mapMetalnessWrap':
  26474. case 'mapMetalnessAnisotropy':
  26475. break;
  26476. case 'mapRoughness':
  26477. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  26478. break;
  26479. case 'mapRoughnessRepeat':
  26480. case 'mapRoughnessOffset':
  26481. case 'mapRoughnessWrap':
  26482. case 'mapRoughnessAnisotropy':
  26483. break;
  26484. case 'mapAlpha':
  26485. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  26486. break;
  26487. case 'mapAlphaRepeat':
  26488. case 'mapAlphaOffset':
  26489. case 'mapAlphaWrap':
  26490. case 'mapAlphaAnisotropy':
  26491. break;
  26492. case 'flipSided':
  26493. json.side = BackSide;
  26494. break;
  26495. case 'doubleSided':
  26496. json.side = DoubleSide;
  26497. break;
  26498. case 'transparency':
  26499. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  26500. json.opacity = value;
  26501. break;
  26502. case 'depthTest':
  26503. case 'depthWrite':
  26504. case 'colorWrite':
  26505. case 'opacity':
  26506. case 'reflectivity':
  26507. case 'transparent':
  26508. case 'visible':
  26509. case 'wireframe':
  26510. json[ name ] = value;
  26511. break;
  26512. case 'vertexColors':
  26513. if ( value === true ) json.vertexColors = VertexColors;
  26514. if ( value === 'face' ) json.vertexColors = FaceColors;
  26515. break;
  26516. default:
  26517. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  26518. break;
  26519. }
  26520. }
  26521. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  26522. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  26523. if ( json.opacity < 1 ) json.transparent = true;
  26524. materialLoader.setTextures( textures );
  26525. return materialLoader.parse( json );
  26526. };
  26527. } )()
  26528. } );
  26529. /**
  26530. * @author mrdoob / http://mrdoob.com/
  26531. * @author alteredq / http://alteredqualia.com/
  26532. */
  26533. function JSONLoader( manager ) {
  26534. if ( typeof manager === 'boolean' ) {
  26535. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  26536. manager = undefined;
  26537. }
  26538. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  26539. this.withCredentials = false;
  26540. }
  26541. Object.assign( JSONLoader.prototype, {
  26542. crossOrigin: 'anonymous',
  26543. load: function ( url, onLoad, onProgress, onError ) {
  26544. var scope = this;
  26545. var path = ( this.path === undefined ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  26546. var loader = new FileLoader( this.manager );
  26547. loader.setPath( this.path );
  26548. loader.setWithCredentials( this.withCredentials );
  26549. loader.load( url, function ( text ) {
  26550. var json = JSON.parse( text );
  26551. var metadata = json.metadata;
  26552. if ( metadata !== undefined ) {
  26553. var type = metadata.type;
  26554. if ( type !== undefined ) {
  26555. if ( type.toLowerCase() === 'object' ) {
  26556. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  26557. return;
  26558. }
  26559. }
  26560. }
  26561. var object = scope.parse( json, path );
  26562. onLoad( object.geometry, object.materials );
  26563. }, onProgress, onError );
  26564. },
  26565. setPath: function ( value ) {
  26566. this.path = value;
  26567. return this;
  26568. },
  26569. setResourcePath: function ( value ) {
  26570. this.resourcePath = value;
  26571. return this;
  26572. },
  26573. setCrossOrigin: function ( value ) {
  26574. this.crossOrigin = value;
  26575. return this;
  26576. },
  26577. parse: ( function () {
  26578. function parseModel( json, geometry ) {
  26579. function isBitSet( value, position ) {
  26580. return value & ( 1 << position );
  26581. }
  26582. var i, j, fi,
  26583. offset, zLength,
  26584. colorIndex, normalIndex, uvIndex, materialIndex,
  26585. type,
  26586. isQuad,
  26587. hasMaterial,
  26588. hasFaceVertexUv,
  26589. hasFaceNormal, hasFaceVertexNormal,
  26590. hasFaceColor, hasFaceVertexColor,
  26591. vertex, face, faceA, faceB, hex, normal,
  26592. uvLayer, uv, u, v,
  26593. faces = json.faces,
  26594. vertices = json.vertices,
  26595. normals = json.normals,
  26596. colors = json.colors,
  26597. scale = json.scale,
  26598. nUvLayers = 0;
  26599. if ( json.uvs !== undefined ) {
  26600. // disregard empty arrays
  26601. for ( i = 0; i < json.uvs.length; i ++ ) {
  26602. if ( json.uvs[ i ].length ) nUvLayers ++;
  26603. }
  26604. for ( i = 0; i < nUvLayers; i ++ ) {
  26605. geometry.faceVertexUvs[ i ] = [];
  26606. }
  26607. }
  26608. offset = 0;
  26609. zLength = vertices.length;
  26610. while ( offset < zLength ) {
  26611. vertex = new Vector3();
  26612. vertex.x = vertices[ offset ++ ] * scale;
  26613. vertex.y = vertices[ offset ++ ] * scale;
  26614. vertex.z = vertices[ offset ++ ] * scale;
  26615. geometry.vertices.push( vertex );
  26616. }
  26617. offset = 0;
  26618. zLength = faces.length;
  26619. while ( offset < zLength ) {
  26620. type = faces[ offset ++ ];
  26621. isQuad = isBitSet( type, 0 );
  26622. hasMaterial = isBitSet( type, 1 );
  26623. hasFaceVertexUv = isBitSet( type, 3 );
  26624. hasFaceNormal = isBitSet( type, 4 );
  26625. hasFaceVertexNormal = isBitSet( type, 5 );
  26626. hasFaceColor = isBitSet( type, 6 );
  26627. hasFaceVertexColor = isBitSet( type, 7 );
  26628. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  26629. if ( isQuad ) {
  26630. faceA = new Face3();
  26631. faceA.a = faces[ offset ];
  26632. faceA.b = faces[ offset + 1 ];
  26633. faceA.c = faces[ offset + 3 ];
  26634. faceB = new Face3();
  26635. faceB.a = faces[ offset + 1 ];
  26636. faceB.b = faces[ offset + 2 ];
  26637. faceB.c = faces[ offset + 3 ];
  26638. offset += 4;
  26639. if ( hasMaterial ) {
  26640. materialIndex = faces[ offset ++ ];
  26641. faceA.materialIndex = materialIndex;
  26642. faceB.materialIndex = materialIndex;
  26643. }
  26644. // to get face <=> uv index correspondence
  26645. fi = geometry.faces.length;
  26646. if ( hasFaceVertexUv ) {
  26647. for ( i = 0; i < nUvLayers; i ++ ) {
  26648. uvLayer = json.uvs[ i ];
  26649. geometry.faceVertexUvs[ i ][ fi ] = [];
  26650. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  26651. for ( j = 0; j < 4; j ++ ) {
  26652. uvIndex = faces[ offset ++ ];
  26653. u = uvLayer[ uvIndex * 2 ];
  26654. v = uvLayer[ uvIndex * 2 + 1 ];
  26655. uv = new Vector2( u, v );
  26656. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  26657. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  26658. }
  26659. }
  26660. }
  26661. if ( hasFaceNormal ) {
  26662. normalIndex = faces[ offset ++ ] * 3;
  26663. faceA.normal.set(
  26664. normals[ normalIndex ++ ],
  26665. normals[ normalIndex ++ ],
  26666. normals[ normalIndex ]
  26667. );
  26668. faceB.normal.copy( faceA.normal );
  26669. }
  26670. if ( hasFaceVertexNormal ) {
  26671. for ( i = 0; i < 4; i ++ ) {
  26672. normalIndex = faces[ offset ++ ] * 3;
  26673. normal = new Vector3(
  26674. normals[ normalIndex ++ ],
  26675. normals[ normalIndex ++ ],
  26676. normals[ normalIndex ]
  26677. );
  26678. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  26679. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  26680. }
  26681. }
  26682. if ( hasFaceColor ) {
  26683. colorIndex = faces[ offset ++ ];
  26684. hex = colors[ colorIndex ];
  26685. faceA.color.setHex( hex );
  26686. faceB.color.setHex( hex );
  26687. }
  26688. if ( hasFaceVertexColor ) {
  26689. for ( i = 0; i < 4; i ++ ) {
  26690. colorIndex = faces[ offset ++ ];
  26691. hex = colors[ colorIndex ];
  26692. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  26693. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  26694. }
  26695. }
  26696. geometry.faces.push( faceA );
  26697. geometry.faces.push( faceB );
  26698. } else {
  26699. face = new Face3();
  26700. face.a = faces[ offset ++ ];
  26701. face.b = faces[ offset ++ ];
  26702. face.c = faces[ offset ++ ];
  26703. if ( hasMaterial ) {
  26704. materialIndex = faces[ offset ++ ];
  26705. face.materialIndex = materialIndex;
  26706. }
  26707. // to get face <=> uv index correspondence
  26708. fi = geometry.faces.length;
  26709. if ( hasFaceVertexUv ) {
  26710. for ( i = 0; i < nUvLayers; i ++ ) {
  26711. uvLayer = json.uvs[ i ];
  26712. geometry.faceVertexUvs[ i ][ fi ] = [];
  26713. for ( j = 0; j < 3; j ++ ) {
  26714. uvIndex = faces[ offset ++ ];
  26715. u = uvLayer[ uvIndex * 2 ];
  26716. v = uvLayer[ uvIndex * 2 + 1 ];
  26717. uv = new Vector2( u, v );
  26718. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  26719. }
  26720. }
  26721. }
  26722. if ( hasFaceNormal ) {
  26723. normalIndex = faces[ offset ++ ] * 3;
  26724. face.normal.set(
  26725. normals[ normalIndex ++ ],
  26726. normals[ normalIndex ++ ],
  26727. normals[ normalIndex ]
  26728. );
  26729. }
  26730. if ( hasFaceVertexNormal ) {
  26731. for ( i = 0; i < 3; i ++ ) {
  26732. normalIndex = faces[ offset ++ ] * 3;
  26733. normal = new Vector3(
  26734. normals[ normalIndex ++ ],
  26735. normals[ normalIndex ++ ],
  26736. normals[ normalIndex ]
  26737. );
  26738. face.vertexNormals.push( normal );
  26739. }
  26740. }
  26741. if ( hasFaceColor ) {
  26742. colorIndex = faces[ offset ++ ];
  26743. face.color.setHex( colors[ colorIndex ] );
  26744. }
  26745. if ( hasFaceVertexColor ) {
  26746. for ( i = 0; i < 3; i ++ ) {
  26747. colorIndex = faces[ offset ++ ];
  26748. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  26749. }
  26750. }
  26751. geometry.faces.push( face );
  26752. }
  26753. }
  26754. }
  26755. function parseSkin( json, geometry ) {
  26756. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  26757. if ( json.skinWeights ) {
  26758. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  26759. var x = json.skinWeights[ i ];
  26760. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  26761. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  26762. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  26763. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  26764. }
  26765. }
  26766. if ( json.skinIndices ) {
  26767. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  26768. var a = json.skinIndices[ i ];
  26769. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  26770. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  26771. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  26772. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  26773. }
  26774. }
  26775. geometry.bones = json.bones;
  26776. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  26777. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  26778. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  26779. }
  26780. }
  26781. function parseMorphing( json, geometry ) {
  26782. var scale = json.scale;
  26783. if ( json.morphTargets !== undefined ) {
  26784. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  26785. geometry.morphTargets[ i ] = {};
  26786. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  26787. geometry.morphTargets[ i ].vertices = [];
  26788. var dstVertices = geometry.morphTargets[ i ].vertices;
  26789. var srcVertices = json.morphTargets[ i ].vertices;
  26790. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  26791. var vertex = new Vector3();
  26792. vertex.x = srcVertices[ v ] * scale;
  26793. vertex.y = srcVertices[ v + 1 ] * scale;
  26794. vertex.z = srcVertices[ v + 2 ] * scale;
  26795. dstVertices.push( vertex );
  26796. }
  26797. }
  26798. }
  26799. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  26800. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  26801. var faces = geometry.faces;
  26802. var morphColors = json.morphColors[ 0 ].colors;
  26803. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  26804. faces[ i ].color.fromArray( morphColors, i * 3 );
  26805. }
  26806. }
  26807. }
  26808. function parseAnimations( json, geometry ) {
  26809. var outputAnimations = [];
  26810. // parse old style Bone/Hierarchy animations
  26811. var animations = [];
  26812. if ( json.animation !== undefined ) {
  26813. animations.push( json.animation );
  26814. }
  26815. if ( json.animations !== undefined ) {
  26816. if ( json.animations.length ) {
  26817. animations = animations.concat( json.animations );
  26818. } else {
  26819. animations.push( json.animations );
  26820. }
  26821. }
  26822. for ( var i = 0; i < animations.length; i ++ ) {
  26823. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  26824. if ( clip ) outputAnimations.push( clip );
  26825. }
  26826. // parse implicit morph animations
  26827. if ( geometry.morphTargets ) {
  26828. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  26829. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  26830. outputAnimations = outputAnimations.concat( morphAnimationClips );
  26831. }
  26832. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  26833. }
  26834. return function parse( json, path ) {
  26835. if ( json.data !== undefined ) {
  26836. // Geometry 4.0 spec
  26837. json = json.data;
  26838. }
  26839. if ( json.scale !== undefined ) {
  26840. json.scale = 1.0 / json.scale;
  26841. } else {
  26842. json.scale = 1.0;
  26843. }
  26844. var geometry = new Geometry();
  26845. parseModel( json, geometry );
  26846. parseSkin( json, geometry );
  26847. parseMorphing( json, geometry );
  26848. parseAnimations( json, geometry );
  26849. geometry.computeFaceNormals();
  26850. geometry.computeBoundingSphere();
  26851. if ( json.materials === undefined || json.materials.length === 0 ) {
  26852. return { geometry: geometry };
  26853. } else {
  26854. var materials = Loader.prototype.initMaterials( json.materials, this.resourcePath || path, this.crossOrigin );
  26855. return { geometry: geometry, materials: materials };
  26856. }
  26857. };
  26858. } )()
  26859. } );
  26860. /**
  26861. * @author mrdoob / http://mrdoob.com/
  26862. */
  26863. function ObjectLoader( manager ) {
  26864. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  26865. this.resourcePath = '';
  26866. }
  26867. Object.assign( ObjectLoader.prototype, {
  26868. crossOrigin: 'anonymous',
  26869. load: function ( url, onLoad, onProgress, onError ) {
  26870. var scope = this;
  26871. var path = ( this.path === undefined ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  26872. this.resourcePath = this.resourcePath || path;
  26873. var loader = new FileLoader( scope.manager );
  26874. loader.setPath( this.path );
  26875. loader.load( url, function ( text ) {
  26876. var json = null;
  26877. try {
  26878. json = JSON.parse( text );
  26879. } catch ( error ) {
  26880. if ( onError !== undefined ) onError( error );
  26881. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  26882. return;
  26883. }
  26884. var metadata = json.metadata;
  26885. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  26886. console.error( 'THREE.ObjectLoader: Can\'t load ' + url + '. Use THREE.JSONLoader instead.' );
  26887. return;
  26888. }
  26889. scope.parse( json, onLoad );
  26890. }, onProgress, onError );
  26891. },
  26892. setPath: function ( value ) {
  26893. this.path = value;
  26894. return this;
  26895. },
  26896. setResourcePath: function ( value ) {
  26897. this.resourcePath = value;
  26898. return this;
  26899. },
  26900. setCrossOrigin: function ( value ) {
  26901. this.crossOrigin = value;
  26902. return this;
  26903. },
  26904. parse: function ( json, onLoad ) {
  26905. var shapes = this.parseShape( json.shapes );
  26906. var geometries = this.parseGeometries( json.geometries, shapes );
  26907. var images = this.parseImages( json.images, function () {
  26908. if ( onLoad !== undefined ) onLoad( object );
  26909. } );
  26910. var textures = this.parseTextures( json.textures, images );
  26911. var materials = this.parseMaterials( json.materials, textures );
  26912. var object = this.parseObject( json.object, geometries, materials );
  26913. if ( json.animations ) {
  26914. object.animations = this.parseAnimations( json.animations );
  26915. }
  26916. if ( json.images === undefined || json.images.length === 0 ) {
  26917. if ( onLoad !== undefined ) onLoad( object );
  26918. }
  26919. return object;
  26920. },
  26921. parseShape: function ( json ) {
  26922. var shapes = {};
  26923. if ( json !== undefined ) {
  26924. for ( var i = 0, l = json.length; i < l; i ++ ) {
  26925. var shape = new Shape().fromJSON( json[ i ] );
  26926. shapes[ shape.uuid ] = shape;
  26927. }
  26928. }
  26929. return shapes;
  26930. },
  26931. parseGeometries: function ( json, shapes ) {
  26932. var geometries = {};
  26933. if ( json !== undefined ) {
  26934. var geometryLoader = new JSONLoader();
  26935. var bufferGeometryLoader = new BufferGeometryLoader();
  26936. for ( var i = 0, l = json.length; i < l; i ++ ) {
  26937. var geometry;
  26938. var data = json[ i ];
  26939. switch ( data.type ) {
  26940. case 'PlaneGeometry':
  26941. case 'PlaneBufferGeometry':
  26942. geometry = new Geometries[ data.type ](
  26943. data.width,
  26944. data.height,
  26945. data.widthSegments,
  26946. data.heightSegments
  26947. );
  26948. break;
  26949. case 'BoxGeometry':
  26950. case 'BoxBufferGeometry':
  26951. case 'CubeGeometry': // backwards compatible
  26952. geometry = new Geometries[ data.type ](
  26953. data.width,
  26954. data.height,
  26955. data.depth,
  26956. data.widthSegments,
  26957. data.heightSegments,
  26958. data.depthSegments
  26959. );
  26960. break;
  26961. case 'CircleGeometry':
  26962. case 'CircleBufferGeometry':
  26963. geometry = new Geometries[ data.type ](
  26964. data.radius,
  26965. data.segments,
  26966. data.thetaStart,
  26967. data.thetaLength
  26968. );
  26969. break;
  26970. case 'CylinderGeometry':
  26971. case 'CylinderBufferGeometry':
  26972. geometry = new Geometries[ data.type ](
  26973. data.radiusTop,
  26974. data.radiusBottom,
  26975. data.height,
  26976. data.radialSegments,
  26977. data.heightSegments,
  26978. data.openEnded,
  26979. data.thetaStart,
  26980. data.thetaLength
  26981. );
  26982. break;
  26983. case 'ConeGeometry':
  26984. case 'ConeBufferGeometry':
  26985. geometry = new Geometries[ data.type ](
  26986. data.radius,
  26987. data.height,
  26988. data.radialSegments,
  26989. data.heightSegments,
  26990. data.openEnded,
  26991. data.thetaStart,
  26992. data.thetaLength
  26993. );
  26994. break;
  26995. case 'SphereGeometry':
  26996. case 'SphereBufferGeometry':
  26997. geometry = new Geometries[ data.type ](
  26998. data.radius,
  26999. data.widthSegments,
  27000. data.heightSegments,
  27001. data.phiStart,
  27002. data.phiLength,
  27003. data.thetaStart,
  27004. data.thetaLength
  27005. );
  27006. break;
  27007. case 'DodecahedronGeometry':
  27008. case 'DodecahedronBufferGeometry':
  27009. case 'IcosahedronGeometry':
  27010. case 'IcosahedronBufferGeometry':
  27011. case 'OctahedronGeometry':
  27012. case 'OctahedronBufferGeometry':
  27013. case 'TetrahedronGeometry':
  27014. case 'TetrahedronBufferGeometry':
  27015. geometry = new Geometries[ data.type ](
  27016. data.radius,
  27017. data.detail
  27018. );
  27019. break;
  27020. case 'RingGeometry':
  27021. case 'RingBufferGeometry':
  27022. geometry = new Geometries[ data.type ](
  27023. data.innerRadius,
  27024. data.outerRadius,
  27025. data.thetaSegments,
  27026. data.phiSegments,
  27027. data.thetaStart,
  27028. data.thetaLength
  27029. );
  27030. break;
  27031. case 'TorusGeometry':
  27032. case 'TorusBufferGeometry':
  27033. geometry = new Geometries[ data.type ](
  27034. data.radius,
  27035. data.tube,
  27036. data.radialSegments,
  27037. data.tubularSegments,
  27038. data.arc
  27039. );
  27040. break;
  27041. case 'TorusKnotGeometry':
  27042. case 'TorusKnotBufferGeometry':
  27043. geometry = new Geometries[ data.type ](
  27044. data.radius,
  27045. data.tube,
  27046. data.tubularSegments,
  27047. data.radialSegments,
  27048. data.p,
  27049. data.q
  27050. );
  27051. break;
  27052. case 'LatheGeometry':
  27053. case 'LatheBufferGeometry':
  27054. geometry = new Geometries[ data.type ](
  27055. data.points,
  27056. data.segments,
  27057. data.phiStart,
  27058. data.phiLength
  27059. );
  27060. break;
  27061. case 'PolyhedronGeometry':
  27062. case 'PolyhedronBufferGeometry':
  27063. geometry = new Geometries[ data.type ](
  27064. data.vertices,
  27065. data.indices,
  27066. data.radius,
  27067. data.details
  27068. );
  27069. break;
  27070. case 'ShapeGeometry':
  27071. case 'ShapeBufferGeometry':
  27072. var geometryShapes = [];
  27073. for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  27074. var shape = shapes[ data.shapes[ j ] ];
  27075. geometryShapes.push( shape );
  27076. }
  27077. geometry = new Geometries[ data.type ](
  27078. geometryShapes,
  27079. data.curveSegments
  27080. );
  27081. break;
  27082. case 'ExtrudeGeometry':
  27083. case 'ExtrudeBufferGeometry':
  27084. var geometryShapes = [];
  27085. for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  27086. var shape = shapes[ data.shapes[ j ] ];
  27087. geometryShapes.push( shape );
  27088. }
  27089. var extrudePath = data.options.extrudePath;
  27090. if ( extrudePath !== undefined ) {
  27091. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  27092. }
  27093. geometry = new Geometries[ data.type ](
  27094. geometryShapes,
  27095. data.options
  27096. );
  27097. break;
  27098. case 'BufferGeometry':
  27099. geometry = bufferGeometryLoader.parse( data );
  27100. break;
  27101. case 'Geometry':
  27102. geometry = geometryLoader.parse( data, this.resourcePath ).geometry;
  27103. break;
  27104. default:
  27105. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  27106. continue;
  27107. }
  27108. geometry.uuid = data.uuid;
  27109. if ( data.name !== undefined ) geometry.name = data.name;
  27110. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  27111. geometries[ data.uuid ] = geometry;
  27112. }
  27113. }
  27114. return geometries;
  27115. },
  27116. parseMaterials: function ( json, textures ) {
  27117. var cache = {}; // MultiMaterial
  27118. var materials = {};
  27119. if ( json !== undefined ) {
  27120. var loader = new MaterialLoader();
  27121. loader.setTextures( textures );
  27122. for ( var i = 0, l = json.length; i < l; i ++ ) {
  27123. var data = json[ i ];
  27124. if ( data.type === 'MultiMaterial' ) {
  27125. // Deprecated
  27126. var array = [];
  27127. for ( var j = 0; j < data.materials.length; j ++ ) {
  27128. var material = data.materials[ j ];
  27129. if ( cache[ material.uuid ] === undefined ) {
  27130. cache[ material.uuid ] = loader.parse( material );
  27131. }
  27132. array.push( cache[ material.uuid ] );
  27133. }
  27134. materials[ data.uuid ] = array;
  27135. } else {
  27136. materials[ data.uuid ] = loader.parse( data );
  27137. cache[ data.uuid ] = materials[ data.uuid ];
  27138. }
  27139. }
  27140. }
  27141. return materials;
  27142. },
  27143. parseAnimations: function ( json ) {
  27144. var animations = [];
  27145. for ( var i = 0; i < json.length; i ++ ) {
  27146. var data = json[ i ];
  27147. var clip = AnimationClip.parse( data );
  27148. if ( data.uuid !== undefined ) clip.uuid = data.uuid;
  27149. animations.push( clip );
  27150. }
  27151. return animations;
  27152. },
  27153. parseImages: function ( json, onLoad ) {
  27154. var scope = this;
  27155. var images = {};
  27156. function loadImage( url ) {
  27157. scope.manager.itemStart( url );
  27158. return loader.load( url, function () {
  27159. scope.manager.itemEnd( url );
  27160. }, undefined, function () {
  27161. scope.manager.itemError( url );
  27162. scope.manager.itemEnd( url );
  27163. } );
  27164. }
  27165. if ( json !== undefined && json.length > 0 ) {
  27166. var manager = new LoadingManager( onLoad );
  27167. var loader = new ImageLoader( manager );
  27168. loader.setCrossOrigin( this.crossOrigin );
  27169. for ( var i = 0, il = json.length; i < il; i ++ ) {
  27170. var image = json[ i ];
  27171. var url = image.url;
  27172. if ( Array.isArray( url ) ) {
  27173. // load array of images e.g CubeTexture
  27174. images[ image.uuid ] = [];
  27175. for ( var j = 0, jl = url.length; j < jl; j ++ ) {
  27176. var currentUrl = url[ j ];
  27177. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( currentUrl ) ? currentUrl : scope.resourcePath + currentUrl;
  27178. images[ image.uuid ].push( loadImage( path ) );
  27179. }
  27180. } else {
  27181. // load single image
  27182. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.resourcePath + image.url;
  27183. images[ image.uuid ] = loadImage( path );
  27184. }
  27185. }
  27186. }
  27187. return images;
  27188. },
  27189. parseTextures: function ( json, images ) {
  27190. function parseConstant( value, type ) {
  27191. if ( typeof value === 'number' ) return value;
  27192. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  27193. return type[ value ];
  27194. }
  27195. var textures = {};
  27196. if ( json !== undefined ) {
  27197. for ( var i = 0, l = json.length; i < l; i ++ ) {
  27198. var data = json[ i ];
  27199. if ( data.image === undefined ) {
  27200. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  27201. }
  27202. if ( images[ data.image ] === undefined ) {
  27203. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  27204. }
  27205. var texture;
  27206. if ( Array.isArray( images[ data.image ] ) ) {
  27207. texture = new CubeTexture( images[ data.image ] );
  27208. } else {
  27209. texture = new Texture( images[ data.image ] );
  27210. }
  27211. texture.needsUpdate = true;
  27212. texture.uuid = data.uuid;
  27213. if ( data.name !== undefined ) texture.name = data.name;
  27214. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  27215. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  27216. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  27217. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  27218. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  27219. if ( data.wrap !== undefined ) {
  27220. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  27221. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  27222. }
  27223. if ( data.format !== undefined ) texture.format = data.format;
  27224. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  27225. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  27226. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  27227. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  27228. textures[ data.uuid ] = texture;
  27229. }
  27230. }
  27231. return textures;
  27232. },
  27233. parseObject: function ( data, geometries, materials ) {
  27234. var object;
  27235. function getGeometry( name ) {
  27236. if ( geometries[ name ] === undefined ) {
  27237. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  27238. }
  27239. return geometries[ name ];
  27240. }
  27241. function getMaterial( name ) {
  27242. if ( name === undefined ) return undefined;
  27243. if ( Array.isArray( name ) ) {
  27244. var array = [];
  27245. for ( var i = 0, l = name.length; i < l; i ++ ) {
  27246. var uuid = name[ i ];
  27247. if ( materials[ uuid ] === undefined ) {
  27248. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  27249. }
  27250. array.push( materials[ uuid ] );
  27251. }
  27252. return array;
  27253. }
  27254. if ( materials[ name ] === undefined ) {
  27255. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  27256. }
  27257. return materials[ name ];
  27258. }
  27259. switch ( data.type ) {
  27260. case 'Scene':
  27261. object = new Scene();
  27262. if ( data.background !== undefined ) {
  27263. if ( Number.isInteger( data.background ) ) {
  27264. object.background = new Color( data.background );
  27265. }
  27266. }
  27267. if ( data.fog !== undefined ) {
  27268. if ( data.fog.type === 'Fog' ) {
  27269. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  27270. } else if ( data.fog.type === 'FogExp2' ) {
  27271. object.fog = new FogExp2( data.fog.color, data.fog.density );
  27272. }
  27273. }
  27274. break;
  27275. case 'PerspectiveCamera':
  27276. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  27277. if ( data.focus !== undefined ) object.focus = data.focus;
  27278. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  27279. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  27280. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  27281. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  27282. break;
  27283. case 'OrthographicCamera':
  27284. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  27285. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  27286. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  27287. break;
  27288. case 'AmbientLight':
  27289. object = new AmbientLight( data.color, data.intensity );
  27290. break;
  27291. case 'DirectionalLight':
  27292. object = new DirectionalLight( data.color, data.intensity );
  27293. break;
  27294. case 'PointLight':
  27295. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  27296. break;
  27297. case 'RectAreaLight':
  27298. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  27299. break;
  27300. case 'SpotLight':
  27301. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  27302. break;
  27303. case 'HemisphereLight':
  27304. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  27305. break;
  27306. case 'SkinnedMesh':
  27307. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' );
  27308. case 'Mesh':
  27309. var geometry = getGeometry( data.geometry );
  27310. var material = getMaterial( data.material );
  27311. if ( geometry.bones && geometry.bones.length > 0 ) {
  27312. object = new SkinnedMesh( geometry, material );
  27313. } else {
  27314. object = new Mesh( geometry, material );
  27315. }
  27316. break;
  27317. case 'LOD':
  27318. object = new LOD();
  27319. break;
  27320. case 'Line':
  27321. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  27322. break;
  27323. case 'LineLoop':
  27324. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  27325. break;
  27326. case 'LineSegments':
  27327. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  27328. break;
  27329. case 'PointCloud':
  27330. case 'Points':
  27331. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  27332. break;
  27333. case 'Sprite':
  27334. object = new Sprite( getMaterial( data.material ) );
  27335. break;
  27336. case 'Group':
  27337. object = new Group();
  27338. break;
  27339. default:
  27340. object = new Object3D();
  27341. }
  27342. object.uuid = data.uuid;
  27343. if ( data.name !== undefined ) object.name = data.name;
  27344. if ( data.matrix !== undefined ) {
  27345. object.matrix.fromArray( data.matrix );
  27346. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  27347. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  27348. } else {
  27349. if ( data.position !== undefined ) object.position.fromArray( data.position );
  27350. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  27351. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  27352. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  27353. }
  27354. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  27355. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  27356. if ( data.shadow ) {
  27357. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  27358. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  27359. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  27360. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  27361. }
  27362. if ( data.visible !== undefined ) object.visible = data.visible;
  27363. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  27364. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  27365. if ( data.userData !== undefined ) object.userData = data.userData;
  27366. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  27367. if ( data.children !== undefined ) {
  27368. var children = data.children;
  27369. for ( var i = 0; i < children.length; i ++ ) {
  27370. object.add( this.parseObject( children[ i ], geometries, materials ) );
  27371. }
  27372. }
  27373. if ( data.type === 'LOD' ) {
  27374. var levels = data.levels;
  27375. for ( var l = 0; l < levels.length; l ++ ) {
  27376. var level = levels[ l ];
  27377. var child = object.getObjectByProperty( 'uuid', level.object );
  27378. if ( child !== undefined ) {
  27379. object.addLevel( child, level.distance );
  27380. }
  27381. }
  27382. }
  27383. return object;
  27384. }
  27385. } );
  27386. var TEXTURE_MAPPING = {
  27387. UVMapping: UVMapping,
  27388. CubeReflectionMapping: CubeReflectionMapping,
  27389. CubeRefractionMapping: CubeRefractionMapping,
  27390. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  27391. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  27392. SphericalReflectionMapping: SphericalReflectionMapping,
  27393. CubeUVReflectionMapping: CubeUVReflectionMapping,
  27394. CubeUVRefractionMapping: CubeUVRefractionMapping
  27395. };
  27396. var TEXTURE_WRAPPING = {
  27397. RepeatWrapping: RepeatWrapping,
  27398. ClampToEdgeWrapping: ClampToEdgeWrapping,
  27399. MirroredRepeatWrapping: MirroredRepeatWrapping
  27400. };
  27401. var TEXTURE_FILTER = {
  27402. NearestFilter: NearestFilter,
  27403. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  27404. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  27405. LinearFilter: LinearFilter,
  27406. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  27407. LinearMipMapLinearFilter: LinearMipMapLinearFilter
  27408. };
  27409. /**
  27410. * @author thespite / http://clicktorelease.com/
  27411. */
  27412. function ImageBitmapLoader( manager ) {
  27413. if ( typeof createImageBitmap === 'undefined' ) {
  27414. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  27415. }
  27416. if ( typeof fetch === 'undefined' ) {
  27417. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  27418. }
  27419. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  27420. this.options = undefined;
  27421. }
  27422. ImageBitmapLoader.prototype = {
  27423. constructor: ImageBitmapLoader,
  27424. setOptions: function setOptions( options ) {
  27425. this.options = options;
  27426. return this;
  27427. },
  27428. load: function ( url, onLoad, onProgress, onError ) {
  27429. if ( url === undefined ) url = '';
  27430. if ( this.path !== undefined ) url = this.path + url;
  27431. url = this.manager.resolveURL( url );
  27432. var scope = this;
  27433. var cached = Cache.get( url );
  27434. if ( cached !== undefined ) {
  27435. scope.manager.itemStart( url );
  27436. setTimeout( function () {
  27437. if ( onLoad ) onLoad( cached );
  27438. scope.manager.itemEnd( url );
  27439. }, 0 );
  27440. return cached;
  27441. }
  27442. fetch( url ).then( function ( res ) {
  27443. return res.blob();
  27444. } ).then( function ( blob ) {
  27445. return createImageBitmap( blob, scope.options );
  27446. } ).then( function ( imageBitmap ) {
  27447. Cache.add( url, imageBitmap );
  27448. if ( onLoad ) onLoad( imageBitmap );
  27449. scope.manager.itemEnd( url );
  27450. } ).catch( function ( e ) {
  27451. if ( onError ) onError( e );
  27452. scope.manager.itemError( url );
  27453. scope.manager.itemEnd( url );
  27454. } );
  27455. },
  27456. setCrossOrigin: function ( /* value */ ) {
  27457. return this;
  27458. },
  27459. setPath: function ( value ) {
  27460. this.path = value;
  27461. return this;
  27462. }
  27463. };
  27464. /**
  27465. * @author zz85 / http://www.lab4games.net/zz85/blog
  27466. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  27467. **/
  27468. function ShapePath() {
  27469. this.type = 'ShapePath';
  27470. this.color = new Color();
  27471. this.subPaths = [];
  27472. this.currentPath = null;
  27473. }
  27474. Object.assign( ShapePath.prototype, {
  27475. moveTo: function ( x, y ) {
  27476. this.currentPath = new Path();
  27477. this.subPaths.push( this.currentPath );
  27478. this.currentPath.moveTo( x, y );
  27479. },
  27480. lineTo: function ( x, y ) {
  27481. this.currentPath.lineTo( x, y );
  27482. },
  27483. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  27484. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  27485. },
  27486. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  27487. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  27488. },
  27489. splineThru: function ( pts ) {
  27490. this.currentPath.splineThru( pts );
  27491. },
  27492. toShapes: function ( isCCW, noHoles ) {
  27493. function toShapesNoHoles( inSubpaths ) {
  27494. var shapes = [];
  27495. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  27496. var tmpPath = inSubpaths[ i ];
  27497. var tmpShape = new Shape();
  27498. tmpShape.curves = tmpPath.curves;
  27499. shapes.push( tmpShape );
  27500. }
  27501. return shapes;
  27502. }
  27503. function isPointInsidePolygon( inPt, inPolygon ) {
  27504. var polyLen = inPolygon.length;
  27505. // inPt on polygon contour => immediate success or
  27506. // toggling of inside/outside at every single! intersection point of an edge
  27507. // with the horizontal line through inPt, left of inPt
  27508. // not counting lowerY endpoints of edges and whole edges on that line
  27509. var inside = false;
  27510. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  27511. var edgeLowPt = inPolygon[ p ];
  27512. var edgeHighPt = inPolygon[ q ];
  27513. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  27514. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  27515. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  27516. // not parallel
  27517. if ( edgeDy < 0 ) {
  27518. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  27519. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  27520. }
  27521. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  27522. if ( inPt.y === edgeLowPt.y ) {
  27523. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  27524. // continue; // no intersection or edgeLowPt => doesn't count !!!
  27525. } else {
  27526. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  27527. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  27528. if ( perpEdge < 0 ) continue;
  27529. inside = ! inside; // true intersection left of inPt
  27530. }
  27531. } else {
  27532. // parallel or collinear
  27533. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  27534. // edge lies on the same horizontal line as inPt
  27535. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  27536. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  27537. // continue;
  27538. }
  27539. }
  27540. return inside;
  27541. }
  27542. var isClockWise = ShapeUtils.isClockWise;
  27543. var subPaths = this.subPaths;
  27544. if ( subPaths.length === 0 ) return [];
  27545. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  27546. var solid, tmpPath, tmpShape, shapes = [];
  27547. if ( subPaths.length === 1 ) {
  27548. tmpPath = subPaths[ 0 ];
  27549. tmpShape = new Shape();
  27550. tmpShape.curves = tmpPath.curves;
  27551. shapes.push( tmpShape );
  27552. return shapes;
  27553. }
  27554. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  27555. holesFirst = isCCW ? ! holesFirst : holesFirst;
  27556. // console.log("Holes first", holesFirst);
  27557. var betterShapeHoles = [];
  27558. var newShapes = [];
  27559. var newShapeHoles = [];
  27560. var mainIdx = 0;
  27561. var tmpPoints;
  27562. newShapes[ mainIdx ] = undefined;
  27563. newShapeHoles[ mainIdx ] = [];
  27564. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  27565. tmpPath = subPaths[ i ];
  27566. tmpPoints = tmpPath.getPoints();
  27567. solid = isClockWise( tmpPoints );
  27568. solid = isCCW ? ! solid : solid;
  27569. if ( solid ) {
  27570. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  27571. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  27572. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  27573. if ( holesFirst ) mainIdx ++;
  27574. newShapeHoles[ mainIdx ] = [];
  27575. //console.log('cw', i);
  27576. } else {
  27577. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  27578. //console.log('ccw', i);
  27579. }
  27580. }
  27581. // only Holes? -> probably all Shapes with wrong orientation
  27582. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  27583. if ( newShapes.length > 1 ) {
  27584. var ambiguous = false;
  27585. var toChange = [];
  27586. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  27587. betterShapeHoles[ sIdx ] = [];
  27588. }
  27589. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  27590. var sho = newShapeHoles[ sIdx ];
  27591. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  27592. var ho = sho[ hIdx ];
  27593. var hole_unassigned = true;
  27594. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  27595. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  27596. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  27597. if ( hole_unassigned ) {
  27598. hole_unassigned = false;
  27599. betterShapeHoles[ s2Idx ].push( ho );
  27600. } else {
  27601. ambiguous = true;
  27602. }
  27603. }
  27604. }
  27605. if ( hole_unassigned ) {
  27606. betterShapeHoles[ sIdx ].push( ho );
  27607. }
  27608. }
  27609. }
  27610. // console.log("ambiguous: ", ambiguous);
  27611. if ( toChange.length > 0 ) {
  27612. // console.log("to change: ", toChange);
  27613. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  27614. }
  27615. }
  27616. var tmpHoles;
  27617. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  27618. tmpShape = newShapes[ i ].s;
  27619. shapes.push( tmpShape );
  27620. tmpHoles = newShapeHoles[ i ];
  27621. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  27622. tmpShape.holes.push( tmpHoles[ j ].h );
  27623. }
  27624. }
  27625. //console.log("shape", shapes);
  27626. return shapes;
  27627. }
  27628. } );
  27629. /**
  27630. * @author zz85 / http://www.lab4games.net/zz85/blog
  27631. * @author mrdoob / http://mrdoob.com/
  27632. */
  27633. function Font( data ) {
  27634. this.type = 'Font';
  27635. this.data = data;
  27636. }
  27637. Object.assign( Font.prototype, {
  27638. isFont: true,
  27639. generateShapes: function ( text, size ) {
  27640. if ( size === undefined ) size = 100;
  27641. var shapes = [];
  27642. var paths = createPaths( text, size, this.data );
  27643. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  27644. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  27645. }
  27646. return shapes;
  27647. }
  27648. } );
  27649. function createPaths( text, size, data ) {
  27650. var chars = Array.from ? Array.from( text ) : String( text ).split( '' ); // see #13988
  27651. var scale = size / data.resolution;
  27652. var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  27653. var paths = [];
  27654. var offsetX = 0, offsetY = 0;
  27655. for ( var i = 0; i < chars.length; i ++ ) {
  27656. var char = chars[ i ];
  27657. if ( char === '\n' ) {
  27658. offsetX = 0;
  27659. offsetY -= line_height;
  27660. } else {
  27661. var ret = createPath( char, scale, offsetX, offsetY, data );
  27662. offsetX += ret.offsetX;
  27663. paths.push( ret.path );
  27664. }
  27665. }
  27666. return paths;
  27667. }
  27668. function createPath( char, scale, offsetX, offsetY, data ) {
  27669. var glyph = data.glyphs[ char ] || data.glyphs[ '?' ];
  27670. if ( ! glyph ) return;
  27671. var path = new ShapePath();
  27672. var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  27673. if ( glyph.o ) {
  27674. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  27675. for ( var i = 0, l = outline.length; i < l; ) {
  27676. var action = outline[ i ++ ];
  27677. switch ( action ) {
  27678. case 'm': // moveTo
  27679. x = outline[ i ++ ] * scale + offsetX;
  27680. y = outline[ i ++ ] * scale + offsetY;
  27681. path.moveTo( x, y );
  27682. break;
  27683. case 'l': // lineTo
  27684. x = outline[ i ++ ] * scale + offsetX;
  27685. y = outline[ i ++ ] * scale + offsetY;
  27686. path.lineTo( x, y );
  27687. break;
  27688. case 'q': // quadraticCurveTo
  27689. cpx = outline[ i ++ ] * scale + offsetX;
  27690. cpy = outline[ i ++ ] * scale + offsetY;
  27691. cpx1 = outline[ i ++ ] * scale + offsetX;
  27692. cpy1 = outline[ i ++ ] * scale + offsetY;
  27693. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  27694. break;
  27695. case 'b': // bezierCurveTo
  27696. cpx = outline[ i ++ ] * scale + offsetX;
  27697. cpy = outline[ i ++ ] * scale + offsetY;
  27698. cpx1 = outline[ i ++ ] * scale + offsetX;
  27699. cpy1 = outline[ i ++ ] * scale + offsetY;
  27700. cpx2 = outline[ i ++ ] * scale + offsetX;
  27701. cpy2 = outline[ i ++ ] * scale + offsetY;
  27702. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  27703. break;
  27704. }
  27705. }
  27706. }
  27707. return { offsetX: glyph.ha * scale, path: path };
  27708. }
  27709. /**
  27710. * @author mrdoob / http://mrdoob.com/
  27711. */
  27712. function FontLoader( manager ) {
  27713. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  27714. }
  27715. Object.assign( FontLoader.prototype, {
  27716. load: function ( url, onLoad, onProgress, onError ) {
  27717. var scope = this;
  27718. var loader = new FileLoader( this.manager );
  27719. loader.setPath( this.path );
  27720. loader.load( url, function ( text ) {
  27721. var json;
  27722. try {
  27723. json = JSON.parse( text );
  27724. } catch ( e ) {
  27725. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  27726. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  27727. }
  27728. var font = scope.parse( json );
  27729. if ( onLoad ) onLoad( font );
  27730. }, onProgress, onError );
  27731. },
  27732. parse: function ( json ) {
  27733. return new Font( json );
  27734. },
  27735. setPath: function ( value ) {
  27736. this.path = value;
  27737. return this;
  27738. }
  27739. } );
  27740. /**
  27741. * @author mrdoob / http://mrdoob.com/
  27742. */
  27743. var context;
  27744. var AudioContext = {
  27745. getContext: function () {
  27746. if ( context === undefined ) {
  27747. context = new ( window.AudioContext || window.webkitAudioContext )();
  27748. }
  27749. return context;
  27750. },
  27751. setContext: function ( value ) {
  27752. context = value;
  27753. }
  27754. };
  27755. /**
  27756. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  27757. */
  27758. function AudioLoader( manager ) {
  27759. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  27760. }
  27761. Object.assign( AudioLoader.prototype, {
  27762. load: function ( url, onLoad, onProgress, onError ) {
  27763. var loader = new FileLoader( this.manager );
  27764. loader.setResponseType( 'arraybuffer' );
  27765. loader.setPath( this.path );
  27766. loader.load( url, function ( buffer ) {
  27767. // Create a copy of the buffer. The `decodeAudioData` method
  27768. // detaches the buffer when complete, preventing reuse.
  27769. var bufferCopy = buffer.slice( 0 );
  27770. var context = AudioContext.getContext();
  27771. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  27772. onLoad( audioBuffer );
  27773. } );
  27774. }, onProgress, onError );
  27775. },
  27776. setPath: function ( value ) {
  27777. this.path = value;
  27778. return this;
  27779. }
  27780. } );
  27781. /**
  27782. * @author mrdoob / http://mrdoob.com/
  27783. */
  27784. function StereoCamera() {
  27785. this.type = 'StereoCamera';
  27786. this.aspect = 1;
  27787. this.eyeSep = 0.064;
  27788. this.cameraL = new PerspectiveCamera();
  27789. this.cameraL.layers.enable( 1 );
  27790. this.cameraL.matrixAutoUpdate = false;
  27791. this.cameraR = new PerspectiveCamera();
  27792. this.cameraR.layers.enable( 2 );
  27793. this.cameraR.matrixAutoUpdate = false;
  27794. }
  27795. Object.assign( StereoCamera.prototype, {
  27796. update: ( function () {
  27797. var instance, focus, fov, aspect, near, far, zoom, eyeSep;
  27798. var eyeRight = new Matrix4();
  27799. var eyeLeft = new Matrix4();
  27800. return function update( camera ) {
  27801. var needsUpdate = instance !== this || focus !== camera.focus || fov !== camera.fov ||
  27802. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  27803. far !== camera.far || zoom !== camera.zoom || eyeSep !== this.eyeSep;
  27804. if ( needsUpdate ) {
  27805. instance = this;
  27806. focus = camera.focus;
  27807. fov = camera.fov;
  27808. aspect = camera.aspect * this.aspect;
  27809. near = camera.near;
  27810. far = camera.far;
  27811. zoom = camera.zoom;
  27812. // Off-axis stereoscopic effect based on
  27813. // http://paulbourke.net/stereographics/stereorender/
  27814. var projectionMatrix = camera.projectionMatrix.clone();
  27815. eyeSep = this.eyeSep / 2;
  27816. var eyeSepOnProjection = eyeSep * near / focus;
  27817. var ymax = ( near * Math.tan( _Math.DEG2RAD * fov * 0.5 ) ) / zoom;
  27818. var xmin, xmax;
  27819. // translate xOffset
  27820. eyeLeft.elements[ 12 ] = - eyeSep;
  27821. eyeRight.elements[ 12 ] = eyeSep;
  27822. // for left eye
  27823. xmin = - ymax * aspect + eyeSepOnProjection;
  27824. xmax = ymax * aspect + eyeSepOnProjection;
  27825. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  27826. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  27827. this.cameraL.projectionMatrix.copy( projectionMatrix );
  27828. // for right eye
  27829. xmin = - ymax * aspect - eyeSepOnProjection;
  27830. xmax = ymax * aspect - eyeSepOnProjection;
  27831. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  27832. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  27833. this.cameraR.projectionMatrix.copy( projectionMatrix );
  27834. }
  27835. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  27836. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  27837. };
  27838. } )()
  27839. } );
  27840. /**
  27841. * Camera for rendering cube maps
  27842. * - renders scene into axis-aligned cube
  27843. *
  27844. * @author alteredq / http://alteredqualia.com/
  27845. */
  27846. function CubeCamera( near, far, cubeResolution, options ) {
  27847. Object3D.call( this );
  27848. this.type = 'CubeCamera';
  27849. var fov = 90, aspect = 1;
  27850. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  27851. cameraPX.up.set( 0, - 1, 0 );
  27852. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  27853. this.add( cameraPX );
  27854. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  27855. cameraNX.up.set( 0, - 1, 0 );
  27856. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  27857. this.add( cameraNX );
  27858. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  27859. cameraPY.up.set( 0, 0, 1 );
  27860. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  27861. this.add( cameraPY );
  27862. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  27863. cameraNY.up.set( 0, 0, - 1 );
  27864. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  27865. this.add( cameraNY );
  27866. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  27867. cameraPZ.up.set( 0, - 1, 0 );
  27868. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  27869. this.add( cameraPZ );
  27870. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  27871. cameraNZ.up.set( 0, - 1, 0 );
  27872. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  27873. this.add( cameraNZ );
  27874. options = options || { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  27875. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  27876. this.renderTarget.texture.name = "CubeCamera";
  27877. this.update = function ( renderer, scene ) {
  27878. if ( this.parent === null ) this.updateMatrixWorld();
  27879. var renderTarget = this.renderTarget;
  27880. var generateMipmaps = renderTarget.texture.generateMipmaps;
  27881. renderTarget.texture.generateMipmaps = false;
  27882. renderTarget.activeCubeFace = 0;
  27883. renderer.render( scene, cameraPX, renderTarget );
  27884. renderTarget.activeCubeFace = 1;
  27885. renderer.render( scene, cameraNX, renderTarget );
  27886. renderTarget.activeCubeFace = 2;
  27887. renderer.render( scene, cameraPY, renderTarget );
  27888. renderTarget.activeCubeFace = 3;
  27889. renderer.render( scene, cameraNY, renderTarget );
  27890. renderTarget.activeCubeFace = 4;
  27891. renderer.render( scene, cameraPZ, renderTarget );
  27892. renderTarget.texture.generateMipmaps = generateMipmaps;
  27893. renderTarget.activeCubeFace = 5;
  27894. renderer.render( scene, cameraNZ, renderTarget );
  27895. renderer.setRenderTarget( null );
  27896. };
  27897. this.clear = function ( renderer, color, depth, stencil ) {
  27898. var renderTarget = this.renderTarget;
  27899. for ( var i = 0; i < 6; i ++ ) {
  27900. renderTarget.activeCubeFace = i;
  27901. renderer.setRenderTarget( renderTarget );
  27902. renderer.clear( color, depth, stencil );
  27903. }
  27904. renderer.setRenderTarget( null );
  27905. };
  27906. }
  27907. CubeCamera.prototype = Object.create( Object3D.prototype );
  27908. CubeCamera.prototype.constructor = CubeCamera;
  27909. /**
  27910. * @author alteredq / http://alteredqualia.com/
  27911. */
  27912. function Clock( autoStart ) {
  27913. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  27914. this.startTime = 0;
  27915. this.oldTime = 0;
  27916. this.elapsedTime = 0;
  27917. this.running = false;
  27918. }
  27919. Object.assign( Clock.prototype, {
  27920. start: function () {
  27921. this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  27922. this.oldTime = this.startTime;
  27923. this.elapsedTime = 0;
  27924. this.running = true;
  27925. },
  27926. stop: function () {
  27927. this.getElapsedTime();
  27928. this.running = false;
  27929. this.autoStart = false;
  27930. },
  27931. getElapsedTime: function () {
  27932. this.getDelta();
  27933. return this.elapsedTime;
  27934. },
  27935. getDelta: function () {
  27936. var diff = 0;
  27937. if ( this.autoStart && ! this.running ) {
  27938. this.start();
  27939. return 0;
  27940. }
  27941. if ( this.running ) {
  27942. var newTime = ( typeof performance === 'undefined' ? Date : performance ).now();
  27943. diff = ( newTime - this.oldTime ) / 1000;
  27944. this.oldTime = newTime;
  27945. this.elapsedTime += diff;
  27946. }
  27947. return diff;
  27948. }
  27949. } );
  27950. /**
  27951. * @author mrdoob / http://mrdoob.com/
  27952. */
  27953. function AudioListener() {
  27954. Object3D.call( this );
  27955. this.type = 'AudioListener';
  27956. this.context = AudioContext.getContext();
  27957. this.gain = this.context.createGain();
  27958. this.gain.connect( this.context.destination );
  27959. this.filter = null;
  27960. this.timeDelta = 0;
  27961. }
  27962. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  27963. constructor: AudioListener,
  27964. getInput: function () {
  27965. return this.gain;
  27966. },
  27967. removeFilter: function ( ) {
  27968. if ( this.filter !== null ) {
  27969. this.gain.disconnect( this.filter );
  27970. this.filter.disconnect( this.context.destination );
  27971. this.gain.connect( this.context.destination );
  27972. this.filter = null;
  27973. }
  27974. return this;
  27975. },
  27976. getFilter: function () {
  27977. return this.filter;
  27978. },
  27979. setFilter: function ( value ) {
  27980. if ( this.filter !== null ) {
  27981. this.gain.disconnect( this.filter );
  27982. this.filter.disconnect( this.context.destination );
  27983. } else {
  27984. this.gain.disconnect( this.context.destination );
  27985. }
  27986. this.filter = value;
  27987. this.gain.connect( this.filter );
  27988. this.filter.connect( this.context.destination );
  27989. return this;
  27990. },
  27991. getMasterVolume: function () {
  27992. return this.gain.gain.value;
  27993. },
  27994. setMasterVolume: function ( value ) {
  27995. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  27996. return this;
  27997. },
  27998. updateMatrixWorld: ( function () {
  27999. var position = new Vector3();
  28000. var quaternion = new Quaternion();
  28001. var scale = new Vector3();
  28002. var orientation = new Vector3();
  28003. var clock = new Clock();
  28004. return function updateMatrixWorld( force ) {
  28005. Object3D.prototype.updateMatrixWorld.call( this, force );
  28006. var listener = this.context.listener;
  28007. var up = this.up;
  28008. this.timeDelta = clock.getDelta();
  28009. this.matrixWorld.decompose( position, quaternion, scale );
  28010. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  28011. if ( listener.positionX ) {
  28012. // code path for Chrome (see #14393)
  28013. var endTime = this.context.currentTime + this.timeDelta;
  28014. listener.positionX.linearRampToValueAtTime( position.x, endTime );
  28015. listener.positionY.linearRampToValueAtTime( position.y, endTime );
  28016. listener.positionZ.linearRampToValueAtTime( position.z, endTime );
  28017. listener.forwardX.linearRampToValueAtTime( orientation.x, endTime );
  28018. listener.forwardY.linearRampToValueAtTime( orientation.y, endTime );
  28019. listener.forwardZ.linearRampToValueAtTime( orientation.z, endTime );
  28020. listener.upX.linearRampToValueAtTime( up.x, endTime );
  28021. listener.upY.linearRampToValueAtTime( up.y, endTime );
  28022. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  28023. } else {
  28024. listener.setPosition( position.x, position.y, position.z );
  28025. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  28026. }
  28027. };
  28028. } )()
  28029. } );
  28030. /**
  28031. * @author mrdoob / http://mrdoob.com/
  28032. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  28033. */
  28034. function Audio( listener ) {
  28035. Object3D.call( this );
  28036. this.type = 'Audio';
  28037. this.listener = listener;
  28038. this.context = listener.context;
  28039. this.gain = this.context.createGain();
  28040. this.gain.connect( listener.getInput() );
  28041. this.autoplay = false;
  28042. this.buffer = null;
  28043. this.loop = false;
  28044. this.startTime = 0;
  28045. this.offset = 0;
  28046. this.playbackRate = 1;
  28047. this.isPlaying = false;
  28048. this.hasPlaybackControl = true;
  28049. this.sourceType = 'empty';
  28050. this.filters = [];
  28051. }
  28052. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  28053. constructor: Audio,
  28054. getOutput: function () {
  28055. return this.gain;
  28056. },
  28057. setNodeSource: function ( audioNode ) {
  28058. this.hasPlaybackControl = false;
  28059. this.sourceType = 'audioNode';
  28060. this.source = audioNode;
  28061. this.connect();
  28062. return this;
  28063. },
  28064. setMediaElementSource: function ( mediaElement ) {
  28065. this.hasPlaybackControl = false;
  28066. this.sourceType = 'mediaNode';
  28067. this.source = this.context.createMediaElementSource( mediaElement );
  28068. this.connect();
  28069. return this;
  28070. },
  28071. setBuffer: function ( audioBuffer ) {
  28072. this.buffer = audioBuffer;
  28073. this.sourceType = 'buffer';
  28074. if ( this.autoplay ) this.play();
  28075. return this;
  28076. },
  28077. play: function () {
  28078. if ( this.isPlaying === true ) {
  28079. console.warn( 'THREE.Audio: Audio is already playing.' );
  28080. return;
  28081. }
  28082. if ( this.hasPlaybackControl === false ) {
  28083. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28084. return;
  28085. }
  28086. var source = this.context.createBufferSource();
  28087. source.buffer = this.buffer;
  28088. source.loop = this.loop;
  28089. source.onended = this.onEnded.bind( this );
  28090. source.playbackRate.setValueAtTime( this.playbackRate, this.startTime );
  28091. this.startTime = this.context.currentTime;
  28092. source.start( this.startTime, this.offset );
  28093. this.isPlaying = true;
  28094. this.source = source;
  28095. return this.connect();
  28096. },
  28097. pause: function () {
  28098. if ( this.hasPlaybackControl === false ) {
  28099. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28100. return;
  28101. }
  28102. if ( this.isPlaying === true ) {
  28103. this.source.stop();
  28104. this.source.onended = null;
  28105. this.offset += ( this.context.currentTime - this.startTime ) * this.playbackRate;
  28106. this.isPlaying = false;
  28107. }
  28108. return this;
  28109. },
  28110. stop: function () {
  28111. if ( this.hasPlaybackControl === false ) {
  28112. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28113. return;
  28114. }
  28115. this.source.stop();
  28116. this.source.onended = null;
  28117. this.offset = 0;
  28118. this.isPlaying = false;
  28119. return this;
  28120. },
  28121. connect: function () {
  28122. if ( this.filters.length > 0 ) {
  28123. this.source.connect( this.filters[ 0 ] );
  28124. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  28125. this.filters[ i - 1 ].connect( this.filters[ i ] );
  28126. }
  28127. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  28128. } else {
  28129. this.source.connect( this.getOutput() );
  28130. }
  28131. return this;
  28132. },
  28133. disconnect: function () {
  28134. if ( this.filters.length > 0 ) {
  28135. this.source.disconnect( this.filters[ 0 ] );
  28136. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  28137. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  28138. }
  28139. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  28140. } else {
  28141. this.source.disconnect( this.getOutput() );
  28142. }
  28143. return this;
  28144. },
  28145. getFilters: function () {
  28146. return this.filters;
  28147. },
  28148. setFilters: function ( value ) {
  28149. if ( ! value ) value = [];
  28150. if ( this.isPlaying === true ) {
  28151. this.disconnect();
  28152. this.filters = value;
  28153. this.connect();
  28154. } else {
  28155. this.filters = value;
  28156. }
  28157. return this;
  28158. },
  28159. getFilter: function () {
  28160. return this.getFilters()[ 0 ];
  28161. },
  28162. setFilter: function ( filter ) {
  28163. return this.setFilters( filter ? [ filter ] : [] );
  28164. },
  28165. setPlaybackRate: function ( value ) {
  28166. if ( this.hasPlaybackControl === false ) {
  28167. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28168. return;
  28169. }
  28170. this.playbackRate = value;
  28171. if ( this.isPlaying === true ) {
  28172. this.source.playbackRate.setValueAtTime( this.playbackRate, this.context.currentTime );
  28173. }
  28174. return this;
  28175. },
  28176. getPlaybackRate: function () {
  28177. return this.playbackRate;
  28178. },
  28179. onEnded: function () {
  28180. this.isPlaying = false;
  28181. },
  28182. getLoop: function () {
  28183. if ( this.hasPlaybackControl === false ) {
  28184. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28185. return false;
  28186. }
  28187. return this.loop;
  28188. },
  28189. setLoop: function ( value ) {
  28190. if ( this.hasPlaybackControl === false ) {
  28191. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28192. return;
  28193. }
  28194. this.loop = value;
  28195. if ( this.isPlaying === true ) {
  28196. this.source.loop = this.loop;
  28197. }
  28198. return this;
  28199. },
  28200. getVolume: function () {
  28201. return this.gain.gain.value;
  28202. },
  28203. setVolume: function ( value ) {
  28204. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  28205. return this;
  28206. }
  28207. } );
  28208. /**
  28209. * @author mrdoob / http://mrdoob.com/
  28210. */
  28211. function PositionalAudio( listener ) {
  28212. Audio.call( this, listener );
  28213. this.panner = this.context.createPanner();
  28214. this.panner.connect( this.gain );
  28215. }
  28216. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  28217. constructor: PositionalAudio,
  28218. getOutput: function () {
  28219. return this.panner;
  28220. },
  28221. getRefDistance: function () {
  28222. return this.panner.refDistance;
  28223. },
  28224. setRefDistance: function ( value ) {
  28225. this.panner.refDistance = value;
  28226. return this;
  28227. },
  28228. getRolloffFactor: function () {
  28229. return this.panner.rolloffFactor;
  28230. },
  28231. setRolloffFactor: function ( value ) {
  28232. this.panner.rolloffFactor = value;
  28233. return this;
  28234. },
  28235. getDistanceModel: function () {
  28236. return this.panner.distanceModel;
  28237. },
  28238. setDistanceModel: function ( value ) {
  28239. this.panner.distanceModel = value;
  28240. return this;
  28241. },
  28242. getMaxDistance: function () {
  28243. return this.panner.maxDistance;
  28244. },
  28245. setMaxDistance: function ( value ) {
  28246. this.panner.maxDistance = value;
  28247. return this;
  28248. },
  28249. setDirectionalCone: function ( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  28250. this.panner.coneInnerAngle = coneInnerAngle;
  28251. this.panner.coneOuterAngle = coneOuterAngle;
  28252. this.panner.coneOuterGain = coneOuterGain;
  28253. return this;
  28254. },
  28255. updateMatrixWorld: ( function () {
  28256. var position = new Vector3();
  28257. var quaternion = new Quaternion();
  28258. var scale = new Vector3();
  28259. var orientation = new Vector3();
  28260. return function updateMatrixWorld( force ) {
  28261. Object3D.prototype.updateMatrixWorld.call( this, force );
  28262. var panner = this.panner;
  28263. this.matrixWorld.decompose( position, quaternion, scale );
  28264. orientation.set( 0, 0, 1 ).applyQuaternion( quaternion );
  28265. if ( panner.positionX ) {
  28266. // code path for Chrome and Firefox (see #14393)
  28267. var endTime = this.context.currentTime + this.listener.timeDelta;
  28268. panner.positionX.linearRampToValueAtTime( position.x, endTime );
  28269. panner.positionY.linearRampToValueAtTime( position.y, endTime );
  28270. panner.positionZ.linearRampToValueAtTime( position.z, endTime );
  28271. panner.orientationX.linearRampToValueAtTime( orientation.x, endTime );
  28272. panner.orientationY.linearRampToValueAtTime( orientation.y, endTime );
  28273. panner.orientationZ.linearRampToValueAtTime( orientation.z, endTime );
  28274. } else {
  28275. panner.setPosition( position.x, position.y, position.z );
  28276. panner.setOrientation( orientation.x, orientation.y, orientation.z );
  28277. }
  28278. };
  28279. } )()
  28280. } );
  28281. /**
  28282. * @author mrdoob / http://mrdoob.com/
  28283. */
  28284. function AudioAnalyser( audio, fftSize ) {
  28285. this.analyser = audio.context.createAnalyser();
  28286. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  28287. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  28288. audio.getOutput().connect( this.analyser );
  28289. }
  28290. Object.assign( AudioAnalyser.prototype, {
  28291. getFrequencyData: function () {
  28292. this.analyser.getByteFrequencyData( this.data );
  28293. return this.data;
  28294. },
  28295. getAverageFrequency: function () {
  28296. var value = 0, data = this.getFrequencyData();
  28297. for ( var i = 0; i < data.length; i ++ ) {
  28298. value += data[ i ];
  28299. }
  28300. return value / data.length;
  28301. }
  28302. } );
  28303. /**
  28304. *
  28305. * Buffered scene graph property that allows weighted accumulation.
  28306. *
  28307. *
  28308. * @author Ben Houston / http://clara.io/
  28309. * @author David Sarno / http://lighthaus.us/
  28310. * @author tschw
  28311. */
  28312. function PropertyMixer( binding, typeName, valueSize ) {
  28313. this.binding = binding;
  28314. this.valueSize = valueSize;
  28315. var bufferType = Float64Array,
  28316. mixFunction;
  28317. switch ( typeName ) {
  28318. case 'quaternion':
  28319. mixFunction = this._slerp;
  28320. break;
  28321. case 'string':
  28322. case 'bool':
  28323. bufferType = Array;
  28324. mixFunction = this._select;
  28325. break;
  28326. default:
  28327. mixFunction = this._lerp;
  28328. }
  28329. this.buffer = new bufferType( valueSize * 4 );
  28330. // layout: [ incoming | accu0 | accu1 | orig ]
  28331. //
  28332. // interpolators can use .buffer as their .result
  28333. // the data then goes to 'incoming'
  28334. //
  28335. // 'accu0' and 'accu1' are used frame-interleaved for
  28336. // the cumulative result and are compared to detect
  28337. // changes
  28338. //
  28339. // 'orig' stores the original state of the property
  28340. this._mixBufferRegion = mixFunction;
  28341. this.cumulativeWeight = 0;
  28342. this.useCount = 0;
  28343. this.referenceCount = 0;
  28344. }
  28345. Object.assign( PropertyMixer.prototype, {
  28346. // accumulate data in the 'incoming' region into 'accu<i>'
  28347. accumulate: function ( accuIndex, weight ) {
  28348. // note: happily accumulating nothing when weight = 0, the caller knows
  28349. // the weight and shouldn't have made the call in the first place
  28350. var buffer = this.buffer,
  28351. stride = this.valueSize,
  28352. offset = accuIndex * stride + stride,
  28353. currentWeight = this.cumulativeWeight;
  28354. if ( currentWeight === 0 ) {
  28355. // accuN := incoming * weight
  28356. for ( var i = 0; i !== stride; ++ i ) {
  28357. buffer[ offset + i ] = buffer[ i ];
  28358. }
  28359. currentWeight = weight;
  28360. } else {
  28361. // accuN := accuN + incoming * weight
  28362. currentWeight += weight;
  28363. var mix = weight / currentWeight;
  28364. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  28365. }
  28366. this.cumulativeWeight = currentWeight;
  28367. },
  28368. // apply the state of 'accu<i>' to the binding when accus differ
  28369. apply: function ( accuIndex ) {
  28370. var stride = this.valueSize,
  28371. buffer = this.buffer,
  28372. offset = accuIndex * stride + stride,
  28373. weight = this.cumulativeWeight,
  28374. binding = this.binding;
  28375. this.cumulativeWeight = 0;
  28376. if ( weight < 1 ) {
  28377. // accuN := accuN + original * ( 1 - cumulativeWeight )
  28378. var originalValueOffset = stride * 3;
  28379. this._mixBufferRegion(
  28380. buffer, offset, originalValueOffset, 1 - weight, stride );
  28381. }
  28382. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  28383. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  28384. // value has changed -> update scene graph
  28385. binding.setValue( buffer, offset );
  28386. break;
  28387. }
  28388. }
  28389. },
  28390. // remember the state of the bound property and copy it to both accus
  28391. saveOriginalState: function () {
  28392. var binding = this.binding;
  28393. var buffer = this.buffer,
  28394. stride = this.valueSize,
  28395. originalValueOffset = stride * 3;
  28396. binding.getValue( buffer, originalValueOffset );
  28397. // accu[0..1] := orig -- initially detect changes against the original
  28398. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  28399. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  28400. }
  28401. this.cumulativeWeight = 0;
  28402. },
  28403. // apply the state previously taken via 'saveOriginalState' to the binding
  28404. restoreOriginalState: function () {
  28405. var originalValueOffset = this.valueSize * 3;
  28406. this.binding.setValue( this.buffer, originalValueOffset );
  28407. },
  28408. // mix functions
  28409. _select: function ( buffer, dstOffset, srcOffset, t, stride ) {
  28410. if ( t >= 0.5 ) {
  28411. for ( var i = 0; i !== stride; ++ i ) {
  28412. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  28413. }
  28414. }
  28415. },
  28416. _slerp: function ( buffer, dstOffset, srcOffset, t ) {
  28417. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  28418. },
  28419. _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
  28420. var s = 1 - t;
  28421. for ( var i = 0; i !== stride; ++ i ) {
  28422. var j = dstOffset + i;
  28423. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  28424. }
  28425. }
  28426. } );
  28427. /**
  28428. *
  28429. * A reference to a real property in the scene graph.
  28430. *
  28431. *
  28432. * @author Ben Houston / http://clara.io/
  28433. * @author David Sarno / http://lighthaus.us/
  28434. * @author tschw
  28435. */
  28436. // Characters [].:/ are reserved for track binding syntax.
  28437. var RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  28438. function Composite( targetGroup, path, optionalParsedPath ) {
  28439. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  28440. this._targetGroup = targetGroup;
  28441. this._bindings = targetGroup.subscribe_( path, parsedPath );
  28442. }
  28443. Object.assign( Composite.prototype, {
  28444. getValue: function ( array, offset ) {
  28445. this.bind(); // bind all binding
  28446. var firstValidIndex = this._targetGroup.nCachedObjects_,
  28447. binding = this._bindings[ firstValidIndex ];
  28448. // and only call .getValue on the first
  28449. if ( binding !== undefined ) binding.getValue( array, offset );
  28450. },
  28451. setValue: function ( array, offset ) {
  28452. var bindings = this._bindings;
  28453. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  28454. bindings[ i ].setValue( array, offset );
  28455. }
  28456. },
  28457. bind: function () {
  28458. var bindings = this._bindings;
  28459. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  28460. bindings[ i ].bind();
  28461. }
  28462. },
  28463. unbind: function () {
  28464. var bindings = this._bindings;
  28465. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  28466. bindings[ i ].unbind();
  28467. }
  28468. }
  28469. } );
  28470. function PropertyBinding( rootNode, path, parsedPath ) {
  28471. this.path = path;
  28472. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  28473. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  28474. this.rootNode = rootNode;
  28475. }
  28476. Object.assign( PropertyBinding, {
  28477. Composite: Composite,
  28478. create: function ( root, path, parsedPath ) {
  28479. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  28480. return new PropertyBinding( root, path, parsedPath );
  28481. } else {
  28482. return new PropertyBinding.Composite( root, path, parsedPath );
  28483. }
  28484. },
  28485. /**
  28486. * Replaces spaces with underscores and removes unsupported characters from
  28487. * node names, to ensure compatibility with parseTrackName().
  28488. *
  28489. * @param {string} name Node name to be sanitized.
  28490. * @return {string}
  28491. */
  28492. sanitizeNodeName: ( function () {
  28493. var reservedRe = new RegExp( '[' + RESERVED_CHARS_RE + ']', 'g' );
  28494. return function sanitizeNodeName( name ) {
  28495. return name.replace( /\s/g, '_' ).replace( reservedRe, '' );
  28496. };
  28497. }() ),
  28498. parseTrackName: function () {
  28499. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  28500. // only latin characters, and the unicode \p{L} is not yet supported. So
  28501. // instead, we exclude reserved characters and match everything else.
  28502. var wordChar = '[^' + RESERVED_CHARS_RE + ']';
  28503. var wordCharOrDot = '[^' + RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  28504. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  28505. // be matched to parse the rest of the track name.
  28506. var directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', wordChar );
  28507. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  28508. var nodeRe = /(WCOD+)?/.source.replace( 'WCOD', wordCharOrDot );
  28509. // Object on target node, and accessor. May not contain reserved
  28510. // characters. Accessor may contain any character except closing bracket.
  28511. var objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', wordChar );
  28512. // Property and accessor. May not contain reserved characters. Accessor may
  28513. // contain any non-bracket characters.
  28514. var propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', wordChar );
  28515. var trackRe = new RegExp( ''
  28516. + '^'
  28517. + directoryRe
  28518. + nodeRe
  28519. + objectRe
  28520. + propertyRe
  28521. + '$'
  28522. );
  28523. var supportedObjectNames = [ 'material', 'materials', 'bones' ];
  28524. return function parseTrackName( trackName ) {
  28525. var matches = trackRe.exec( trackName );
  28526. if ( ! matches ) {
  28527. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  28528. }
  28529. var results = {
  28530. // directoryName: matches[ 1 ], // (tschw) currently unused
  28531. nodeName: matches[ 2 ],
  28532. objectName: matches[ 3 ],
  28533. objectIndex: matches[ 4 ],
  28534. propertyName: matches[ 5 ], // required
  28535. propertyIndex: matches[ 6 ]
  28536. };
  28537. var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  28538. if ( lastDot !== undefined && lastDot !== - 1 ) {
  28539. var objectName = results.nodeName.substring( lastDot + 1 );
  28540. // Object names must be checked against a whitelist. Otherwise, there
  28541. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  28542. // 'bar' could be the objectName, or part of a nodeName (which can
  28543. // include '.' characters).
  28544. if ( supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  28545. results.nodeName = results.nodeName.substring( 0, lastDot );
  28546. results.objectName = objectName;
  28547. }
  28548. }
  28549. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  28550. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  28551. }
  28552. return results;
  28553. };
  28554. }(),
  28555. findNode: function ( root, nodeName ) {
  28556. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  28557. return root;
  28558. }
  28559. // search into skeleton bones.
  28560. if ( root.skeleton ) {
  28561. var bone = root.skeleton.getBoneByName( nodeName );
  28562. if ( bone !== undefined ) {
  28563. return bone;
  28564. }
  28565. }
  28566. // search into node subtree.
  28567. if ( root.children ) {
  28568. var searchNodeSubtree = function ( children ) {
  28569. for ( var i = 0; i < children.length; i ++ ) {
  28570. var childNode = children[ i ];
  28571. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  28572. return childNode;
  28573. }
  28574. var result = searchNodeSubtree( childNode.children );
  28575. if ( result ) return result;
  28576. }
  28577. return null;
  28578. };
  28579. var subTreeNode = searchNodeSubtree( root.children );
  28580. if ( subTreeNode ) {
  28581. return subTreeNode;
  28582. }
  28583. }
  28584. return null;
  28585. }
  28586. } );
  28587. Object.assign( PropertyBinding.prototype, { // prototype, continued
  28588. // these are used to "bind" a nonexistent property
  28589. _getValue_unavailable: function () {},
  28590. _setValue_unavailable: function () {},
  28591. BindingType: {
  28592. Direct: 0,
  28593. EntireArray: 1,
  28594. ArrayElement: 2,
  28595. HasFromToArray: 3
  28596. },
  28597. Versioning: {
  28598. None: 0,
  28599. NeedsUpdate: 1,
  28600. MatrixWorldNeedsUpdate: 2
  28601. },
  28602. GetterByBindingType: [
  28603. function getValue_direct( buffer, offset ) {
  28604. buffer[ offset ] = this.node[ this.propertyName ];
  28605. },
  28606. function getValue_array( buffer, offset ) {
  28607. var source = this.resolvedProperty;
  28608. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  28609. buffer[ offset ++ ] = source[ i ];
  28610. }
  28611. },
  28612. function getValue_arrayElement( buffer, offset ) {
  28613. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  28614. },
  28615. function getValue_toArray( buffer, offset ) {
  28616. this.resolvedProperty.toArray( buffer, offset );
  28617. }
  28618. ],
  28619. SetterByBindingTypeAndVersioning: [
  28620. [
  28621. // Direct
  28622. function setValue_direct( buffer, offset ) {
  28623. this.targetObject[ this.propertyName ] = buffer[ offset ];
  28624. },
  28625. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  28626. this.targetObject[ this.propertyName ] = buffer[ offset ];
  28627. this.targetObject.needsUpdate = true;
  28628. },
  28629. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28630. this.targetObject[ this.propertyName ] = buffer[ offset ];
  28631. this.targetObject.matrixWorldNeedsUpdate = true;
  28632. }
  28633. ], [
  28634. // EntireArray
  28635. function setValue_array( buffer, offset ) {
  28636. var dest = this.resolvedProperty;
  28637. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  28638. dest[ i ] = buffer[ offset ++ ];
  28639. }
  28640. },
  28641. function setValue_array_setNeedsUpdate( buffer, offset ) {
  28642. var dest = this.resolvedProperty;
  28643. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  28644. dest[ i ] = buffer[ offset ++ ];
  28645. }
  28646. this.targetObject.needsUpdate = true;
  28647. },
  28648. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28649. var dest = this.resolvedProperty;
  28650. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  28651. dest[ i ] = buffer[ offset ++ ];
  28652. }
  28653. this.targetObject.matrixWorldNeedsUpdate = true;
  28654. }
  28655. ], [
  28656. // ArrayElement
  28657. function setValue_arrayElement( buffer, offset ) {
  28658. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28659. },
  28660. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  28661. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28662. this.targetObject.needsUpdate = true;
  28663. },
  28664. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28665. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28666. this.targetObject.matrixWorldNeedsUpdate = true;
  28667. }
  28668. ], [
  28669. // HasToFromArray
  28670. function setValue_fromArray( buffer, offset ) {
  28671. this.resolvedProperty.fromArray( buffer, offset );
  28672. },
  28673. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  28674. this.resolvedProperty.fromArray( buffer, offset );
  28675. this.targetObject.needsUpdate = true;
  28676. },
  28677. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28678. this.resolvedProperty.fromArray( buffer, offset );
  28679. this.targetObject.matrixWorldNeedsUpdate = true;
  28680. }
  28681. ]
  28682. ],
  28683. getValue: function getValue_unbound( targetArray, offset ) {
  28684. this.bind();
  28685. this.getValue( targetArray, offset );
  28686. // Note: This class uses a State pattern on a per-method basis:
  28687. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  28688. // prototype version of these methods with one that represents
  28689. // the bound state. When the property is not found, the methods
  28690. // become no-ops.
  28691. },
  28692. setValue: function getValue_unbound( sourceArray, offset ) {
  28693. this.bind();
  28694. this.setValue( sourceArray, offset );
  28695. },
  28696. // create getter / setter pair for a property in the scene graph
  28697. bind: function () {
  28698. var targetObject = this.node,
  28699. parsedPath = this.parsedPath,
  28700. objectName = parsedPath.objectName,
  28701. propertyName = parsedPath.propertyName,
  28702. propertyIndex = parsedPath.propertyIndex;
  28703. if ( ! targetObject ) {
  28704. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  28705. this.node = targetObject;
  28706. }
  28707. // set fail state so we can just 'return' on error
  28708. this.getValue = this._getValue_unavailable;
  28709. this.setValue = this._setValue_unavailable;
  28710. // ensure there is a value node
  28711. if ( ! targetObject ) {
  28712. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  28713. return;
  28714. }
  28715. if ( objectName ) {
  28716. var objectIndex = parsedPath.objectIndex;
  28717. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  28718. switch ( objectName ) {
  28719. case 'materials':
  28720. if ( ! targetObject.material ) {
  28721. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  28722. return;
  28723. }
  28724. if ( ! targetObject.material.materials ) {
  28725. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  28726. return;
  28727. }
  28728. targetObject = targetObject.material.materials;
  28729. break;
  28730. case 'bones':
  28731. if ( ! targetObject.skeleton ) {
  28732. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  28733. return;
  28734. }
  28735. // potential future optimization: skip this if propertyIndex is already an integer
  28736. // and convert the integer string to a true integer.
  28737. targetObject = targetObject.skeleton.bones;
  28738. // support resolving morphTarget names into indices.
  28739. for ( var i = 0; i < targetObject.length; i ++ ) {
  28740. if ( targetObject[ i ].name === objectIndex ) {
  28741. objectIndex = i;
  28742. break;
  28743. }
  28744. }
  28745. break;
  28746. default:
  28747. if ( targetObject[ objectName ] === undefined ) {
  28748. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  28749. return;
  28750. }
  28751. targetObject = targetObject[ objectName ];
  28752. }
  28753. if ( objectIndex !== undefined ) {
  28754. if ( targetObject[ objectIndex ] === undefined ) {
  28755. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  28756. return;
  28757. }
  28758. targetObject = targetObject[ objectIndex ];
  28759. }
  28760. }
  28761. // resolve property
  28762. var nodeProperty = targetObject[ propertyName ];
  28763. if ( nodeProperty === undefined ) {
  28764. var nodeName = parsedPath.nodeName;
  28765. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  28766. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  28767. return;
  28768. }
  28769. // determine versioning scheme
  28770. var versioning = this.Versioning.None;
  28771. this.targetObject = targetObject;
  28772. if ( targetObject.needsUpdate !== undefined ) { // material
  28773. versioning = this.Versioning.NeedsUpdate;
  28774. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  28775. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  28776. }
  28777. // determine how the property gets bound
  28778. var bindingType = this.BindingType.Direct;
  28779. if ( propertyIndex !== undefined ) {
  28780. // access a sub element of the property array (only primitives are supported right now)
  28781. if ( propertyName === "morphTargetInfluences" ) {
  28782. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  28783. // support resolving morphTarget names into indices.
  28784. if ( ! targetObject.geometry ) {
  28785. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  28786. return;
  28787. }
  28788. if ( targetObject.geometry.isBufferGeometry ) {
  28789. if ( ! targetObject.geometry.morphAttributes ) {
  28790. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  28791. return;
  28792. }
  28793. for ( var i = 0; i < this.node.geometry.morphAttributes.position.length; i ++ ) {
  28794. if ( targetObject.geometry.morphAttributes.position[ i ].name === propertyIndex ) {
  28795. propertyIndex = i;
  28796. break;
  28797. }
  28798. }
  28799. } else {
  28800. if ( ! targetObject.geometry.morphTargets ) {
  28801. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this );
  28802. return;
  28803. }
  28804. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  28805. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  28806. propertyIndex = i;
  28807. break;
  28808. }
  28809. }
  28810. }
  28811. }
  28812. bindingType = this.BindingType.ArrayElement;
  28813. this.resolvedProperty = nodeProperty;
  28814. this.propertyIndex = propertyIndex;
  28815. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  28816. // must use copy for Object3D.Euler/Quaternion
  28817. bindingType = this.BindingType.HasFromToArray;
  28818. this.resolvedProperty = nodeProperty;
  28819. } else if ( Array.isArray( nodeProperty ) ) {
  28820. bindingType = this.BindingType.EntireArray;
  28821. this.resolvedProperty = nodeProperty;
  28822. } else {
  28823. this.propertyName = propertyName;
  28824. }
  28825. // select getter / setter
  28826. this.getValue = this.GetterByBindingType[ bindingType ];
  28827. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  28828. },
  28829. unbind: function () {
  28830. this.node = null;
  28831. // back to the prototype version of getValue / setValue
  28832. // note: avoiding to mutate the shape of 'this' via 'delete'
  28833. this.getValue = this._getValue_unbound;
  28834. this.setValue = this._setValue_unbound;
  28835. }
  28836. } );
  28837. //!\ DECLARE ALIAS AFTER assign prototype !
  28838. Object.assign( PropertyBinding.prototype, {
  28839. // initial state of these methods that calls 'bind'
  28840. _getValue_unbound: PropertyBinding.prototype.getValue,
  28841. _setValue_unbound: PropertyBinding.prototype.setValue,
  28842. } );
  28843. /**
  28844. *
  28845. * A group of objects that receives a shared animation state.
  28846. *
  28847. * Usage:
  28848. *
  28849. * - Add objects you would otherwise pass as 'root' to the
  28850. * constructor or the .clipAction method of AnimationMixer.
  28851. *
  28852. * - Instead pass this object as 'root'.
  28853. *
  28854. * - You can also add and remove objects later when the mixer
  28855. * is running.
  28856. *
  28857. * Note:
  28858. *
  28859. * Objects of this class appear as one object to the mixer,
  28860. * so cache control of the individual objects must be done
  28861. * on the group.
  28862. *
  28863. * Limitation:
  28864. *
  28865. * - The animated properties must be compatible among the
  28866. * all objects in the group.
  28867. *
  28868. * - A single property can either be controlled through a
  28869. * target group or directly, but not both.
  28870. *
  28871. * @author tschw
  28872. */
  28873. function AnimationObjectGroup() {
  28874. this.uuid = _Math.generateUUID();
  28875. // cached objects followed by the active ones
  28876. this._objects = Array.prototype.slice.call( arguments );
  28877. this.nCachedObjects_ = 0; // threshold
  28878. // note: read by PropertyBinding.Composite
  28879. var indices = {};
  28880. this._indicesByUUID = indices; // for bookkeeping
  28881. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  28882. indices[ arguments[ i ].uuid ] = i;
  28883. }
  28884. this._paths = []; // inside: string
  28885. this._parsedPaths = []; // inside: { we don't care, here }
  28886. this._bindings = []; // inside: Array< PropertyBinding >
  28887. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  28888. var scope = this;
  28889. this.stats = {
  28890. objects: {
  28891. get total() {
  28892. return scope._objects.length;
  28893. },
  28894. get inUse() {
  28895. return this.total - scope.nCachedObjects_;
  28896. }
  28897. },
  28898. get bindingsPerObject() {
  28899. return scope._bindings.length;
  28900. }
  28901. };
  28902. }
  28903. Object.assign( AnimationObjectGroup.prototype, {
  28904. isAnimationObjectGroup: true,
  28905. add: function () {
  28906. var objects = this._objects,
  28907. nObjects = objects.length,
  28908. nCachedObjects = this.nCachedObjects_,
  28909. indicesByUUID = this._indicesByUUID,
  28910. paths = this._paths,
  28911. parsedPaths = this._parsedPaths,
  28912. bindings = this._bindings,
  28913. nBindings = bindings.length,
  28914. knownObject = undefined;
  28915. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  28916. var object = arguments[ i ],
  28917. uuid = object.uuid,
  28918. index = indicesByUUID[ uuid ];
  28919. if ( index === undefined ) {
  28920. // unknown object -> add it to the ACTIVE region
  28921. index = nObjects ++;
  28922. indicesByUUID[ uuid ] = index;
  28923. objects.push( object );
  28924. // accounting is done, now do the same for all bindings
  28925. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  28926. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  28927. }
  28928. } else if ( index < nCachedObjects ) {
  28929. knownObject = objects[ index ];
  28930. // move existing object to the ACTIVE region
  28931. var firstActiveIndex = -- nCachedObjects,
  28932. lastCachedObject = objects[ firstActiveIndex ];
  28933. indicesByUUID[ lastCachedObject.uuid ] = index;
  28934. objects[ index ] = lastCachedObject;
  28935. indicesByUUID[ uuid ] = firstActiveIndex;
  28936. objects[ firstActiveIndex ] = object;
  28937. // accounting is done, now do the same for all bindings
  28938. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  28939. var bindingsForPath = bindings[ j ],
  28940. lastCached = bindingsForPath[ firstActiveIndex ],
  28941. binding = bindingsForPath[ index ];
  28942. bindingsForPath[ index ] = lastCached;
  28943. if ( binding === undefined ) {
  28944. // since we do not bother to create new bindings
  28945. // for objects that are cached, the binding may
  28946. // or may not exist
  28947. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  28948. }
  28949. bindingsForPath[ firstActiveIndex ] = binding;
  28950. }
  28951. } else if ( objects[ index ] !== knownObject ) {
  28952. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  28953. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  28954. } // else the object is already where we want it to be
  28955. } // for arguments
  28956. this.nCachedObjects_ = nCachedObjects;
  28957. },
  28958. remove: function () {
  28959. var objects = this._objects,
  28960. nCachedObjects = this.nCachedObjects_,
  28961. indicesByUUID = this._indicesByUUID,
  28962. bindings = this._bindings,
  28963. nBindings = bindings.length;
  28964. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  28965. var object = arguments[ i ],
  28966. uuid = object.uuid,
  28967. index = indicesByUUID[ uuid ];
  28968. if ( index !== undefined && index >= nCachedObjects ) {
  28969. // move existing object into the CACHED region
  28970. var lastCachedIndex = nCachedObjects ++,
  28971. firstActiveObject = objects[ lastCachedIndex ];
  28972. indicesByUUID[ firstActiveObject.uuid ] = index;
  28973. objects[ index ] = firstActiveObject;
  28974. indicesByUUID[ uuid ] = lastCachedIndex;
  28975. objects[ lastCachedIndex ] = object;
  28976. // accounting is done, now do the same for all bindings
  28977. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  28978. var bindingsForPath = bindings[ j ],
  28979. firstActive = bindingsForPath[ lastCachedIndex ],
  28980. binding = bindingsForPath[ index ];
  28981. bindingsForPath[ index ] = firstActive;
  28982. bindingsForPath[ lastCachedIndex ] = binding;
  28983. }
  28984. }
  28985. } // for arguments
  28986. this.nCachedObjects_ = nCachedObjects;
  28987. },
  28988. // remove & forget
  28989. uncache: function () {
  28990. var objects = this._objects,
  28991. nObjects = objects.length,
  28992. nCachedObjects = this.nCachedObjects_,
  28993. indicesByUUID = this._indicesByUUID,
  28994. bindings = this._bindings,
  28995. nBindings = bindings.length;
  28996. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  28997. var object = arguments[ i ],
  28998. uuid = object.uuid,
  28999. index = indicesByUUID[ uuid ];
  29000. if ( index !== undefined ) {
  29001. delete indicesByUUID[ uuid ];
  29002. if ( index < nCachedObjects ) {
  29003. // object is cached, shrink the CACHED region
  29004. var firstActiveIndex = -- nCachedObjects,
  29005. lastCachedObject = objects[ firstActiveIndex ],
  29006. lastIndex = -- nObjects,
  29007. lastObject = objects[ lastIndex ];
  29008. // last cached object takes this object's place
  29009. indicesByUUID[ lastCachedObject.uuid ] = index;
  29010. objects[ index ] = lastCachedObject;
  29011. // last object goes to the activated slot and pop
  29012. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  29013. objects[ firstActiveIndex ] = lastObject;
  29014. objects.pop();
  29015. // accounting is done, now do the same for all bindings
  29016. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  29017. var bindingsForPath = bindings[ j ],
  29018. lastCached = bindingsForPath[ firstActiveIndex ],
  29019. last = bindingsForPath[ lastIndex ];
  29020. bindingsForPath[ index ] = lastCached;
  29021. bindingsForPath[ firstActiveIndex ] = last;
  29022. bindingsForPath.pop();
  29023. }
  29024. } else {
  29025. // object is active, just swap with the last and pop
  29026. var lastIndex = -- nObjects,
  29027. lastObject = objects[ lastIndex ];
  29028. indicesByUUID[ lastObject.uuid ] = index;
  29029. objects[ index ] = lastObject;
  29030. objects.pop();
  29031. // accounting is done, now do the same for all bindings
  29032. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  29033. var bindingsForPath = bindings[ j ];
  29034. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  29035. bindingsForPath.pop();
  29036. }
  29037. } // cached or active
  29038. } // if object is known
  29039. } // for arguments
  29040. this.nCachedObjects_ = nCachedObjects;
  29041. },
  29042. // Internal interface used by befriended PropertyBinding.Composite:
  29043. subscribe_: function ( path, parsedPath ) {
  29044. // returns an array of bindings for the given path that is changed
  29045. // according to the contained objects in the group
  29046. var indicesByPath = this._bindingsIndicesByPath,
  29047. index = indicesByPath[ path ],
  29048. bindings = this._bindings;
  29049. if ( index !== undefined ) return bindings[ index ];
  29050. var paths = this._paths,
  29051. parsedPaths = this._parsedPaths,
  29052. objects = this._objects,
  29053. nObjects = objects.length,
  29054. nCachedObjects = this.nCachedObjects_,
  29055. bindingsForPath = new Array( nObjects );
  29056. index = bindings.length;
  29057. indicesByPath[ path ] = index;
  29058. paths.push( path );
  29059. parsedPaths.push( parsedPath );
  29060. bindings.push( bindingsForPath );
  29061. for ( var i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  29062. var object = objects[ i ];
  29063. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  29064. }
  29065. return bindingsForPath;
  29066. },
  29067. unsubscribe_: function ( path ) {
  29068. // tells the group to forget about a property path and no longer
  29069. // update the array previously obtained with 'subscribe_'
  29070. var indicesByPath = this._bindingsIndicesByPath,
  29071. index = indicesByPath[ path ];
  29072. if ( index !== undefined ) {
  29073. var paths = this._paths,
  29074. parsedPaths = this._parsedPaths,
  29075. bindings = this._bindings,
  29076. lastBindingsIndex = bindings.length - 1,
  29077. lastBindings = bindings[ lastBindingsIndex ],
  29078. lastBindingsPath = path[ lastBindingsIndex ];
  29079. indicesByPath[ lastBindingsPath ] = index;
  29080. bindings[ index ] = lastBindings;
  29081. bindings.pop();
  29082. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  29083. parsedPaths.pop();
  29084. paths[ index ] = paths[ lastBindingsIndex ];
  29085. paths.pop();
  29086. }
  29087. }
  29088. } );
  29089. /**
  29090. *
  29091. * Action provided by AnimationMixer for scheduling clip playback on specific
  29092. * objects.
  29093. *
  29094. * @author Ben Houston / http://clara.io/
  29095. * @author David Sarno / http://lighthaus.us/
  29096. * @author tschw
  29097. *
  29098. */
  29099. function AnimationAction( mixer, clip, localRoot ) {
  29100. this._mixer = mixer;
  29101. this._clip = clip;
  29102. this._localRoot = localRoot || null;
  29103. var tracks = clip.tracks,
  29104. nTracks = tracks.length,
  29105. interpolants = new Array( nTracks );
  29106. var interpolantSettings = {
  29107. endingStart: ZeroCurvatureEnding,
  29108. endingEnd: ZeroCurvatureEnding
  29109. };
  29110. for ( var i = 0; i !== nTracks; ++ i ) {
  29111. var interpolant = tracks[ i ].createInterpolant( null );
  29112. interpolants[ i ] = interpolant;
  29113. interpolant.settings = interpolantSettings;
  29114. }
  29115. this._interpolantSettings = interpolantSettings;
  29116. this._interpolants = interpolants; // bound by the mixer
  29117. // inside: PropertyMixer (managed by the mixer)
  29118. this._propertyBindings = new Array( nTracks );
  29119. this._cacheIndex = null; // for the memory manager
  29120. this._byClipCacheIndex = null; // for the memory manager
  29121. this._timeScaleInterpolant = null;
  29122. this._weightInterpolant = null;
  29123. this.loop = LoopRepeat;
  29124. this._loopCount = - 1;
  29125. // global mixer time when the action is to be started
  29126. // it's set back to 'null' upon start of the action
  29127. this._startTime = null;
  29128. // scaled local time of the action
  29129. // gets clamped or wrapped to 0..clip.duration according to loop
  29130. this.time = 0;
  29131. this.timeScale = 1;
  29132. this._effectiveTimeScale = 1;
  29133. this.weight = 1;
  29134. this._effectiveWeight = 1;
  29135. this.repetitions = Infinity; // no. of repetitions when looping
  29136. this.paused = false; // true -> zero effective time scale
  29137. this.enabled = true; // false -> zero effective weight
  29138. this.clampWhenFinished = false;// keep feeding the last frame?
  29139. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  29140. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  29141. }
  29142. Object.assign( AnimationAction.prototype, {
  29143. // State & Scheduling
  29144. play: function () {
  29145. this._mixer._activateAction( this );
  29146. return this;
  29147. },
  29148. stop: function () {
  29149. this._mixer._deactivateAction( this );
  29150. return this.reset();
  29151. },
  29152. reset: function () {
  29153. this.paused = false;
  29154. this.enabled = true;
  29155. this.time = 0; // restart clip
  29156. this._loopCount = - 1;// forget previous loops
  29157. this._startTime = null;// forget scheduling
  29158. return this.stopFading().stopWarping();
  29159. },
  29160. isRunning: function () {
  29161. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  29162. this._startTime === null && this._mixer._isActiveAction( this );
  29163. },
  29164. // return true when play has been called
  29165. isScheduled: function () {
  29166. return this._mixer._isActiveAction( this );
  29167. },
  29168. startAt: function ( time ) {
  29169. this._startTime = time;
  29170. return this;
  29171. },
  29172. setLoop: function ( mode, repetitions ) {
  29173. this.loop = mode;
  29174. this.repetitions = repetitions;
  29175. return this;
  29176. },
  29177. // Weight
  29178. // set the weight stopping any scheduled fading
  29179. // although .enabled = false yields an effective weight of zero, this
  29180. // method does *not* change .enabled, because it would be confusing
  29181. setEffectiveWeight: function ( weight ) {
  29182. this.weight = weight;
  29183. // note: same logic as when updated at runtime
  29184. this._effectiveWeight = this.enabled ? weight : 0;
  29185. return this.stopFading();
  29186. },
  29187. // return the weight considering fading and .enabled
  29188. getEffectiveWeight: function () {
  29189. return this._effectiveWeight;
  29190. },
  29191. fadeIn: function ( duration ) {
  29192. return this._scheduleFading( duration, 0, 1 );
  29193. },
  29194. fadeOut: function ( duration ) {
  29195. return this._scheduleFading( duration, 1, 0 );
  29196. },
  29197. crossFadeFrom: function ( fadeOutAction, duration, warp ) {
  29198. fadeOutAction.fadeOut( duration );
  29199. this.fadeIn( duration );
  29200. if ( warp ) {
  29201. var fadeInDuration = this._clip.duration,
  29202. fadeOutDuration = fadeOutAction._clip.duration,
  29203. startEndRatio = fadeOutDuration / fadeInDuration,
  29204. endStartRatio = fadeInDuration / fadeOutDuration;
  29205. fadeOutAction.warp( 1.0, startEndRatio, duration );
  29206. this.warp( endStartRatio, 1.0, duration );
  29207. }
  29208. return this;
  29209. },
  29210. crossFadeTo: function ( fadeInAction, duration, warp ) {
  29211. return fadeInAction.crossFadeFrom( this, duration, warp );
  29212. },
  29213. stopFading: function () {
  29214. var weightInterpolant = this._weightInterpolant;
  29215. if ( weightInterpolant !== null ) {
  29216. this._weightInterpolant = null;
  29217. this._mixer._takeBackControlInterpolant( weightInterpolant );
  29218. }
  29219. return this;
  29220. },
  29221. // Time Scale Control
  29222. // set the time scale stopping any scheduled warping
  29223. // although .paused = true yields an effective time scale of zero, this
  29224. // method does *not* change .paused, because it would be confusing
  29225. setEffectiveTimeScale: function ( timeScale ) {
  29226. this.timeScale = timeScale;
  29227. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  29228. return this.stopWarping();
  29229. },
  29230. // return the time scale considering warping and .paused
  29231. getEffectiveTimeScale: function () {
  29232. return this._effectiveTimeScale;
  29233. },
  29234. setDuration: function ( duration ) {
  29235. this.timeScale = this._clip.duration / duration;
  29236. return this.stopWarping();
  29237. },
  29238. syncWith: function ( action ) {
  29239. this.time = action.time;
  29240. this.timeScale = action.timeScale;
  29241. return this.stopWarping();
  29242. },
  29243. halt: function ( duration ) {
  29244. return this.warp( this._effectiveTimeScale, 0, duration );
  29245. },
  29246. warp: function ( startTimeScale, endTimeScale, duration ) {
  29247. var mixer = this._mixer, now = mixer.time,
  29248. interpolant = this._timeScaleInterpolant,
  29249. timeScale = this.timeScale;
  29250. if ( interpolant === null ) {
  29251. interpolant = mixer._lendControlInterpolant();
  29252. this._timeScaleInterpolant = interpolant;
  29253. }
  29254. var times = interpolant.parameterPositions,
  29255. values = interpolant.sampleValues;
  29256. times[ 0 ] = now;
  29257. times[ 1 ] = now + duration;
  29258. values[ 0 ] = startTimeScale / timeScale;
  29259. values[ 1 ] = endTimeScale / timeScale;
  29260. return this;
  29261. },
  29262. stopWarping: function () {
  29263. var timeScaleInterpolant = this._timeScaleInterpolant;
  29264. if ( timeScaleInterpolant !== null ) {
  29265. this._timeScaleInterpolant = null;
  29266. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  29267. }
  29268. return this;
  29269. },
  29270. // Object Accessors
  29271. getMixer: function () {
  29272. return this._mixer;
  29273. },
  29274. getClip: function () {
  29275. return this._clip;
  29276. },
  29277. getRoot: function () {
  29278. return this._localRoot || this._mixer._root;
  29279. },
  29280. // Interna
  29281. _update: function ( time, deltaTime, timeDirection, accuIndex ) {
  29282. // called by the mixer
  29283. if ( ! this.enabled ) {
  29284. // call ._updateWeight() to update ._effectiveWeight
  29285. this._updateWeight( time );
  29286. return;
  29287. }
  29288. var startTime = this._startTime;
  29289. if ( startTime !== null ) {
  29290. // check for scheduled start of action
  29291. var timeRunning = ( time - startTime ) * timeDirection;
  29292. if ( timeRunning < 0 || timeDirection === 0 ) {
  29293. return; // yet to come / don't decide when delta = 0
  29294. }
  29295. // start
  29296. this._startTime = null; // unschedule
  29297. deltaTime = timeDirection * timeRunning;
  29298. }
  29299. // apply time scale and advance time
  29300. deltaTime *= this._updateTimeScale( time );
  29301. var clipTime = this._updateTime( deltaTime );
  29302. // note: _updateTime may disable the action resulting in
  29303. // an effective weight of 0
  29304. var weight = this._updateWeight( time );
  29305. if ( weight > 0 ) {
  29306. var interpolants = this._interpolants;
  29307. var propertyMixers = this._propertyBindings;
  29308. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  29309. interpolants[ j ].evaluate( clipTime );
  29310. propertyMixers[ j ].accumulate( accuIndex, weight );
  29311. }
  29312. }
  29313. },
  29314. _updateWeight: function ( time ) {
  29315. var weight = 0;
  29316. if ( this.enabled ) {
  29317. weight = this.weight;
  29318. var interpolant = this._weightInterpolant;
  29319. if ( interpolant !== null ) {
  29320. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  29321. weight *= interpolantValue;
  29322. if ( time > interpolant.parameterPositions[ 1 ] ) {
  29323. this.stopFading();
  29324. if ( interpolantValue === 0 ) {
  29325. // faded out, disable
  29326. this.enabled = false;
  29327. }
  29328. }
  29329. }
  29330. }
  29331. this._effectiveWeight = weight;
  29332. return weight;
  29333. },
  29334. _updateTimeScale: function ( time ) {
  29335. var timeScale = 0;
  29336. if ( ! this.paused ) {
  29337. timeScale = this.timeScale;
  29338. var interpolant = this._timeScaleInterpolant;
  29339. if ( interpolant !== null ) {
  29340. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  29341. timeScale *= interpolantValue;
  29342. if ( time > interpolant.parameterPositions[ 1 ] ) {
  29343. this.stopWarping();
  29344. if ( timeScale === 0 ) {
  29345. // motion has halted, pause
  29346. this.paused = true;
  29347. } else {
  29348. // warp done - apply final time scale
  29349. this.timeScale = timeScale;
  29350. }
  29351. }
  29352. }
  29353. }
  29354. this._effectiveTimeScale = timeScale;
  29355. return timeScale;
  29356. },
  29357. _updateTime: function ( deltaTime ) {
  29358. var time = this.time + deltaTime;
  29359. var duration = this._clip.duration;
  29360. var loop = this.loop;
  29361. var loopCount = this._loopCount;
  29362. var pingPong = ( loop === LoopPingPong );
  29363. if ( deltaTime === 0 ) {
  29364. if ( loopCount === - 1 ) return time;
  29365. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  29366. }
  29367. if ( loop === LoopOnce ) {
  29368. if ( loopCount === - 1 ) {
  29369. // just started
  29370. this._loopCount = 0;
  29371. this._setEndings( true, true, false );
  29372. }
  29373. handle_stop: {
  29374. if ( time >= duration ) {
  29375. time = duration;
  29376. } else if ( time < 0 ) {
  29377. time = 0;
  29378. } else break handle_stop;
  29379. if ( this.clampWhenFinished ) this.paused = true;
  29380. else this.enabled = false;
  29381. this._mixer.dispatchEvent( {
  29382. type: 'finished', action: this,
  29383. direction: deltaTime < 0 ? - 1 : 1
  29384. } );
  29385. }
  29386. } else { // repetitive Repeat or PingPong
  29387. if ( loopCount === - 1 ) {
  29388. // just started
  29389. if ( deltaTime >= 0 ) {
  29390. loopCount = 0;
  29391. this._setEndings( true, this.repetitions === 0, pingPong );
  29392. } else {
  29393. // when looping in reverse direction, the initial
  29394. // transition through zero counts as a repetition,
  29395. // so leave loopCount at -1
  29396. this._setEndings( this.repetitions === 0, true, pingPong );
  29397. }
  29398. }
  29399. if ( time >= duration || time < 0 ) {
  29400. // wrap around
  29401. var loopDelta = Math.floor( time / duration ); // signed
  29402. time -= duration * loopDelta;
  29403. loopCount += Math.abs( loopDelta );
  29404. var pending = this.repetitions - loopCount;
  29405. if ( pending <= 0 ) {
  29406. // have to stop (switch state, clamp time, fire event)
  29407. if ( this.clampWhenFinished ) this.paused = true;
  29408. else this.enabled = false;
  29409. time = deltaTime > 0 ? duration : 0;
  29410. this._mixer.dispatchEvent( {
  29411. type: 'finished', action: this,
  29412. direction: deltaTime > 0 ? 1 : - 1
  29413. } );
  29414. } else {
  29415. // keep running
  29416. if ( pending === 1 ) {
  29417. // entering the last round
  29418. var atStart = deltaTime < 0;
  29419. this._setEndings( atStart, ! atStart, pingPong );
  29420. } else {
  29421. this._setEndings( false, false, pingPong );
  29422. }
  29423. this._loopCount = loopCount;
  29424. this._mixer.dispatchEvent( {
  29425. type: 'loop', action: this, loopDelta: loopDelta
  29426. } );
  29427. }
  29428. }
  29429. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  29430. // invert time for the "pong round"
  29431. this.time = time;
  29432. return duration - time;
  29433. }
  29434. }
  29435. this.time = time;
  29436. return time;
  29437. },
  29438. _setEndings: function ( atStart, atEnd, pingPong ) {
  29439. var settings = this._interpolantSettings;
  29440. if ( pingPong ) {
  29441. settings.endingStart = ZeroSlopeEnding;
  29442. settings.endingEnd = ZeroSlopeEnding;
  29443. } else {
  29444. // assuming for LoopOnce atStart == atEnd == true
  29445. if ( atStart ) {
  29446. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  29447. } else {
  29448. settings.endingStart = WrapAroundEnding;
  29449. }
  29450. if ( atEnd ) {
  29451. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  29452. } else {
  29453. settings.endingEnd = WrapAroundEnding;
  29454. }
  29455. }
  29456. },
  29457. _scheduleFading: function ( duration, weightNow, weightThen ) {
  29458. var mixer = this._mixer, now = mixer.time,
  29459. interpolant = this._weightInterpolant;
  29460. if ( interpolant === null ) {
  29461. interpolant = mixer._lendControlInterpolant();
  29462. this._weightInterpolant = interpolant;
  29463. }
  29464. var times = interpolant.parameterPositions,
  29465. values = interpolant.sampleValues;
  29466. times[ 0 ] = now;
  29467. values[ 0 ] = weightNow;
  29468. times[ 1 ] = now + duration;
  29469. values[ 1 ] = weightThen;
  29470. return this;
  29471. }
  29472. } );
  29473. /**
  29474. *
  29475. * Player for AnimationClips.
  29476. *
  29477. *
  29478. * @author Ben Houston / http://clara.io/
  29479. * @author David Sarno / http://lighthaus.us/
  29480. * @author tschw
  29481. */
  29482. function AnimationMixer( root ) {
  29483. this._root = root;
  29484. this._initMemoryManager();
  29485. this._accuIndex = 0;
  29486. this.time = 0;
  29487. this.timeScale = 1.0;
  29488. }
  29489. AnimationMixer.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  29490. constructor: AnimationMixer,
  29491. _bindAction: function ( action, prototypeAction ) {
  29492. var root = action._localRoot || this._root,
  29493. tracks = action._clip.tracks,
  29494. nTracks = tracks.length,
  29495. bindings = action._propertyBindings,
  29496. interpolants = action._interpolants,
  29497. rootUuid = root.uuid,
  29498. bindingsByRoot = this._bindingsByRootAndName,
  29499. bindingsByName = bindingsByRoot[ rootUuid ];
  29500. if ( bindingsByName === undefined ) {
  29501. bindingsByName = {};
  29502. bindingsByRoot[ rootUuid ] = bindingsByName;
  29503. }
  29504. for ( var i = 0; i !== nTracks; ++ i ) {
  29505. var track = tracks[ i ],
  29506. trackName = track.name,
  29507. binding = bindingsByName[ trackName ];
  29508. if ( binding !== undefined ) {
  29509. bindings[ i ] = binding;
  29510. } else {
  29511. binding = bindings[ i ];
  29512. if ( binding !== undefined ) {
  29513. // existing binding, make sure the cache knows
  29514. if ( binding._cacheIndex === null ) {
  29515. ++ binding.referenceCount;
  29516. this._addInactiveBinding( binding, rootUuid, trackName );
  29517. }
  29518. continue;
  29519. }
  29520. var path = prototypeAction && prototypeAction.
  29521. _propertyBindings[ i ].binding.parsedPath;
  29522. binding = new PropertyMixer(
  29523. PropertyBinding.create( root, trackName, path ),
  29524. track.ValueTypeName, track.getValueSize() );
  29525. ++ binding.referenceCount;
  29526. this._addInactiveBinding( binding, rootUuid, trackName );
  29527. bindings[ i ] = binding;
  29528. }
  29529. interpolants[ i ].resultBuffer = binding.buffer;
  29530. }
  29531. },
  29532. _activateAction: function ( action ) {
  29533. if ( ! this._isActiveAction( action ) ) {
  29534. if ( action._cacheIndex === null ) {
  29535. // this action has been forgotten by the cache, but the user
  29536. // appears to be still using it -> rebind
  29537. var rootUuid = ( action._localRoot || this._root ).uuid,
  29538. clipUuid = action._clip.uuid,
  29539. actionsForClip = this._actionsByClip[ clipUuid ];
  29540. this._bindAction( action,
  29541. actionsForClip && actionsForClip.knownActions[ 0 ] );
  29542. this._addInactiveAction( action, clipUuid, rootUuid );
  29543. }
  29544. var bindings = action._propertyBindings;
  29545. // increment reference counts / sort out state
  29546. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  29547. var binding = bindings[ i ];
  29548. if ( binding.useCount ++ === 0 ) {
  29549. this._lendBinding( binding );
  29550. binding.saveOriginalState();
  29551. }
  29552. }
  29553. this._lendAction( action );
  29554. }
  29555. },
  29556. _deactivateAction: function ( action ) {
  29557. if ( this._isActiveAction( action ) ) {
  29558. var bindings = action._propertyBindings;
  29559. // decrement reference counts / sort out state
  29560. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  29561. var binding = bindings[ i ];
  29562. if ( -- binding.useCount === 0 ) {
  29563. binding.restoreOriginalState();
  29564. this._takeBackBinding( binding );
  29565. }
  29566. }
  29567. this._takeBackAction( action );
  29568. }
  29569. },
  29570. // Memory manager
  29571. _initMemoryManager: function () {
  29572. this._actions = []; // 'nActiveActions' followed by inactive ones
  29573. this._nActiveActions = 0;
  29574. this._actionsByClip = {};
  29575. // inside:
  29576. // {
  29577. // knownActions: Array< AnimationAction > - used as prototypes
  29578. // actionByRoot: AnimationAction - lookup
  29579. // }
  29580. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  29581. this._nActiveBindings = 0;
  29582. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  29583. this._controlInterpolants = []; // same game as above
  29584. this._nActiveControlInterpolants = 0;
  29585. var scope = this;
  29586. this.stats = {
  29587. actions: {
  29588. get total() {
  29589. return scope._actions.length;
  29590. },
  29591. get inUse() {
  29592. return scope._nActiveActions;
  29593. }
  29594. },
  29595. bindings: {
  29596. get total() {
  29597. return scope._bindings.length;
  29598. },
  29599. get inUse() {
  29600. return scope._nActiveBindings;
  29601. }
  29602. },
  29603. controlInterpolants: {
  29604. get total() {
  29605. return scope._controlInterpolants.length;
  29606. },
  29607. get inUse() {
  29608. return scope._nActiveControlInterpolants;
  29609. }
  29610. }
  29611. };
  29612. },
  29613. // Memory management for AnimationAction objects
  29614. _isActiveAction: function ( action ) {
  29615. var index = action._cacheIndex;
  29616. return index !== null && index < this._nActiveActions;
  29617. },
  29618. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  29619. var actions = this._actions,
  29620. actionsByClip = this._actionsByClip,
  29621. actionsForClip = actionsByClip[ clipUuid ];
  29622. if ( actionsForClip === undefined ) {
  29623. actionsForClip = {
  29624. knownActions: [ action ],
  29625. actionByRoot: {}
  29626. };
  29627. action._byClipCacheIndex = 0;
  29628. actionsByClip[ clipUuid ] = actionsForClip;
  29629. } else {
  29630. var knownActions = actionsForClip.knownActions;
  29631. action._byClipCacheIndex = knownActions.length;
  29632. knownActions.push( action );
  29633. }
  29634. action._cacheIndex = actions.length;
  29635. actions.push( action );
  29636. actionsForClip.actionByRoot[ rootUuid ] = action;
  29637. },
  29638. _removeInactiveAction: function ( action ) {
  29639. var actions = this._actions,
  29640. lastInactiveAction = actions[ actions.length - 1 ],
  29641. cacheIndex = action._cacheIndex;
  29642. lastInactiveAction._cacheIndex = cacheIndex;
  29643. actions[ cacheIndex ] = lastInactiveAction;
  29644. actions.pop();
  29645. action._cacheIndex = null;
  29646. var clipUuid = action._clip.uuid,
  29647. actionsByClip = this._actionsByClip,
  29648. actionsForClip = actionsByClip[ clipUuid ],
  29649. knownActionsForClip = actionsForClip.knownActions,
  29650. lastKnownAction =
  29651. knownActionsForClip[ knownActionsForClip.length - 1 ],
  29652. byClipCacheIndex = action._byClipCacheIndex;
  29653. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  29654. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  29655. knownActionsForClip.pop();
  29656. action._byClipCacheIndex = null;
  29657. var actionByRoot = actionsForClip.actionByRoot,
  29658. rootUuid = ( action._localRoot || this._root ).uuid;
  29659. delete actionByRoot[ rootUuid ];
  29660. if ( knownActionsForClip.length === 0 ) {
  29661. delete actionsByClip[ clipUuid ];
  29662. }
  29663. this._removeInactiveBindingsForAction( action );
  29664. },
  29665. _removeInactiveBindingsForAction: function ( action ) {
  29666. var bindings = action._propertyBindings;
  29667. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  29668. var binding = bindings[ i ];
  29669. if ( -- binding.referenceCount === 0 ) {
  29670. this._removeInactiveBinding( binding );
  29671. }
  29672. }
  29673. },
  29674. _lendAction: function ( action ) {
  29675. // [ active actions | inactive actions ]
  29676. // [ active actions >| inactive actions ]
  29677. // s a
  29678. // <-swap->
  29679. // a s
  29680. var actions = this._actions,
  29681. prevIndex = action._cacheIndex,
  29682. lastActiveIndex = this._nActiveActions ++,
  29683. firstInactiveAction = actions[ lastActiveIndex ];
  29684. action._cacheIndex = lastActiveIndex;
  29685. actions[ lastActiveIndex ] = action;
  29686. firstInactiveAction._cacheIndex = prevIndex;
  29687. actions[ prevIndex ] = firstInactiveAction;
  29688. },
  29689. _takeBackAction: function ( action ) {
  29690. // [ active actions | inactive actions ]
  29691. // [ active actions |< inactive actions ]
  29692. // a s
  29693. // <-swap->
  29694. // s a
  29695. var actions = this._actions,
  29696. prevIndex = action._cacheIndex,
  29697. firstInactiveIndex = -- this._nActiveActions,
  29698. lastActiveAction = actions[ firstInactiveIndex ];
  29699. action._cacheIndex = firstInactiveIndex;
  29700. actions[ firstInactiveIndex ] = action;
  29701. lastActiveAction._cacheIndex = prevIndex;
  29702. actions[ prevIndex ] = lastActiveAction;
  29703. },
  29704. // Memory management for PropertyMixer objects
  29705. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  29706. var bindingsByRoot = this._bindingsByRootAndName,
  29707. bindingByName = bindingsByRoot[ rootUuid ],
  29708. bindings = this._bindings;
  29709. if ( bindingByName === undefined ) {
  29710. bindingByName = {};
  29711. bindingsByRoot[ rootUuid ] = bindingByName;
  29712. }
  29713. bindingByName[ trackName ] = binding;
  29714. binding._cacheIndex = bindings.length;
  29715. bindings.push( binding );
  29716. },
  29717. _removeInactiveBinding: function ( binding ) {
  29718. var bindings = this._bindings,
  29719. propBinding = binding.binding,
  29720. rootUuid = propBinding.rootNode.uuid,
  29721. trackName = propBinding.path,
  29722. bindingsByRoot = this._bindingsByRootAndName,
  29723. bindingByName = bindingsByRoot[ rootUuid ],
  29724. lastInactiveBinding = bindings[ bindings.length - 1 ],
  29725. cacheIndex = binding._cacheIndex;
  29726. lastInactiveBinding._cacheIndex = cacheIndex;
  29727. bindings[ cacheIndex ] = lastInactiveBinding;
  29728. bindings.pop();
  29729. delete bindingByName[ trackName ];
  29730. remove_empty_map: {
  29731. for ( var _ in bindingByName ) break remove_empty_map; // eslint-disable-line no-unused-vars
  29732. delete bindingsByRoot[ rootUuid ];
  29733. }
  29734. },
  29735. _lendBinding: function ( binding ) {
  29736. var bindings = this._bindings,
  29737. prevIndex = binding._cacheIndex,
  29738. lastActiveIndex = this._nActiveBindings ++,
  29739. firstInactiveBinding = bindings[ lastActiveIndex ];
  29740. binding._cacheIndex = lastActiveIndex;
  29741. bindings[ lastActiveIndex ] = binding;
  29742. firstInactiveBinding._cacheIndex = prevIndex;
  29743. bindings[ prevIndex ] = firstInactiveBinding;
  29744. },
  29745. _takeBackBinding: function ( binding ) {
  29746. var bindings = this._bindings,
  29747. prevIndex = binding._cacheIndex,
  29748. firstInactiveIndex = -- this._nActiveBindings,
  29749. lastActiveBinding = bindings[ firstInactiveIndex ];
  29750. binding._cacheIndex = firstInactiveIndex;
  29751. bindings[ firstInactiveIndex ] = binding;
  29752. lastActiveBinding._cacheIndex = prevIndex;
  29753. bindings[ prevIndex ] = lastActiveBinding;
  29754. },
  29755. // Memory management of Interpolants for weight and time scale
  29756. _lendControlInterpolant: function () {
  29757. var interpolants = this._controlInterpolants,
  29758. lastActiveIndex = this._nActiveControlInterpolants ++,
  29759. interpolant = interpolants[ lastActiveIndex ];
  29760. if ( interpolant === undefined ) {
  29761. interpolant = new LinearInterpolant(
  29762. new Float32Array( 2 ), new Float32Array( 2 ),
  29763. 1, this._controlInterpolantsResultBuffer );
  29764. interpolant.__cacheIndex = lastActiveIndex;
  29765. interpolants[ lastActiveIndex ] = interpolant;
  29766. }
  29767. return interpolant;
  29768. },
  29769. _takeBackControlInterpolant: function ( interpolant ) {
  29770. var interpolants = this._controlInterpolants,
  29771. prevIndex = interpolant.__cacheIndex,
  29772. firstInactiveIndex = -- this._nActiveControlInterpolants,
  29773. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  29774. interpolant.__cacheIndex = firstInactiveIndex;
  29775. interpolants[ firstInactiveIndex ] = interpolant;
  29776. lastActiveInterpolant.__cacheIndex = prevIndex;
  29777. interpolants[ prevIndex ] = lastActiveInterpolant;
  29778. },
  29779. _controlInterpolantsResultBuffer: new Float32Array( 1 ),
  29780. // return an action for a clip optionally using a custom root target
  29781. // object (this method allocates a lot of dynamic memory in case a
  29782. // previously unknown clip/root combination is specified)
  29783. clipAction: function ( clip, optionalRoot ) {
  29784. var root = optionalRoot || this._root,
  29785. rootUuid = root.uuid,
  29786. clipObject = typeof clip === 'string' ?
  29787. AnimationClip.findByName( root, clip ) : clip,
  29788. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  29789. actionsForClip = this._actionsByClip[ clipUuid ],
  29790. prototypeAction = null;
  29791. if ( actionsForClip !== undefined ) {
  29792. var existingAction =
  29793. actionsForClip.actionByRoot[ rootUuid ];
  29794. if ( existingAction !== undefined ) {
  29795. return existingAction;
  29796. }
  29797. // we know the clip, so we don't have to parse all
  29798. // the bindings again but can just copy
  29799. prototypeAction = actionsForClip.knownActions[ 0 ];
  29800. // also, take the clip from the prototype action
  29801. if ( clipObject === null )
  29802. clipObject = prototypeAction._clip;
  29803. }
  29804. // clip must be known when specified via string
  29805. if ( clipObject === null ) return null;
  29806. // allocate all resources required to run it
  29807. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  29808. this._bindAction( newAction, prototypeAction );
  29809. // and make the action known to the memory manager
  29810. this._addInactiveAction( newAction, clipUuid, rootUuid );
  29811. return newAction;
  29812. },
  29813. // get an existing action
  29814. existingAction: function ( clip, optionalRoot ) {
  29815. var root = optionalRoot || this._root,
  29816. rootUuid = root.uuid,
  29817. clipObject = typeof clip === 'string' ?
  29818. AnimationClip.findByName( root, clip ) : clip,
  29819. clipUuid = clipObject ? clipObject.uuid : clip,
  29820. actionsForClip = this._actionsByClip[ clipUuid ];
  29821. if ( actionsForClip !== undefined ) {
  29822. return actionsForClip.actionByRoot[ rootUuid ] || null;
  29823. }
  29824. return null;
  29825. },
  29826. // deactivates all previously scheduled actions
  29827. stopAllAction: function () {
  29828. var actions = this._actions,
  29829. nActions = this._nActiveActions,
  29830. bindings = this._bindings,
  29831. nBindings = this._nActiveBindings;
  29832. this._nActiveActions = 0;
  29833. this._nActiveBindings = 0;
  29834. for ( var i = 0; i !== nActions; ++ i ) {
  29835. actions[ i ].reset();
  29836. }
  29837. for ( var i = 0; i !== nBindings; ++ i ) {
  29838. bindings[ i ].useCount = 0;
  29839. }
  29840. return this;
  29841. },
  29842. // advance the time and update apply the animation
  29843. update: function ( deltaTime ) {
  29844. deltaTime *= this.timeScale;
  29845. var actions = this._actions,
  29846. nActions = this._nActiveActions,
  29847. time = this.time += deltaTime,
  29848. timeDirection = Math.sign( deltaTime ),
  29849. accuIndex = this._accuIndex ^= 1;
  29850. // run active actions
  29851. for ( var i = 0; i !== nActions; ++ i ) {
  29852. var action = actions[ i ];
  29853. action._update( time, deltaTime, timeDirection, accuIndex );
  29854. }
  29855. // update scene graph
  29856. var bindings = this._bindings,
  29857. nBindings = this._nActiveBindings;
  29858. for ( var i = 0; i !== nBindings; ++ i ) {
  29859. bindings[ i ].apply( accuIndex );
  29860. }
  29861. return this;
  29862. },
  29863. // return this mixer's root target object
  29864. getRoot: function () {
  29865. return this._root;
  29866. },
  29867. // free all resources specific to a particular clip
  29868. uncacheClip: function ( clip ) {
  29869. var actions = this._actions,
  29870. clipUuid = clip.uuid,
  29871. actionsByClip = this._actionsByClip,
  29872. actionsForClip = actionsByClip[ clipUuid ];
  29873. if ( actionsForClip !== undefined ) {
  29874. // note: just calling _removeInactiveAction would mess up the
  29875. // iteration state and also require updating the state we can
  29876. // just throw away
  29877. var actionsToRemove = actionsForClip.knownActions;
  29878. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  29879. var action = actionsToRemove[ i ];
  29880. this._deactivateAction( action );
  29881. var cacheIndex = action._cacheIndex,
  29882. lastInactiveAction = actions[ actions.length - 1 ];
  29883. action._cacheIndex = null;
  29884. action._byClipCacheIndex = null;
  29885. lastInactiveAction._cacheIndex = cacheIndex;
  29886. actions[ cacheIndex ] = lastInactiveAction;
  29887. actions.pop();
  29888. this._removeInactiveBindingsForAction( action );
  29889. }
  29890. delete actionsByClip[ clipUuid ];
  29891. }
  29892. },
  29893. // free all resources specific to a particular root target object
  29894. uncacheRoot: function ( root ) {
  29895. var rootUuid = root.uuid,
  29896. actionsByClip = this._actionsByClip;
  29897. for ( var clipUuid in actionsByClip ) {
  29898. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  29899. action = actionByRoot[ rootUuid ];
  29900. if ( action !== undefined ) {
  29901. this._deactivateAction( action );
  29902. this._removeInactiveAction( action );
  29903. }
  29904. }
  29905. var bindingsByRoot = this._bindingsByRootAndName,
  29906. bindingByName = bindingsByRoot[ rootUuid ];
  29907. if ( bindingByName !== undefined ) {
  29908. for ( var trackName in bindingByName ) {
  29909. var binding = bindingByName[ trackName ];
  29910. binding.restoreOriginalState();
  29911. this._removeInactiveBinding( binding );
  29912. }
  29913. }
  29914. },
  29915. // remove a targeted clip from the cache
  29916. uncacheAction: function ( clip, optionalRoot ) {
  29917. var action = this.existingAction( clip, optionalRoot );
  29918. if ( action !== null ) {
  29919. this._deactivateAction( action );
  29920. this._removeInactiveAction( action );
  29921. }
  29922. }
  29923. } );
  29924. /**
  29925. * @author mrdoob / http://mrdoob.com/
  29926. */
  29927. function Uniform( value ) {
  29928. if ( typeof value === 'string' ) {
  29929. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  29930. value = arguments[ 1 ];
  29931. }
  29932. this.value = value;
  29933. }
  29934. Uniform.prototype.clone = function () {
  29935. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  29936. };
  29937. /**
  29938. * @author benaadams / https://twitter.com/ben_a_adams
  29939. */
  29940. function InstancedBufferGeometry() {
  29941. BufferGeometry.call( this );
  29942. this.type = 'InstancedBufferGeometry';
  29943. this.maxInstancedCount = undefined;
  29944. }
  29945. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  29946. constructor: InstancedBufferGeometry,
  29947. isInstancedBufferGeometry: true,
  29948. copy: function ( source ) {
  29949. BufferGeometry.prototype.copy.call( this, source );
  29950. this.maxInstancedCount = source.maxInstancedCount;
  29951. return this;
  29952. },
  29953. clone: function () {
  29954. return new this.constructor().copy( this );
  29955. }
  29956. } );
  29957. /**
  29958. * @author benaadams / https://twitter.com/ben_a_adams
  29959. */
  29960. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  29961. InterleavedBuffer.call( this, array, stride );
  29962. this.meshPerAttribute = meshPerAttribute || 1;
  29963. }
  29964. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  29965. constructor: InstancedInterleavedBuffer,
  29966. isInstancedInterleavedBuffer: true,
  29967. copy: function ( source ) {
  29968. InterleavedBuffer.prototype.copy.call( this, source );
  29969. this.meshPerAttribute = source.meshPerAttribute;
  29970. return this;
  29971. }
  29972. } );
  29973. /**
  29974. * @author benaadams / https://twitter.com/ben_a_adams
  29975. */
  29976. function InstancedBufferAttribute( array, itemSize, normalized, meshPerAttribute ) {
  29977. if ( typeof ( normalized ) === 'number' ) {
  29978. meshPerAttribute = normalized;
  29979. normalized = false;
  29980. console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );
  29981. }
  29982. BufferAttribute.call( this, array, itemSize, normalized );
  29983. this.meshPerAttribute = meshPerAttribute || 1;
  29984. }
  29985. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  29986. constructor: InstancedBufferAttribute,
  29987. isInstancedBufferAttribute: true,
  29988. copy: function ( source ) {
  29989. BufferAttribute.prototype.copy.call( this, source );
  29990. this.meshPerAttribute = source.meshPerAttribute;
  29991. return this;
  29992. }
  29993. } );
  29994. /**
  29995. * @author mrdoob / http://mrdoob.com/
  29996. * @author bhouston / http://clara.io/
  29997. * @author stephomi / http://stephaneginier.com/
  29998. */
  29999. function Raycaster( origin, direction, near, far ) {
  30000. this.ray = new Ray( origin, direction );
  30001. // direction is assumed to be normalized (for accurate distance calculations)
  30002. this.near = near || 0;
  30003. this.far = far || Infinity;
  30004. this.params = {
  30005. Mesh: {},
  30006. Line: {},
  30007. LOD: {},
  30008. Points: { threshold: 1 },
  30009. Sprite: {}
  30010. };
  30011. Object.defineProperties( this.params, {
  30012. PointCloud: {
  30013. get: function () {
  30014. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  30015. return this.Points;
  30016. }
  30017. }
  30018. } );
  30019. }
  30020. function ascSort( a, b ) {
  30021. return a.distance - b.distance;
  30022. }
  30023. function intersectObject( object, raycaster, intersects, recursive ) {
  30024. if ( object.visible === false ) return;
  30025. object.raycast( raycaster, intersects );
  30026. if ( recursive === true ) {
  30027. var children = object.children;
  30028. for ( var i = 0, l = children.length; i < l; i ++ ) {
  30029. intersectObject( children[ i ], raycaster, intersects, true );
  30030. }
  30031. }
  30032. }
  30033. Object.assign( Raycaster.prototype, {
  30034. linePrecision: 1,
  30035. set: function ( origin, direction ) {
  30036. // direction is assumed to be normalized (for accurate distance calculations)
  30037. this.ray.set( origin, direction );
  30038. },
  30039. setFromCamera: function ( coords, camera ) {
  30040. if ( ( camera && camera.isPerspectiveCamera ) ) {
  30041. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  30042. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  30043. } else if ( ( camera && camera.isOrthographicCamera ) ) {
  30044. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  30045. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  30046. } else {
  30047. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  30048. }
  30049. },
  30050. intersectObject: function ( object, recursive, optionalTarget ) {
  30051. var intersects = optionalTarget || [];
  30052. intersectObject( object, this, intersects, recursive );
  30053. intersects.sort( ascSort );
  30054. return intersects;
  30055. },
  30056. intersectObjects: function ( objects, recursive, optionalTarget ) {
  30057. var intersects = optionalTarget || [];
  30058. if ( Array.isArray( objects ) === false ) {
  30059. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  30060. return intersects;
  30061. }
  30062. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  30063. intersectObject( objects[ i ], this, intersects, recursive );
  30064. }
  30065. intersects.sort( ascSort );
  30066. return intersects;
  30067. }
  30068. } );
  30069. /**
  30070. * @author bhouston / http://clara.io
  30071. * @author WestLangley / http://github.com/WestLangley
  30072. *
  30073. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  30074. *
  30075. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  30076. * The azimuthal angle (theta) is measured from the positive z-axiz.
  30077. */
  30078. function Spherical( radius, phi, theta ) {
  30079. this.radius = ( radius !== undefined ) ? radius : 1.0;
  30080. this.phi = ( phi !== undefined ) ? phi : 0; // polar angle
  30081. this.theta = ( theta !== undefined ) ? theta : 0; // azimuthal angle
  30082. return this;
  30083. }
  30084. Object.assign( Spherical.prototype, {
  30085. set: function ( radius, phi, theta ) {
  30086. this.radius = radius;
  30087. this.phi = phi;
  30088. this.theta = theta;
  30089. return this;
  30090. },
  30091. clone: function () {
  30092. return new this.constructor().copy( this );
  30093. },
  30094. copy: function ( other ) {
  30095. this.radius = other.radius;
  30096. this.phi = other.phi;
  30097. this.theta = other.theta;
  30098. return this;
  30099. },
  30100. // restrict phi to be betwee EPS and PI-EPS
  30101. makeSafe: function () {
  30102. var EPS = 0.000001;
  30103. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  30104. return this;
  30105. },
  30106. setFromVector3: function ( v ) {
  30107. return this.setFromCartesianCoords( v.x, v.y, v.z );
  30108. },
  30109. setFromCartesianCoords: function ( x, y, z ) {
  30110. this.radius = Math.sqrt( x * x + y * y + z * z );
  30111. if ( this.radius === 0 ) {
  30112. this.theta = 0;
  30113. this.phi = 0;
  30114. } else {
  30115. this.theta = Math.atan2( x, z );
  30116. this.phi = Math.acos( _Math.clamp( y / this.radius, - 1, 1 ) );
  30117. }
  30118. return this;
  30119. }
  30120. } );
  30121. /**
  30122. * @author Mugen87 / https://github.com/Mugen87
  30123. *
  30124. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  30125. *
  30126. */
  30127. function Cylindrical( radius, theta, y ) {
  30128. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  30129. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  30130. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  30131. return this;
  30132. }
  30133. Object.assign( Cylindrical.prototype, {
  30134. set: function ( radius, theta, y ) {
  30135. this.radius = radius;
  30136. this.theta = theta;
  30137. this.y = y;
  30138. return this;
  30139. },
  30140. clone: function () {
  30141. return new this.constructor().copy( this );
  30142. },
  30143. copy: function ( other ) {
  30144. this.radius = other.radius;
  30145. this.theta = other.theta;
  30146. this.y = other.y;
  30147. return this;
  30148. },
  30149. setFromVector3: function ( v ) {
  30150. return this.setFromCartesianCoords( v.x, v.y, v.z );
  30151. },
  30152. setFromCartesianCoords: function ( x, y, z ) {
  30153. this.radius = Math.sqrt( x * x + z * z );
  30154. this.theta = Math.atan2( x, z );
  30155. this.y = y;
  30156. return this;
  30157. }
  30158. } );
  30159. /**
  30160. * @author bhouston / http://clara.io
  30161. */
  30162. function Box2( min, max ) {
  30163. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  30164. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  30165. }
  30166. Object.assign( Box2.prototype, {
  30167. set: function ( min, max ) {
  30168. this.min.copy( min );
  30169. this.max.copy( max );
  30170. return this;
  30171. },
  30172. setFromPoints: function ( points ) {
  30173. this.makeEmpty();
  30174. for ( var i = 0, il = points.length; i < il; i ++ ) {
  30175. this.expandByPoint( points[ i ] );
  30176. }
  30177. return this;
  30178. },
  30179. setFromCenterAndSize: function () {
  30180. var v1 = new Vector2();
  30181. return function setFromCenterAndSize( center, size ) {
  30182. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  30183. this.min.copy( center ).sub( halfSize );
  30184. this.max.copy( center ).add( halfSize );
  30185. return this;
  30186. };
  30187. }(),
  30188. clone: function () {
  30189. return new this.constructor().copy( this );
  30190. },
  30191. copy: function ( box ) {
  30192. this.min.copy( box.min );
  30193. this.max.copy( box.max );
  30194. return this;
  30195. },
  30196. makeEmpty: function () {
  30197. this.min.x = this.min.y = + Infinity;
  30198. this.max.x = this.max.y = - Infinity;
  30199. return this;
  30200. },
  30201. isEmpty: function () {
  30202. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  30203. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  30204. },
  30205. getCenter: function ( target ) {
  30206. if ( target === undefined ) {
  30207. console.warn( 'THREE.Box2: .getCenter() target is now required' );
  30208. target = new Vector2();
  30209. }
  30210. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  30211. },
  30212. getSize: function ( target ) {
  30213. if ( target === undefined ) {
  30214. console.warn( 'THREE.Box2: .getSize() target is now required' );
  30215. target = new Vector2();
  30216. }
  30217. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  30218. },
  30219. expandByPoint: function ( point ) {
  30220. this.min.min( point );
  30221. this.max.max( point );
  30222. return this;
  30223. },
  30224. expandByVector: function ( vector ) {
  30225. this.min.sub( vector );
  30226. this.max.add( vector );
  30227. return this;
  30228. },
  30229. expandByScalar: function ( scalar ) {
  30230. this.min.addScalar( - scalar );
  30231. this.max.addScalar( scalar );
  30232. return this;
  30233. },
  30234. containsPoint: function ( point ) {
  30235. return point.x < this.min.x || point.x > this.max.x ||
  30236. point.y < this.min.y || point.y > this.max.y ? false : true;
  30237. },
  30238. containsBox: function ( box ) {
  30239. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  30240. this.min.y <= box.min.y && box.max.y <= this.max.y;
  30241. },
  30242. getParameter: function ( point, target ) {
  30243. // This can potentially have a divide by zero if the box
  30244. // has a size dimension of 0.
  30245. if ( target === undefined ) {
  30246. console.warn( 'THREE.Box2: .getParameter() target is now required' );
  30247. target = new Vector2();
  30248. }
  30249. return target.set(
  30250. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  30251. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  30252. );
  30253. },
  30254. intersectsBox: function ( box ) {
  30255. // using 4 splitting planes to rule out intersections
  30256. return box.max.x < this.min.x || box.min.x > this.max.x ||
  30257. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  30258. },
  30259. clampPoint: function ( point, target ) {
  30260. if ( target === undefined ) {
  30261. console.warn( 'THREE.Box2: .clampPoint() target is now required' );
  30262. target = new Vector2();
  30263. }
  30264. return target.copy( point ).clamp( this.min, this.max );
  30265. },
  30266. distanceToPoint: function () {
  30267. var v1 = new Vector2();
  30268. return function distanceToPoint( point ) {
  30269. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  30270. return clampedPoint.sub( point ).length();
  30271. };
  30272. }(),
  30273. intersect: function ( box ) {
  30274. this.min.max( box.min );
  30275. this.max.min( box.max );
  30276. return this;
  30277. },
  30278. union: function ( box ) {
  30279. this.min.min( box.min );
  30280. this.max.max( box.max );
  30281. return this;
  30282. },
  30283. translate: function ( offset ) {
  30284. this.min.add( offset );
  30285. this.max.add( offset );
  30286. return this;
  30287. },
  30288. equals: function ( box ) {
  30289. return box.min.equals( this.min ) && box.max.equals( this.max );
  30290. }
  30291. } );
  30292. /**
  30293. * @author bhouston / http://clara.io
  30294. */
  30295. function Line3( start, end ) {
  30296. this.start = ( start !== undefined ) ? start : new Vector3();
  30297. this.end = ( end !== undefined ) ? end : new Vector3();
  30298. }
  30299. Object.assign( Line3.prototype, {
  30300. set: function ( start, end ) {
  30301. this.start.copy( start );
  30302. this.end.copy( end );
  30303. return this;
  30304. },
  30305. clone: function () {
  30306. return new this.constructor().copy( this );
  30307. },
  30308. copy: function ( line ) {
  30309. this.start.copy( line.start );
  30310. this.end.copy( line.end );
  30311. return this;
  30312. },
  30313. getCenter: function ( target ) {
  30314. if ( target === undefined ) {
  30315. console.warn( 'THREE.Line3: .getCenter() target is now required' );
  30316. target = new Vector3();
  30317. }
  30318. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  30319. },
  30320. delta: function ( target ) {
  30321. if ( target === undefined ) {
  30322. console.warn( 'THREE.Line3: .delta() target is now required' );
  30323. target = new Vector3();
  30324. }
  30325. return target.subVectors( this.end, this.start );
  30326. },
  30327. distanceSq: function () {
  30328. return this.start.distanceToSquared( this.end );
  30329. },
  30330. distance: function () {
  30331. return this.start.distanceTo( this.end );
  30332. },
  30333. at: function ( t, target ) {
  30334. if ( target === undefined ) {
  30335. console.warn( 'THREE.Line3: .at() target is now required' );
  30336. target = new Vector3();
  30337. }
  30338. return this.delta( target ).multiplyScalar( t ).add( this.start );
  30339. },
  30340. closestPointToPointParameter: function () {
  30341. var startP = new Vector3();
  30342. var startEnd = new Vector3();
  30343. return function closestPointToPointParameter( point, clampToLine ) {
  30344. startP.subVectors( point, this.start );
  30345. startEnd.subVectors( this.end, this.start );
  30346. var startEnd2 = startEnd.dot( startEnd );
  30347. var startEnd_startP = startEnd.dot( startP );
  30348. var t = startEnd_startP / startEnd2;
  30349. if ( clampToLine ) {
  30350. t = _Math.clamp( t, 0, 1 );
  30351. }
  30352. return t;
  30353. };
  30354. }(),
  30355. closestPointToPoint: function ( point, clampToLine, target ) {
  30356. var t = this.closestPointToPointParameter( point, clampToLine );
  30357. if ( target === undefined ) {
  30358. console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' );
  30359. target = new Vector3();
  30360. }
  30361. return this.delta( target ).multiplyScalar( t ).add( this.start );
  30362. },
  30363. applyMatrix4: function ( matrix ) {
  30364. this.start.applyMatrix4( matrix );
  30365. this.end.applyMatrix4( matrix );
  30366. return this;
  30367. },
  30368. equals: function ( line ) {
  30369. return line.start.equals( this.start ) && line.end.equals( this.end );
  30370. }
  30371. } );
  30372. /**
  30373. * @author alteredq / http://alteredqualia.com/
  30374. */
  30375. function ImmediateRenderObject( material ) {
  30376. Object3D.call( this );
  30377. this.material = material;
  30378. this.render = function ( /* renderCallback */ ) {};
  30379. }
  30380. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  30381. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  30382. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  30383. /**
  30384. * @author mrdoob / http://mrdoob.com/
  30385. * @author WestLangley / http://github.com/WestLangley
  30386. */
  30387. function VertexNormalsHelper( object, size, hex, linewidth ) {
  30388. this.object = object;
  30389. this.size = ( size !== undefined ) ? size : 1;
  30390. var color = ( hex !== undefined ) ? hex : 0xff0000;
  30391. var width = ( linewidth !== undefined ) ? linewidth : 1;
  30392. //
  30393. var nNormals = 0;
  30394. var objGeometry = this.object.geometry;
  30395. if ( objGeometry && objGeometry.isGeometry ) {
  30396. nNormals = objGeometry.faces.length * 3;
  30397. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  30398. nNormals = objGeometry.attributes.normal.count;
  30399. }
  30400. //
  30401. var geometry = new BufferGeometry();
  30402. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  30403. geometry.addAttribute( 'position', positions );
  30404. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  30405. //
  30406. this.matrixAutoUpdate = false;
  30407. this.update();
  30408. }
  30409. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  30410. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  30411. VertexNormalsHelper.prototype.update = ( function () {
  30412. var v1 = new Vector3();
  30413. var v2 = new Vector3();
  30414. var normalMatrix = new Matrix3();
  30415. return function update() {
  30416. var keys = [ 'a', 'b', 'c' ];
  30417. this.object.updateMatrixWorld( true );
  30418. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  30419. var matrixWorld = this.object.matrixWorld;
  30420. var position = this.geometry.attributes.position;
  30421. //
  30422. var objGeometry = this.object.geometry;
  30423. if ( objGeometry && objGeometry.isGeometry ) {
  30424. var vertices = objGeometry.vertices;
  30425. var faces = objGeometry.faces;
  30426. var idx = 0;
  30427. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  30428. var face = faces[ i ];
  30429. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  30430. var vertex = vertices[ face[ keys[ j ] ] ];
  30431. var normal = face.vertexNormals[ j ];
  30432. v1.copy( vertex ).applyMatrix4( matrixWorld );
  30433. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  30434. position.setXYZ( idx, v1.x, v1.y, v1.z );
  30435. idx = idx + 1;
  30436. position.setXYZ( idx, v2.x, v2.y, v2.z );
  30437. idx = idx + 1;
  30438. }
  30439. }
  30440. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  30441. var objPos = objGeometry.attributes.position;
  30442. var objNorm = objGeometry.attributes.normal;
  30443. var idx = 0;
  30444. // for simplicity, ignore index and drawcalls, and render every normal
  30445. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  30446. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  30447. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  30448. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  30449. position.setXYZ( idx, v1.x, v1.y, v1.z );
  30450. idx = idx + 1;
  30451. position.setXYZ( idx, v2.x, v2.y, v2.z );
  30452. idx = idx + 1;
  30453. }
  30454. }
  30455. position.needsUpdate = true;
  30456. };
  30457. }() );
  30458. /**
  30459. * @author alteredq / http://alteredqualia.com/
  30460. * @author mrdoob / http://mrdoob.com/
  30461. * @author WestLangley / http://github.com/WestLangley
  30462. */
  30463. function SpotLightHelper( light, color ) {
  30464. Object3D.call( this );
  30465. this.light = light;
  30466. this.light.updateMatrixWorld();
  30467. this.matrix = light.matrixWorld;
  30468. this.matrixAutoUpdate = false;
  30469. this.color = color;
  30470. var geometry = new BufferGeometry();
  30471. var positions = [
  30472. 0, 0, 0, 0, 0, 1,
  30473. 0, 0, 0, 1, 0, 1,
  30474. 0, 0, 0, - 1, 0, 1,
  30475. 0, 0, 0, 0, 1, 1,
  30476. 0, 0, 0, 0, - 1, 1
  30477. ];
  30478. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  30479. var p1 = ( i / l ) * Math.PI * 2;
  30480. var p2 = ( j / l ) * Math.PI * 2;
  30481. positions.push(
  30482. Math.cos( p1 ), Math.sin( p1 ), 1,
  30483. Math.cos( p2 ), Math.sin( p2 ), 1
  30484. );
  30485. }
  30486. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  30487. var material = new LineBasicMaterial( { fog: false } );
  30488. this.cone = new LineSegments( geometry, material );
  30489. this.add( this.cone );
  30490. this.update();
  30491. }
  30492. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  30493. SpotLightHelper.prototype.constructor = SpotLightHelper;
  30494. SpotLightHelper.prototype.dispose = function () {
  30495. this.cone.geometry.dispose();
  30496. this.cone.material.dispose();
  30497. };
  30498. SpotLightHelper.prototype.update = function () {
  30499. var vector = new Vector3();
  30500. var vector2 = new Vector3();
  30501. return function update() {
  30502. this.light.updateMatrixWorld();
  30503. var coneLength = this.light.distance ? this.light.distance : 1000;
  30504. var coneWidth = coneLength * Math.tan( this.light.angle );
  30505. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  30506. vector.setFromMatrixPosition( this.light.matrixWorld );
  30507. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  30508. this.cone.lookAt( vector2.sub( vector ) );
  30509. if ( this.color !== undefined ) {
  30510. this.cone.material.color.set( this.color );
  30511. } else {
  30512. this.cone.material.color.copy( this.light.color );
  30513. }
  30514. };
  30515. }();
  30516. /**
  30517. * @author Sean Griffin / http://twitter.com/sgrif
  30518. * @author Michael Guerrero / http://realitymeltdown.com
  30519. * @author mrdoob / http://mrdoob.com/
  30520. * @author ikerr / http://verold.com
  30521. * @author Mugen87 / https://github.com/Mugen87
  30522. */
  30523. function getBoneList( object ) {
  30524. var boneList = [];
  30525. if ( object && object.isBone ) {
  30526. boneList.push( object );
  30527. }
  30528. for ( var i = 0; i < object.children.length; i ++ ) {
  30529. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  30530. }
  30531. return boneList;
  30532. }
  30533. function SkeletonHelper( object ) {
  30534. var bones = getBoneList( object );
  30535. var geometry = new BufferGeometry();
  30536. var vertices = [];
  30537. var colors = [];
  30538. var color1 = new Color( 0, 0, 1 );
  30539. var color2 = new Color( 0, 1, 0 );
  30540. for ( var i = 0; i < bones.length; i ++ ) {
  30541. var bone = bones[ i ];
  30542. if ( bone.parent && bone.parent.isBone ) {
  30543. vertices.push( 0, 0, 0 );
  30544. vertices.push( 0, 0, 0 );
  30545. colors.push( color1.r, color1.g, color1.b );
  30546. colors.push( color2.r, color2.g, color2.b );
  30547. }
  30548. }
  30549. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30550. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30551. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  30552. LineSegments.call( this, geometry, material );
  30553. this.root = object;
  30554. this.bones = bones;
  30555. this.matrix = object.matrixWorld;
  30556. this.matrixAutoUpdate = false;
  30557. }
  30558. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  30559. SkeletonHelper.prototype.constructor = SkeletonHelper;
  30560. SkeletonHelper.prototype.updateMatrixWorld = function () {
  30561. var vector = new Vector3();
  30562. var boneMatrix = new Matrix4();
  30563. var matrixWorldInv = new Matrix4();
  30564. return function updateMatrixWorld( force ) {
  30565. var bones = this.bones;
  30566. var geometry = this.geometry;
  30567. var position = geometry.getAttribute( 'position' );
  30568. matrixWorldInv.getInverse( this.root.matrixWorld );
  30569. for ( var i = 0, j = 0; i < bones.length; i ++ ) {
  30570. var bone = bones[ i ];
  30571. if ( bone.parent && bone.parent.isBone ) {
  30572. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  30573. vector.setFromMatrixPosition( boneMatrix );
  30574. position.setXYZ( j, vector.x, vector.y, vector.z );
  30575. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  30576. vector.setFromMatrixPosition( boneMatrix );
  30577. position.setXYZ( j + 1, vector.x, vector.y, vector.z );
  30578. j += 2;
  30579. }
  30580. }
  30581. geometry.getAttribute( 'position' ).needsUpdate = true;
  30582. Object3D.prototype.updateMatrixWorld.call( this, force );
  30583. };
  30584. }();
  30585. /**
  30586. * @author alteredq / http://alteredqualia.com/
  30587. * @author mrdoob / http://mrdoob.com/
  30588. */
  30589. function PointLightHelper( light, sphereSize, color ) {
  30590. this.light = light;
  30591. this.light.updateMatrixWorld();
  30592. this.color = color;
  30593. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  30594. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  30595. Mesh.call( this, geometry, material );
  30596. this.matrix = this.light.matrixWorld;
  30597. this.matrixAutoUpdate = false;
  30598. this.update();
  30599. /*
  30600. var distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  30601. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  30602. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  30603. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  30604. var d = light.distance;
  30605. if ( d === 0.0 ) {
  30606. this.lightDistance.visible = false;
  30607. } else {
  30608. this.lightDistance.scale.set( d, d, d );
  30609. }
  30610. this.add( this.lightDistance );
  30611. */
  30612. }
  30613. PointLightHelper.prototype = Object.create( Mesh.prototype );
  30614. PointLightHelper.prototype.constructor = PointLightHelper;
  30615. PointLightHelper.prototype.dispose = function () {
  30616. this.geometry.dispose();
  30617. this.material.dispose();
  30618. };
  30619. PointLightHelper.prototype.update = function () {
  30620. if ( this.color !== undefined ) {
  30621. this.material.color.set( this.color );
  30622. } else {
  30623. this.material.color.copy( this.light.color );
  30624. }
  30625. /*
  30626. var d = this.light.distance;
  30627. if ( d === 0.0 ) {
  30628. this.lightDistance.visible = false;
  30629. } else {
  30630. this.lightDistance.visible = true;
  30631. this.lightDistance.scale.set( d, d, d );
  30632. }
  30633. */
  30634. };
  30635. /**
  30636. * @author abelnation / http://github.com/abelnation
  30637. * @author Mugen87 / http://github.com/Mugen87
  30638. * @author WestLangley / http://github.com/WestLangley
  30639. */
  30640. function RectAreaLightHelper( light, color ) {
  30641. Object3D.call( this );
  30642. this.light = light;
  30643. this.light.updateMatrixWorld();
  30644. this.matrix = light.matrixWorld;
  30645. this.matrixAutoUpdate = false;
  30646. this.color = color;
  30647. var material = new LineBasicMaterial( { fog: false } );
  30648. var geometry = new BufferGeometry();
  30649. geometry.addAttribute( 'position', new BufferAttribute( new Float32Array( 5 * 3 ), 3 ) );
  30650. this.line = new Line( geometry, material );
  30651. this.add( this.line );
  30652. this.update();
  30653. }
  30654. RectAreaLightHelper.prototype = Object.create( Object3D.prototype );
  30655. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  30656. RectAreaLightHelper.prototype.dispose = function () {
  30657. this.children[ 0 ].geometry.dispose();
  30658. this.children[ 0 ].material.dispose();
  30659. };
  30660. RectAreaLightHelper.prototype.update = function () {
  30661. // calculate new dimensions of the helper
  30662. var hx = this.light.width * 0.5;
  30663. var hy = this.light.height * 0.5;
  30664. var position = this.line.geometry.attributes.position;
  30665. var array = position.array;
  30666. // update vertices
  30667. array[ 0 ] = hx; array[ 1 ] = - hy; array[ 2 ] = 0;
  30668. array[ 3 ] = hx; array[ 4 ] = hy; array[ 5 ] = 0;
  30669. array[ 6 ] = - hx; array[ 7 ] = hy; array[ 8 ] = 0;
  30670. array[ 9 ] = - hx; array[ 10 ] = - hy; array[ 11 ] = 0;
  30671. array[ 12 ] = hx; array[ 13 ] = - hy; array[ 14 ] = 0;
  30672. position.needsUpdate = true;
  30673. if ( this.color !== undefined ) {
  30674. this.line.material.color.set( this.color );
  30675. } else {
  30676. this.line.material.color.copy( this.light.color );
  30677. }
  30678. };
  30679. /**
  30680. * @author alteredq / http://alteredqualia.com/
  30681. * @author mrdoob / http://mrdoob.com/
  30682. * @author Mugen87 / https://github.com/Mugen87
  30683. */
  30684. function HemisphereLightHelper( light, size, color ) {
  30685. Object3D.call( this );
  30686. this.light = light;
  30687. this.light.updateMatrixWorld();
  30688. this.matrix = light.matrixWorld;
  30689. this.matrixAutoUpdate = false;
  30690. this.color = color;
  30691. var geometry = new OctahedronBufferGeometry( size );
  30692. geometry.rotateY( Math.PI * 0.5 );
  30693. this.material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  30694. if ( this.color === undefined ) this.material.vertexColors = VertexColors;
  30695. var position = geometry.getAttribute( 'position' );
  30696. var colors = new Float32Array( position.count * 3 );
  30697. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  30698. this.add( new Mesh( geometry, this.material ) );
  30699. this.update();
  30700. }
  30701. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  30702. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  30703. HemisphereLightHelper.prototype.dispose = function () {
  30704. this.children[ 0 ].geometry.dispose();
  30705. this.children[ 0 ].material.dispose();
  30706. };
  30707. HemisphereLightHelper.prototype.update = function () {
  30708. var vector = new Vector3();
  30709. var color1 = new Color();
  30710. var color2 = new Color();
  30711. return function update() {
  30712. var mesh = this.children[ 0 ];
  30713. if ( this.color !== undefined ) {
  30714. this.material.color.set( this.color );
  30715. } else {
  30716. var colors = mesh.geometry.getAttribute( 'color' );
  30717. color1.copy( this.light.color );
  30718. color2.copy( this.light.groundColor );
  30719. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  30720. var color = ( i < ( l / 2 ) ) ? color1 : color2;
  30721. colors.setXYZ( i, color.r, color.g, color.b );
  30722. }
  30723. colors.needsUpdate = true;
  30724. }
  30725. mesh.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  30726. };
  30727. }();
  30728. /**
  30729. * @author mrdoob / http://mrdoob.com/
  30730. */
  30731. function GridHelper( size, divisions, color1, color2 ) {
  30732. size = size || 10;
  30733. divisions = divisions || 10;
  30734. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  30735. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  30736. var center = divisions / 2;
  30737. var step = size / divisions;
  30738. var halfSize = size / 2;
  30739. var vertices = [], colors = [];
  30740. for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  30741. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  30742. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  30743. var color = i === center ? color1 : color2;
  30744. color.toArray( colors, j ); j += 3;
  30745. color.toArray( colors, j ); j += 3;
  30746. color.toArray( colors, j ); j += 3;
  30747. color.toArray( colors, j ); j += 3;
  30748. }
  30749. var geometry = new BufferGeometry();
  30750. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30751. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30752. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  30753. LineSegments.call( this, geometry, material );
  30754. }
  30755. GridHelper.prototype = Object.create( LineSegments.prototype );
  30756. GridHelper.prototype.constructor = GridHelper;
  30757. /**
  30758. * @author mrdoob / http://mrdoob.com/
  30759. * @author Mugen87 / http://github.com/Mugen87
  30760. * @author Hectate / http://www.github.com/Hectate
  30761. */
  30762. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  30763. radius = radius || 10;
  30764. radials = radials || 16;
  30765. circles = circles || 8;
  30766. divisions = divisions || 64;
  30767. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  30768. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  30769. var vertices = [];
  30770. var colors = [];
  30771. var x, z;
  30772. var v, i, j, r, color;
  30773. // create the radials
  30774. for ( i = 0; i <= radials; i ++ ) {
  30775. v = ( i / radials ) * ( Math.PI * 2 );
  30776. x = Math.sin( v ) * radius;
  30777. z = Math.cos( v ) * radius;
  30778. vertices.push( 0, 0, 0 );
  30779. vertices.push( x, 0, z );
  30780. color = ( i & 1 ) ? color1 : color2;
  30781. colors.push( color.r, color.g, color.b );
  30782. colors.push( color.r, color.g, color.b );
  30783. }
  30784. // create the circles
  30785. for ( i = 0; i <= circles; i ++ ) {
  30786. color = ( i & 1 ) ? color1 : color2;
  30787. r = radius - ( radius / circles * i );
  30788. for ( j = 0; j < divisions; j ++ ) {
  30789. // first vertex
  30790. v = ( j / divisions ) * ( Math.PI * 2 );
  30791. x = Math.sin( v ) * r;
  30792. z = Math.cos( v ) * r;
  30793. vertices.push( x, 0, z );
  30794. colors.push( color.r, color.g, color.b );
  30795. // second vertex
  30796. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  30797. x = Math.sin( v ) * r;
  30798. z = Math.cos( v ) * r;
  30799. vertices.push( x, 0, z );
  30800. colors.push( color.r, color.g, color.b );
  30801. }
  30802. }
  30803. var geometry = new BufferGeometry();
  30804. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30805. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30806. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  30807. LineSegments.call( this, geometry, material );
  30808. }
  30809. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  30810. PolarGridHelper.prototype.constructor = PolarGridHelper;
  30811. /**
  30812. * @author mrdoob / http://mrdoob.com/
  30813. * @author WestLangley / http://github.com/WestLangley
  30814. */
  30815. function FaceNormalsHelper( object, size, hex, linewidth ) {
  30816. // FaceNormalsHelper only supports THREE.Geometry
  30817. this.object = object;
  30818. this.size = ( size !== undefined ) ? size : 1;
  30819. var color = ( hex !== undefined ) ? hex : 0xffff00;
  30820. var width = ( linewidth !== undefined ) ? linewidth : 1;
  30821. //
  30822. var nNormals = 0;
  30823. var objGeometry = this.object.geometry;
  30824. if ( objGeometry && objGeometry.isGeometry ) {
  30825. nNormals = objGeometry.faces.length;
  30826. } else {
  30827. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  30828. }
  30829. //
  30830. var geometry = new BufferGeometry();
  30831. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  30832. geometry.addAttribute( 'position', positions );
  30833. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  30834. //
  30835. this.matrixAutoUpdate = false;
  30836. this.update();
  30837. }
  30838. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  30839. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  30840. FaceNormalsHelper.prototype.update = ( function () {
  30841. var v1 = new Vector3();
  30842. var v2 = new Vector3();
  30843. var normalMatrix = new Matrix3();
  30844. return function update() {
  30845. this.object.updateMatrixWorld( true );
  30846. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  30847. var matrixWorld = this.object.matrixWorld;
  30848. var position = this.geometry.attributes.position;
  30849. //
  30850. var objGeometry = this.object.geometry;
  30851. var vertices = objGeometry.vertices;
  30852. var faces = objGeometry.faces;
  30853. var idx = 0;
  30854. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  30855. var face = faces[ i ];
  30856. var normal = face.normal;
  30857. v1.copy( vertices[ face.a ] )
  30858. .add( vertices[ face.b ] )
  30859. .add( vertices[ face.c ] )
  30860. .divideScalar( 3 )
  30861. .applyMatrix4( matrixWorld );
  30862. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  30863. position.setXYZ( idx, v1.x, v1.y, v1.z );
  30864. idx = idx + 1;
  30865. position.setXYZ( idx, v2.x, v2.y, v2.z );
  30866. idx = idx + 1;
  30867. }
  30868. position.needsUpdate = true;
  30869. };
  30870. }() );
  30871. /**
  30872. * @author alteredq / http://alteredqualia.com/
  30873. * @author mrdoob / http://mrdoob.com/
  30874. * @author WestLangley / http://github.com/WestLangley
  30875. */
  30876. function DirectionalLightHelper( light, size, color ) {
  30877. Object3D.call( this );
  30878. this.light = light;
  30879. this.light.updateMatrixWorld();
  30880. this.matrix = light.matrixWorld;
  30881. this.matrixAutoUpdate = false;
  30882. this.color = color;
  30883. if ( size === undefined ) size = 1;
  30884. var geometry = new BufferGeometry();
  30885. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  30886. - size, size, 0,
  30887. size, size, 0,
  30888. size, - size, 0,
  30889. - size, - size, 0,
  30890. - size, size, 0
  30891. ], 3 ) );
  30892. var material = new LineBasicMaterial( { fog: false } );
  30893. this.lightPlane = new Line( geometry, material );
  30894. this.add( this.lightPlane );
  30895. geometry = new BufferGeometry();
  30896. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  30897. this.targetLine = new Line( geometry, material );
  30898. this.add( this.targetLine );
  30899. this.update();
  30900. }
  30901. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  30902. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  30903. DirectionalLightHelper.prototype.dispose = function () {
  30904. this.lightPlane.geometry.dispose();
  30905. this.lightPlane.material.dispose();
  30906. this.targetLine.geometry.dispose();
  30907. this.targetLine.material.dispose();
  30908. };
  30909. DirectionalLightHelper.prototype.update = function () {
  30910. var v1 = new Vector3();
  30911. var v2 = new Vector3();
  30912. var v3 = new Vector3();
  30913. return function update() {
  30914. v1.setFromMatrixPosition( this.light.matrixWorld );
  30915. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  30916. v3.subVectors( v2, v1 );
  30917. this.lightPlane.lookAt( v2 );
  30918. if ( this.color !== undefined ) {
  30919. this.lightPlane.material.color.set( this.color );
  30920. this.targetLine.material.color.set( this.color );
  30921. } else {
  30922. this.lightPlane.material.color.copy( this.light.color );
  30923. this.targetLine.material.color.copy( this.light.color );
  30924. }
  30925. this.targetLine.lookAt( v2 );
  30926. this.targetLine.scale.z = v3.length();
  30927. };
  30928. }();
  30929. /**
  30930. * @author alteredq / http://alteredqualia.com/
  30931. * @author Mugen87 / https://github.com/Mugen87
  30932. *
  30933. * - shows frustum, line of sight and up of the camera
  30934. * - suitable for fast updates
  30935. * - based on frustum visualization in lightgl.js shadowmap example
  30936. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  30937. */
  30938. function CameraHelper( camera ) {
  30939. var geometry = new BufferGeometry();
  30940. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  30941. var vertices = [];
  30942. var colors = [];
  30943. var pointMap = {};
  30944. // colors
  30945. var colorFrustum = new Color( 0xffaa00 );
  30946. var colorCone = new Color( 0xff0000 );
  30947. var colorUp = new Color( 0x00aaff );
  30948. var colorTarget = new Color( 0xffffff );
  30949. var colorCross = new Color( 0x333333 );
  30950. // near
  30951. addLine( 'n1', 'n2', colorFrustum );
  30952. addLine( 'n2', 'n4', colorFrustum );
  30953. addLine( 'n4', 'n3', colorFrustum );
  30954. addLine( 'n3', 'n1', colorFrustum );
  30955. // far
  30956. addLine( 'f1', 'f2', colorFrustum );
  30957. addLine( 'f2', 'f4', colorFrustum );
  30958. addLine( 'f4', 'f3', colorFrustum );
  30959. addLine( 'f3', 'f1', colorFrustum );
  30960. // sides
  30961. addLine( 'n1', 'f1', colorFrustum );
  30962. addLine( 'n2', 'f2', colorFrustum );
  30963. addLine( 'n3', 'f3', colorFrustum );
  30964. addLine( 'n4', 'f4', colorFrustum );
  30965. // cone
  30966. addLine( 'p', 'n1', colorCone );
  30967. addLine( 'p', 'n2', colorCone );
  30968. addLine( 'p', 'n3', colorCone );
  30969. addLine( 'p', 'n4', colorCone );
  30970. // up
  30971. addLine( 'u1', 'u2', colorUp );
  30972. addLine( 'u2', 'u3', colorUp );
  30973. addLine( 'u3', 'u1', colorUp );
  30974. // target
  30975. addLine( 'c', 't', colorTarget );
  30976. addLine( 'p', 'c', colorCross );
  30977. // cross
  30978. addLine( 'cn1', 'cn2', colorCross );
  30979. addLine( 'cn3', 'cn4', colorCross );
  30980. addLine( 'cf1', 'cf2', colorCross );
  30981. addLine( 'cf3', 'cf4', colorCross );
  30982. function addLine( a, b, color ) {
  30983. addPoint( a, color );
  30984. addPoint( b, color );
  30985. }
  30986. function addPoint( id, color ) {
  30987. vertices.push( 0, 0, 0 );
  30988. colors.push( color.r, color.g, color.b );
  30989. if ( pointMap[ id ] === undefined ) {
  30990. pointMap[ id ] = [];
  30991. }
  30992. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  30993. }
  30994. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30995. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30996. LineSegments.call( this, geometry, material );
  30997. this.camera = camera;
  30998. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  30999. this.matrix = camera.matrixWorld;
  31000. this.matrixAutoUpdate = false;
  31001. this.pointMap = pointMap;
  31002. this.update();
  31003. }
  31004. CameraHelper.prototype = Object.create( LineSegments.prototype );
  31005. CameraHelper.prototype.constructor = CameraHelper;
  31006. CameraHelper.prototype.update = function () {
  31007. var geometry, pointMap;
  31008. var vector = new Vector3();
  31009. var camera = new Camera();
  31010. function setPoint( point, x, y, z ) {
  31011. vector.set( x, y, z ).unproject( camera );
  31012. var points = pointMap[ point ];
  31013. if ( points !== undefined ) {
  31014. var position = geometry.getAttribute( 'position' );
  31015. for ( var i = 0, l = points.length; i < l; i ++ ) {
  31016. position.setXYZ( points[ i ], vector.x, vector.y, vector.z );
  31017. }
  31018. }
  31019. }
  31020. return function update() {
  31021. geometry = this.geometry;
  31022. pointMap = this.pointMap;
  31023. var w = 1, h = 1;
  31024. // we need just camera projection matrix
  31025. // world matrix must be identity
  31026. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  31027. // center / target
  31028. setPoint( 'c', 0, 0, - 1 );
  31029. setPoint( 't', 0, 0, 1 );
  31030. // near
  31031. setPoint( 'n1', - w, - h, - 1 );
  31032. setPoint( 'n2', w, - h, - 1 );
  31033. setPoint( 'n3', - w, h, - 1 );
  31034. setPoint( 'n4', w, h, - 1 );
  31035. // far
  31036. setPoint( 'f1', - w, - h, 1 );
  31037. setPoint( 'f2', w, - h, 1 );
  31038. setPoint( 'f3', - w, h, 1 );
  31039. setPoint( 'f4', w, h, 1 );
  31040. // up
  31041. setPoint( 'u1', w * 0.7, h * 1.1, - 1 );
  31042. setPoint( 'u2', - w * 0.7, h * 1.1, - 1 );
  31043. setPoint( 'u3', 0, h * 2, - 1 );
  31044. // cross
  31045. setPoint( 'cf1', - w, 0, 1 );
  31046. setPoint( 'cf2', w, 0, 1 );
  31047. setPoint( 'cf3', 0, - h, 1 );
  31048. setPoint( 'cf4', 0, h, 1 );
  31049. setPoint( 'cn1', - w, 0, - 1 );
  31050. setPoint( 'cn2', w, 0, - 1 );
  31051. setPoint( 'cn3', 0, - h, - 1 );
  31052. setPoint( 'cn4', 0, h, - 1 );
  31053. geometry.getAttribute( 'position' ).needsUpdate = true;
  31054. };
  31055. }();
  31056. /**
  31057. * @author mrdoob / http://mrdoob.com/
  31058. * @author Mugen87 / http://github.com/Mugen87
  31059. */
  31060. function BoxHelper( object, color ) {
  31061. this.object = object;
  31062. if ( color === undefined ) color = 0xffff00;
  31063. 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 ] );
  31064. var positions = new Float32Array( 8 * 3 );
  31065. var geometry = new BufferGeometry();
  31066. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  31067. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  31068. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  31069. this.matrixAutoUpdate = false;
  31070. this.update();
  31071. }
  31072. BoxHelper.prototype = Object.create( LineSegments.prototype );
  31073. BoxHelper.prototype.constructor = BoxHelper;
  31074. BoxHelper.prototype.update = ( function () {
  31075. var box = new Box3();
  31076. return function update( object ) {
  31077. if ( object !== undefined ) {
  31078. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  31079. }
  31080. if ( this.object !== undefined ) {
  31081. box.setFromObject( this.object );
  31082. }
  31083. if ( box.isEmpty() ) return;
  31084. var min = box.min;
  31085. var max = box.max;
  31086. /*
  31087. 5____4
  31088. 1/___0/|
  31089. | 6__|_7
  31090. 2/___3/
  31091. 0: max.x, max.y, max.z
  31092. 1: min.x, max.y, max.z
  31093. 2: min.x, min.y, max.z
  31094. 3: max.x, min.y, max.z
  31095. 4: max.x, max.y, min.z
  31096. 5: min.x, max.y, min.z
  31097. 6: min.x, min.y, min.z
  31098. 7: max.x, min.y, min.z
  31099. */
  31100. var position = this.geometry.attributes.position;
  31101. var array = position.array;
  31102. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  31103. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  31104. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  31105. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  31106. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  31107. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  31108. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  31109. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  31110. position.needsUpdate = true;
  31111. this.geometry.computeBoundingSphere();
  31112. };
  31113. } )();
  31114. BoxHelper.prototype.setFromObject = function ( object ) {
  31115. this.object = object;
  31116. this.update();
  31117. return this;
  31118. };
  31119. BoxHelper.prototype.copy = function ( source ) {
  31120. LineSegments.prototype.copy.call( this, source );
  31121. this.object = source.object;
  31122. return this;
  31123. };
  31124. BoxHelper.prototype.clone = function () {
  31125. return new this.constructor().copy( this );
  31126. };
  31127. /**
  31128. * @author WestLangley / http://github.com/WestLangley
  31129. */
  31130. function Box3Helper( box, hex ) {
  31131. this.type = 'Box3Helper';
  31132. this.box = box;
  31133. var color = ( hex !== undefined ) ? hex : 0xffff00;
  31134. 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 ] );
  31135. var positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ];
  31136. var geometry = new BufferGeometry();
  31137. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  31138. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  31139. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  31140. this.geometry.computeBoundingSphere();
  31141. }
  31142. Box3Helper.prototype = Object.create( LineSegments.prototype );
  31143. Box3Helper.prototype.constructor = Box3Helper;
  31144. Box3Helper.prototype.updateMatrixWorld = function ( force ) {
  31145. var box = this.box;
  31146. if ( box.isEmpty() ) return;
  31147. box.getCenter( this.position );
  31148. box.getSize( this.scale );
  31149. this.scale.multiplyScalar( 0.5 );
  31150. Object3D.prototype.updateMatrixWorld.call( this, force );
  31151. };
  31152. /**
  31153. * @author WestLangley / http://github.com/WestLangley
  31154. */
  31155. function PlaneHelper( plane, size, hex ) {
  31156. this.type = 'PlaneHelper';
  31157. this.plane = plane;
  31158. this.size = ( size === undefined ) ? 1 : size;
  31159. var color = ( hex !== undefined ) ? hex : 0xffff00;
  31160. var positions = [ 1, - 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0 ];
  31161. var geometry = new BufferGeometry();
  31162. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  31163. geometry.computeBoundingSphere();
  31164. Line.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  31165. //
  31166. var positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  31167. var geometry2 = new BufferGeometry();
  31168. geometry2.addAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  31169. geometry2.computeBoundingSphere();
  31170. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false } ) ) );
  31171. }
  31172. PlaneHelper.prototype = Object.create( Line.prototype );
  31173. PlaneHelper.prototype.constructor = PlaneHelper;
  31174. PlaneHelper.prototype.updateMatrixWorld = function ( force ) {
  31175. var scale = - this.plane.constant;
  31176. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  31177. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  31178. this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  31179. this.lookAt( this.plane.normal );
  31180. Object3D.prototype.updateMatrixWorld.call( this, force );
  31181. };
  31182. /**
  31183. * @author WestLangley / http://github.com/WestLangley
  31184. * @author zz85 / http://github.com/zz85
  31185. * @author bhouston / http://clara.io
  31186. *
  31187. * Creates an arrow for visualizing directions
  31188. *
  31189. * Parameters:
  31190. * dir - Vector3
  31191. * origin - Vector3
  31192. * length - Number
  31193. * color - color in hex value
  31194. * headLength - Number
  31195. * headWidth - Number
  31196. */
  31197. var lineGeometry;
  31198. var coneGeometry;
  31199. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  31200. // dir is assumed to be normalized
  31201. Object3D.call( this );
  31202. if ( dir === undefined ) dir = new THREE.Vector3( 0, 0, 1 );
  31203. if ( origin === undefined ) origin = new THREE.Vector3( 0, 0, 0 );
  31204. if ( length === undefined ) length = 1;
  31205. if ( color === undefined ) color = 0xffff00;
  31206. if ( headLength === undefined ) headLength = 0.2 * length;
  31207. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  31208. if ( lineGeometry === undefined ) {
  31209. lineGeometry = new BufferGeometry();
  31210. lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  31211. coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  31212. coneGeometry.translate( 0, - 0.5, 0 );
  31213. }
  31214. this.position.copy( origin );
  31215. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  31216. this.line.matrixAutoUpdate = false;
  31217. this.add( this.line );
  31218. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  31219. this.cone.matrixAutoUpdate = false;
  31220. this.add( this.cone );
  31221. this.setDirection( dir );
  31222. this.setLength( length, headLength, headWidth );
  31223. }
  31224. ArrowHelper.prototype = Object.create( Object3D.prototype );
  31225. ArrowHelper.prototype.constructor = ArrowHelper;
  31226. ArrowHelper.prototype.setDirection = ( function () {
  31227. var axis = new Vector3();
  31228. var radians;
  31229. return function setDirection( dir ) {
  31230. // dir is assumed to be normalized
  31231. if ( dir.y > 0.99999 ) {
  31232. this.quaternion.set( 0, 0, 0, 1 );
  31233. } else if ( dir.y < - 0.99999 ) {
  31234. this.quaternion.set( 1, 0, 0, 0 );
  31235. } else {
  31236. axis.set( dir.z, 0, - dir.x ).normalize();
  31237. radians = Math.acos( dir.y );
  31238. this.quaternion.setFromAxisAngle( axis, radians );
  31239. }
  31240. };
  31241. }() );
  31242. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  31243. if ( headLength === undefined ) headLength = 0.2 * length;
  31244. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  31245. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  31246. this.line.updateMatrix();
  31247. this.cone.scale.set( headWidth, headLength, headWidth );
  31248. this.cone.position.y = length;
  31249. this.cone.updateMatrix();
  31250. };
  31251. ArrowHelper.prototype.setColor = function ( color ) {
  31252. this.line.material.color.copy( color );
  31253. this.cone.material.color.copy( color );
  31254. };
  31255. ArrowHelper.prototype.copy = function ( source ) {
  31256. Object3D.prototype.copy.call( this, source, false );
  31257. this.line.copy( source.line );
  31258. this.cone.copy( source.cone );
  31259. return this;
  31260. };
  31261. ArrowHelper.prototype.clone = function () {
  31262. return new this.constructor().copy( this );
  31263. };
  31264. /**
  31265. * @author sroucheray / http://sroucheray.org/
  31266. * @author mrdoob / http://mrdoob.com/
  31267. */
  31268. function AxesHelper( size ) {
  31269. size = size || 1;
  31270. var vertices = [
  31271. 0, 0, 0, size, 0, 0,
  31272. 0, 0, 0, 0, size, 0,
  31273. 0, 0, 0, 0, 0, size
  31274. ];
  31275. var colors = [
  31276. 1, 0, 0, 1, 0.6, 0,
  31277. 0, 1, 0, 0.6, 1, 0,
  31278. 0, 0, 1, 0, 0.6, 1
  31279. ];
  31280. var geometry = new BufferGeometry();
  31281. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31282. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31283. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  31284. LineSegments.call( this, geometry, material );
  31285. }
  31286. AxesHelper.prototype = Object.create( LineSegments.prototype );
  31287. AxesHelper.prototype.constructor = AxesHelper;
  31288. /**
  31289. * @author mrdoob / http://mrdoob.com/
  31290. */
  31291. function Face4( a, b, c, d, normal, color, materialIndex ) {
  31292. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  31293. return new Face3( a, b, c, normal, color, materialIndex );
  31294. }
  31295. var LineStrip = 0;
  31296. var LinePieces = 1;
  31297. function MeshFaceMaterial( materials ) {
  31298. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  31299. return materials;
  31300. }
  31301. function MultiMaterial( materials ) {
  31302. if ( materials === undefined ) materials = [];
  31303. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  31304. materials.isMultiMaterial = true;
  31305. materials.materials = materials;
  31306. materials.clone = function () {
  31307. return materials.slice();
  31308. };
  31309. return materials;
  31310. }
  31311. function PointCloud( geometry, material ) {
  31312. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  31313. return new Points( geometry, material );
  31314. }
  31315. function Particle( material ) {
  31316. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  31317. return new Sprite( material );
  31318. }
  31319. function ParticleSystem( geometry, material ) {
  31320. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  31321. return new Points( geometry, material );
  31322. }
  31323. function PointCloudMaterial( parameters ) {
  31324. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  31325. return new PointsMaterial( parameters );
  31326. }
  31327. function ParticleBasicMaterial( parameters ) {
  31328. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  31329. return new PointsMaterial( parameters );
  31330. }
  31331. function ParticleSystemMaterial( parameters ) {
  31332. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  31333. return new PointsMaterial( parameters );
  31334. }
  31335. function Vertex( x, y, z ) {
  31336. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  31337. return new Vector3( x, y, z );
  31338. }
  31339. //
  31340. function DynamicBufferAttribute( array, itemSize ) {
  31341. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  31342. return new BufferAttribute( array, itemSize ).setDynamic( true );
  31343. }
  31344. function Int8Attribute( array, itemSize ) {
  31345. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  31346. return new Int8BufferAttribute( array, itemSize );
  31347. }
  31348. function Uint8Attribute( array, itemSize ) {
  31349. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  31350. return new Uint8BufferAttribute( array, itemSize );
  31351. }
  31352. function Uint8ClampedAttribute( array, itemSize ) {
  31353. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  31354. return new Uint8ClampedBufferAttribute( array, itemSize );
  31355. }
  31356. function Int16Attribute( array, itemSize ) {
  31357. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  31358. return new Int16BufferAttribute( array, itemSize );
  31359. }
  31360. function Uint16Attribute( array, itemSize ) {
  31361. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  31362. return new Uint16BufferAttribute( array, itemSize );
  31363. }
  31364. function Int32Attribute( array, itemSize ) {
  31365. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  31366. return new Int32BufferAttribute( array, itemSize );
  31367. }
  31368. function Uint32Attribute( array, itemSize ) {
  31369. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  31370. return new Uint32BufferAttribute( array, itemSize );
  31371. }
  31372. function Float32Attribute( array, itemSize ) {
  31373. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  31374. return new Float32BufferAttribute( array, itemSize );
  31375. }
  31376. function Float64Attribute( array, itemSize ) {
  31377. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  31378. return new Float64BufferAttribute( array, itemSize );
  31379. }
  31380. //
  31381. Curve.create = function ( construct, getPoint ) {
  31382. console.log( 'THREE.Curve.create() has been deprecated' );
  31383. construct.prototype = Object.create( Curve.prototype );
  31384. construct.prototype.constructor = construct;
  31385. construct.prototype.getPoint = getPoint;
  31386. return construct;
  31387. };
  31388. //
  31389. Object.assign( CurvePath.prototype, {
  31390. createPointsGeometry: function ( divisions ) {
  31391. console.warn( 'THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  31392. // generate geometry from path points (for Line or Points objects)
  31393. var pts = this.getPoints( divisions );
  31394. return this.createGeometry( pts );
  31395. },
  31396. createSpacedPointsGeometry: function ( divisions ) {
  31397. console.warn( 'THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  31398. // generate geometry from equidistant sampling along the path
  31399. var pts = this.getSpacedPoints( divisions );
  31400. return this.createGeometry( pts );
  31401. },
  31402. createGeometry: function ( points ) {
  31403. console.warn( 'THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  31404. var geometry = new Geometry();
  31405. for ( var i = 0, l = points.length; i < l; i ++ ) {
  31406. var point = points[ i ];
  31407. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  31408. }
  31409. return geometry;
  31410. }
  31411. } );
  31412. //
  31413. Object.assign( Path.prototype, {
  31414. fromPoints: function ( points ) {
  31415. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  31416. this.setFromPoints( points );
  31417. }
  31418. } );
  31419. //
  31420. function ClosedSplineCurve3( points ) {
  31421. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  31422. CatmullRomCurve3.call( this, points );
  31423. this.type = 'catmullrom';
  31424. this.closed = true;
  31425. }
  31426. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  31427. //
  31428. function SplineCurve3( points ) {
  31429. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  31430. CatmullRomCurve3.call( this, points );
  31431. this.type = 'catmullrom';
  31432. }
  31433. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  31434. //
  31435. function Spline( points ) {
  31436. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  31437. CatmullRomCurve3.call( this, points );
  31438. this.type = 'catmullrom';
  31439. }
  31440. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  31441. Object.assign( Spline.prototype, {
  31442. initFromArray: function ( /* a */ ) {
  31443. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  31444. },
  31445. getControlPointsArray: function ( /* optionalTarget */ ) {
  31446. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  31447. },
  31448. reparametrizeByArcLength: function ( /* samplingCoef */ ) {
  31449. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  31450. }
  31451. } );
  31452. //
  31453. function AxisHelper( size ) {
  31454. console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
  31455. return new AxesHelper( size );
  31456. }
  31457. function BoundingBoxHelper( object, color ) {
  31458. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  31459. return new BoxHelper( object, color );
  31460. }
  31461. function EdgesHelper( object, hex ) {
  31462. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  31463. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  31464. }
  31465. GridHelper.prototype.setColors = function () {
  31466. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  31467. };
  31468. SkeletonHelper.prototype.update = function () {
  31469. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  31470. };
  31471. function WireframeHelper( object, hex ) {
  31472. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  31473. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  31474. }
  31475. //
  31476. Object.assign( Loader.prototype, {
  31477. extractUrlBase: function ( url ) {
  31478. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  31479. return LoaderUtils.extractUrlBase( url );
  31480. }
  31481. } );
  31482. function XHRLoader( manager ) {
  31483. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  31484. return new FileLoader( manager );
  31485. }
  31486. function BinaryTextureLoader( manager ) {
  31487. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  31488. return new DataTextureLoader( manager );
  31489. }
  31490. Object.assign( JSONLoader.prototype, {
  31491. setTexturePath: function ( value ) {
  31492. console.warn( 'THREE.JSONLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  31493. return this.setResourcePath( value );
  31494. }
  31495. } );
  31496. Object.assign( ObjectLoader.prototype, {
  31497. setTexturePath: function ( value ) {
  31498. console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  31499. return this.setResourcePath( value );
  31500. }
  31501. } );
  31502. //
  31503. Object.assign( Box2.prototype, {
  31504. center: function ( optionalTarget ) {
  31505. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  31506. return this.getCenter( optionalTarget );
  31507. },
  31508. empty: function () {
  31509. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  31510. return this.isEmpty();
  31511. },
  31512. isIntersectionBox: function ( box ) {
  31513. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  31514. return this.intersectsBox( box );
  31515. },
  31516. size: function ( optionalTarget ) {
  31517. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  31518. return this.getSize( optionalTarget );
  31519. }
  31520. } );
  31521. Object.assign( Box3.prototype, {
  31522. center: function ( optionalTarget ) {
  31523. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  31524. return this.getCenter( optionalTarget );
  31525. },
  31526. empty: function () {
  31527. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  31528. return this.isEmpty();
  31529. },
  31530. isIntersectionBox: function ( box ) {
  31531. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  31532. return this.intersectsBox( box );
  31533. },
  31534. isIntersectionSphere: function ( sphere ) {
  31535. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  31536. return this.intersectsSphere( sphere );
  31537. },
  31538. size: function ( optionalTarget ) {
  31539. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  31540. return this.getSize( optionalTarget );
  31541. }
  31542. } );
  31543. Line3.prototype.center = function ( optionalTarget ) {
  31544. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  31545. return this.getCenter( optionalTarget );
  31546. };
  31547. Object.assign( _Math, {
  31548. random16: function () {
  31549. console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' );
  31550. return Math.random();
  31551. },
  31552. nearestPowerOfTwo: function ( value ) {
  31553. console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' );
  31554. return _Math.floorPowerOfTwo( value );
  31555. },
  31556. nextPowerOfTwo: function ( value ) {
  31557. console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' );
  31558. return _Math.ceilPowerOfTwo( value );
  31559. }
  31560. } );
  31561. Object.assign( Matrix3.prototype, {
  31562. flattenToArrayOffset: function ( array, offset ) {
  31563. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  31564. return this.toArray( array, offset );
  31565. },
  31566. multiplyVector3: function ( vector ) {
  31567. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  31568. return vector.applyMatrix3( this );
  31569. },
  31570. multiplyVector3Array: function ( /* a */ ) {
  31571. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  31572. },
  31573. applyToBuffer: function ( buffer /*, offset, length */ ) {
  31574. console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  31575. return this.applyToBufferAttribute( buffer );
  31576. },
  31577. applyToVector3Array: function ( /* array, offset, length */ ) {
  31578. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  31579. }
  31580. } );
  31581. Object.assign( Matrix4.prototype, {
  31582. extractPosition: function ( m ) {
  31583. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  31584. return this.copyPosition( m );
  31585. },
  31586. flattenToArrayOffset: function ( array, offset ) {
  31587. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  31588. return this.toArray( array, offset );
  31589. },
  31590. getPosition: function () {
  31591. var v1;
  31592. return function getPosition() {
  31593. if ( v1 === undefined ) v1 = new Vector3();
  31594. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  31595. return v1.setFromMatrixColumn( this, 3 );
  31596. };
  31597. }(),
  31598. setRotationFromQuaternion: function ( q ) {
  31599. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  31600. return this.makeRotationFromQuaternion( q );
  31601. },
  31602. multiplyToArray: function () {
  31603. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  31604. },
  31605. multiplyVector3: function ( vector ) {
  31606. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  31607. return vector.applyMatrix4( this );
  31608. },
  31609. multiplyVector4: function ( vector ) {
  31610. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  31611. return vector.applyMatrix4( this );
  31612. },
  31613. multiplyVector3Array: function ( /* a */ ) {
  31614. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  31615. },
  31616. rotateAxis: function ( v ) {
  31617. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  31618. v.transformDirection( this );
  31619. },
  31620. crossVector: function ( vector ) {
  31621. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  31622. return vector.applyMatrix4( this );
  31623. },
  31624. translate: function () {
  31625. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  31626. },
  31627. rotateX: function () {
  31628. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  31629. },
  31630. rotateY: function () {
  31631. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  31632. },
  31633. rotateZ: function () {
  31634. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  31635. },
  31636. rotateByAxis: function () {
  31637. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  31638. },
  31639. applyToBuffer: function ( buffer /*, offset, length */ ) {
  31640. console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  31641. return this.applyToBufferAttribute( buffer );
  31642. },
  31643. applyToVector3Array: function ( /* array, offset, length */ ) {
  31644. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  31645. },
  31646. makeFrustum: function ( left, right, bottom, top, near, far ) {
  31647. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  31648. return this.makePerspective( left, right, top, bottom, near, far );
  31649. }
  31650. } );
  31651. Plane.prototype.isIntersectionLine = function ( line ) {
  31652. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  31653. return this.intersectsLine( line );
  31654. };
  31655. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  31656. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  31657. return vector.applyQuaternion( this );
  31658. };
  31659. Object.assign( Ray.prototype, {
  31660. isIntersectionBox: function ( box ) {
  31661. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  31662. return this.intersectsBox( box );
  31663. },
  31664. isIntersectionPlane: function ( plane ) {
  31665. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  31666. return this.intersectsPlane( plane );
  31667. },
  31668. isIntersectionSphere: function ( sphere ) {
  31669. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  31670. return this.intersectsSphere( sphere );
  31671. }
  31672. } );
  31673. Object.assign( Triangle.prototype, {
  31674. area: function () {
  31675. console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
  31676. return this.getArea();
  31677. },
  31678. barycoordFromPoint: function ( point, target ) {
  31679. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  31680. return this.getBarycoord( point, target );
  31681. },
  31682. midpoint: function ( target ) {
  31683. console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
  31684. return this.getMidpoint( target );
  31685. },
  31686. normal: function ( target ) {
  31687. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  31688. return this.getNormal( target );
  31689. },
  31690. plane: function ( target ) {
  31691. console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
  31692. return this.getPlane( target );
  31693. }
  31694. } );
  31695. Object.assign( Triangle, {
  31696. barycoordFromPoint: function ( point, a, b, c, target ) {
  31697. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  31698. return Triangle.getBarycoord( point, a, b, c, target );
  31699. },
  31700. normal: function ( a, b, c, target ) {
  31701. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  31702. return Triangle.getNormal( a, b, c, target );
  31703. }
  31704. } );
  31705. Object.assign( Shape.prototype, {
  31706. extractAllPoints: function ( divisions ) {
  31707. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  31708. return this.extractPoints( divisions );
  31709. },
  31710. extrude: function ( options ) {
  31711. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  31712. return new ExtrudeGeometry( this, options );
  31713. },
  31714. makeGeometry: function ( options ) {
  31715. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  31716. return new ShapeGeometry( this, options );
  31717. }
  31718. } );
  31719. Object.assign( Vector2.prototype, {
  31720. fromAttribute: function ( attribute, index, offset ) {
  31721. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  31722. return this.fromBufferAttribute( attribute, index, offset );
  31723. },
  31724. distanceToManhattan: function ( v ) {
  31725. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  31726. return this.manhattanDistanceTo( v );
  31727. },
  31728. lengthManhattan: function () {
  31729. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  31730. return this.manhattanLength();
  31731. }
  31732. } );
  31733. Object.assign( Vector3.prototype, {
  31734. setEulerFromRotationMatrix: function () {
  31735. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  31736. },
  31737. setEulerFromQuaternion: function () {
  31738. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  31739. },
  31740. getPositionFromMatrix: function ( m ) {
  31741. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  31742. return this.setFromMatrixPosition( m );
  31743. },
  31744. getScaleFromMatrix: function ( m ) {
  31745. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  31746. return this.setFromMatrixScale( m );
  31747. },
  31748. getColumnFromMatrix: function ( index, matrix ) {
  31749. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  31750. return this.setFromMatrixColumn( matrix, index );
  31751. },
  31752. applyProjection: function ( m ) {
  31753. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  31754. return this.applyMatrix4( m );
  31755. },
  31756. fromAttribute: function ( attribute, index, offset ) {
  31757. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  31758. return this.fromBufferAttribute( attribute, index, offset );
  31759. },
  31760. distanceToManhattan: function ( v ) {
  31761. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  31762. return this.manhattanDistanceTo( v );
  31763. },
  31764. lengthManhattan: function () {
  31765. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  31766. return this.manhattanLength();
  31767. }
  31768. } );
  31769. Object.assign( Vector4.prototype, {
  31770. fromAttribute: function ( attribute, index, offset ) {
  31771. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  31772. return this.fromBufferAttribute( attribute, index, offset );
  31773. },
  31774. lengthManhattan: function () {
  31775. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  31776. return this.manhattanLength();
  31777. }
  31778. } );
  31779. //
  31780. Object.assign( Geometry.prototype, {
  31781. computeTangents: function () {
  31782. console.error( 'THREE.Geometry: .computeTangents() has been removed.' );
  31783. },
  31784. computeLineDistances: function () {
  31785. console.error( 'THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.' );
  31786. }
  31787. } );
  31788. Object.assign( Object3D.prototype, {
  31789. getChildByName: function ( name ) {
  31790. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  31791. return this.getObjectByName( name );
  31792. },
  31793. renderDepth: function () {
  31794. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  31795. },
  31796. translate: function ( distance, axis ) {
  31797. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  31798. return this.translateOnAxis( axis, distance );
  31799. },
  31800. getWorldRotation: function () {
  31801. console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
  31802. }
  31803. } );
  31804. Object.defineProperties( Object3D.prototype, {
  31805. eulerOrder: {
  31806. get: function () {
  31807. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  31808. return this.rotation.order;
  31809. },
  31810. set: function ( value ) {
  31811. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  31812. this.rotation.order = value;
  31813. }
  31814. },
  31815. useQuaternion: {
  31816. get: function () {
  31817. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  31818. },
  31819. set: function () {
  31820. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  31821. }
  31822. }
  31823. } );
  31824. Object.defineProperties( LOD.prototype, {
  31825. objects: {
  31826. get: function () {
  31827. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  31828. return this.levels;
  31829. }
  31830. }
  31831. } );
  31832. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  31833. get: function () {
  31834. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  31835. },
  31836. set: function () {
  31837. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  31838. }
  31839. } );
  31840. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  31841. get: function () {
  31842. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  31843. return this.arcLengthDivisions;
  31844. },
  31845. set: function ( value ) {
  31846. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  31847. this.arcLengthDivisions = value;
  31848. }
  31849. } );
  31850. //
  31851. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  31852. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  31853. "Use .setFocalLength and .filmGauge for a photographic setup." );
  31854. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  31855. this.setFocalLength( focalLength );
  31856. };
  31857. //
  31858. Object.defineProperties( Light.prototype, {
  31859. onlyShadow: {
  31860. set: function () {
  31861. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  31862. }
  31863. },
  31864. shadowCameraFov: {
  31865. set: function ( value ) {
  31866. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  31867. this.shadow.camera.fov = value;
  31868. }
  31869. },
  31870. shadowCameraLeft: {
  31871. set: function ( value ) {
  31872. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  31873. this.shadow.camera.left = value;
  31874. }
  31875. },
  31876. shadowCameraRight: {
  31877. set: function ( value ) {
  31878. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  31879. this.shadow.camera.right = value;
  31880. }
  31881. },
  31882. shadowCameraTop: {
  31883. set: function ( value ) {
  31884. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  31885. this.shadow.camera.top = value;
  31886. }
  31887. },
  31888. shadowCameraBottom: {
  31889. set: function ( value ) {
  31890. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  31891. this.shadow.camera.bottom = value;
  31892. }
  31893. },
  31894. shadowCameraNear: {
  31895. set: function ( value ) {
  31896. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  31897. this.shadow.camera.near = value;
  31898. }
  31899. },
  31900. shadowCameraFar: {
  31901. set: function ( value ) {
  31902. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  31903. this.shadow.camera.far = value;
  31904. }
  31905. },
  31906. shadowCameraVisible: {
  31907. set: function () {
  31908. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  31909. }
  31910. },
  31911. shadowBias: {
  31912. set: function ( value ) {
  31913. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  31914. this.shadow.bias = value;
  31915. }
  31916. },
  31917. shadowDarkness: {
  31918. set: function () {
  31919. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  31920. }
  31921. },
  31922. shadowMapWidth: {
  31923. set: function ( value ) {
  31924. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  31925. this.shadow.mapSize.width = value;
  31926. }
  31927. },
  31928. shadowMapHeight: {
  31929. set: function ( value ) {
  31930. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  31931. this.shadow.mapSize.height = value;
  31932. }
  31933. }
  31934. } );
  31935. //
  31936. Object.defineProperties( BufferAttribute.prototype, {
  31937. length: {
  31938. get: function () {
  31939. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  31940. return this.array.length;
  31941. }
  31942. },
  31943. copyIndicesArray: function ( /* indices */ ) {
  31944. console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
  31945. }
  31946. } );
  31947. Object.assign( BufferGeometry.prototype, {
  31948. addIndex: function ( index ) {
  31949. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  31950. this.setIndex( index );
  31951. },
  31952. addDrawCall: function ( start, count, indexOffset ) {
  31953. if ( indexOffset !== undefined ) {
  31954. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  31955. }
  31956. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  31957. this.addGroup( start, count );
  31958. },
  31959. clearDrawCalls: function () {
  31960. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  31961. this.clearGroups();
  31962. },
  31963. computeTangents: function () {
  31964. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  31965. },
  31966. computeOffsets: function () {
  31967. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  31968. }
  31969. } );
  31970. Object.defineProperties( BufferGeometry.prototype, {
  31971. drawcalls: {
  31972. get: function () {
  31973. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  31974. return this.groups;
  31975. }
  31976. },
  31977. offsets: {
  31978. get: function () {
  31979. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  31980. return this.groups;
  31981. }
  31982. }
  31983. } );
  31984. //
  31985. Object.assign( ExtrudeBufferGeometry.prototype, {
  31986. getArrays: function () {
  31987. console.error( 'THREE.ExtrudeBufferGeometry: .getArrays() has been removed.' );
  31988. },
  31989. addShapeList: function () {
  31990. console.error( 'THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.' );
  31991. },
  31992. addShape: function () {
  31993. console.error( 'THREE.ExtrudeBufferGeometry: .addShape() has been removed.' );
  31994. }
  31995. } );
  31996. //
  31997. Object.defineProperties( Uniform.prototype, {
  31998. dynamic: {
  31999. set: function () {
  32000. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  32001. }
  32002. },
  32003. onUpdate: {
  32004. value: function () {
  32005. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  32006. return this;
  32007. }
  32008. }
  32009. } );
  32010. //
  32011. Object.defineProperties( Material.prototype, {
  32012. wrapAround: {
  32013. get: function () {
  32014. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  32015. },
  32016. set: function () {
  32017. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  32018. }
  32019. },
  32020. overdraw: {
  32021. get: function () {
  32022. console.warn( 'THREE.Material: .overdraw has been removed.' );
  32023. },
  32024. set: function () {
  32025. console.warn( 'THREE.Material: .overdraw has been removed.' );
  32026. }
  32027. },
  32028. wrapRGB: {
  32029. get: function () {
  32030. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  32031. return new Color();
  32032. }
  32033. },
  32034. shading: {
  32035. get: function () {
  32036. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  32037. },
  32038. set: function ( value ) {
  32039. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  32040. this.flatShading = ( value === FlatShading );
  32041. }
  32042. }
  32043. } );
  32044. Object.defineProperties( MeshPhongMaterial.prototype, {
  32045. metal: {
  32046. get: function () {
  32047. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  32048. return false;
  32049. },
  32050. set: function () {
  32051. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  32052. }
  32053. }
  32054. } );
  32055. Object.defineProperties( ShaderMaterial.prototype, {
  32056. derivatives: {
  32057. get: function () {
  32058. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  32059. return this.extensions.derivatives;
  32060. },
  32061. set: function ( value ) {
  32062. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  32063. this.extensions.derivatives = value;
  32064. }
  32065. }
  32066. } );
  32067. //
  32068. Object.assign( WebGLRenderer.prototype, {
  32069. clearTarget: function ( renderTarget, color, depth, stencil ) {
  32070. console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
  32071. this.setRenderTarget( renderTarget );
  32072. this.clear( color, depth, stencil );
  32073. },
  32074. animate: function ( callback ) {
  32075. console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
  32076. this.setAnimationLoop( callback );
  32077. },
  32078. getCurrentRenderTarget: function () {
  32079. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  32080. return this.getRenderTarget();
  32081. },
  32082. getMaxAnisotropy: function () {
  32083. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  32084. return this.capabilities.getMaxAnisotropy();
  32085. },
  32086. getPrecision: function () {
  32087. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  32088. return this.capabilities.precision;
  32089. },
  32090. resetGLState: function () {
  32091. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  32092. return this.state.reset();
  32093. },
  32094. supportsFloatTextures: function () {
  32095. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  32096. return this.extensions.get( 'OES_texture_float' );
  32097. },
  32098. supportsHalfFloatTextures: function () {
  32099. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  32100. return this.extensions.get( 'OES_texture_half_float' );
  32101. },
  32102. supportsStandardDerivatives: function () {
  32103. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  32104. return this.extensions.get( 'OES_standard_derivatives' );
  32105. },
  32106. supportsCompressedTextureS3TC: function () {
  32107. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  32108. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  32109. },
  32110. supportsCompressedTexturePVRTC: function () {
  32111. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  32112. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  32113. },
  32114. supportsBlendMinMax: function () {
  32115. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  32116. return this.extensions.get( 'EXT_blend_minmax' );
  32117. },
  32118. supportsVertexTextures: function () {
  32119. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  32120. return this.capabilities.vertexTextures;
  32121. },
  32122. supportsInstancedArrays: function () {
  32123. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  32124. return this.extensions.get( 'ANGLE_instanced_arrays' );
  32125. },
  32126. enableScissorTest: function ( boolean ) {
  32127. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  32128. this.setScissorTest( boolean );
  32129. },
  32130. initMaterial: function () {
  32131. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  32132. },
  32133. addPrePlugin: function () {
  32134. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  32135. },
  32136. addPostPlugin: function () {
  32137. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  32138. },
  32139. updateShadowMap: function () {
  32140. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  32141. },
  32142. setFaceCulling: function () {
  32143. console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
  32144. }
  32145. } );
  32146. Object.defineProperties( WebGLRenderer.prototype, {
  32147. shadowMapEnabled: {
  32148. get: function () {
  32149. return this.shadowMap.enabled;
  32150. },
  32151. set: function ( value ) {
  32152. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  32153. this.shadowMap.enabled = value;
  32154. }
  32155. },
  32156. shadowMapType: {
  32157. get: function () {
  32158. return this.shadowMap.type;
  32159. },
  32160. set: function ( value ) {
  32161. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  32162. this.shadowMap.type = value;
  32163. }
  32164. },
  32165. shadowMapCullFace: {
  32166. get: function () {
  32167. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  32168. return undefined;
  32169. },
  32170. set: function ( /* value */ ) {
  32171. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  32172. }
  32173. }
  32174. } );
  32175. Object.defineProperties( WebGLShadowMap.prototype, {
  32176. cullFace: {
  32177. get: function () {
  32178. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  32179. return undefined;
  32180. },
  32181. set: function ( /* cullFace */ ) {
  32182. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  32183. }
  32184. },
  32185. renderReverseSided: {
  32186. get: function () {
  32187. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  32188. return undefined;
  32189. },
  32190. set: function () {
  32191. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  32192. }
  32193. },
  32194. renderSingleSided: {
  32195. get: function () {
  32196. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  32197. return undefined;
  32198. },
  32199. set: function () {
  32200. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  32201. }
  32202. }
  32203. } );
  32204. //
  32205. Object.defineProperties( WebGLRenderTarget.prototype, {
  32206. wrapS: {
  32207. get: function () {
  32208. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  32209. return this.texture.wrapS;
  32210. },
  32211. set: function ( value ) {
  32212. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  32213. this.texture.wrapS = value;
  32214. }
  32215. },
  32216. wrapT: {
  32217. get: function () {
  32218. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  32219. return this.texture.wrapT;
  32220. },
  32221. set: function ( value ) {
  32222. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  32223. this.texture.wrapT = value;
  32224. }
  32225. },
  32226. magFilter: {
  32227. get: function () {
  32228. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  32229. return this.texture.magFilter;
  32230. },
  32231. set: function ( value ) {
  32232. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  32233. this.texture.magFilter = value;
  32234. }
  32235. },
  32236. minFilter: {
  32237. get: function () {
  32238. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  32239. return this.texture.minFilter;
  32240. },
  32241. set: function ( value ) {
  32242. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  32243. this.texture.minFilter = value;
  32244. }
  32245. },
  32246. anisotropy: {
  32247. get: function () {
  32248. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  32249. return this.texture.anisotropy;
  32250. },
  32251. set: function ( value ) {
  32252. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  32253. this.texture.anisotropy = value;
  32254. }
  32255. },
  32256. offset: {
  32257. get: function () {
  32258. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  32259. return this.texture.offset;
  32260. },
  32261. set: function ( value ) {
  32262. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  32263. this.texture.offset = value;
  32264. }
  32265. },
  32266. repeat: {
  32267. get: function () {
  32268. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  32269. return this.texture.repeat;
  32270. },
  32271. set: function ( value ) {
  32272. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  32273. this.texture.repeat = value;
  32274. }
  32275. },
  32276. format: {
  32277. get: function () {
  32278. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  32279. return this.texture.format;
  32280. },
  32281. set: function ( value ) {
  32282. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  32283. this.texture.format = value;
  32284. }
  32285. },
  32286. type: {
  32287. get: function () {
  32288. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  32289. return this.texture.type;
  32290. },
  32291. set: function ( value ) {
  32292. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  32293. this.texture.type = value;
  32294. }
  32295. },
  32296. generateMipmaps: {
  32297. get: function () {
  32298. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  32299. return this.texture.generateMipmaps;
  32300. },
  32301. set: function ( value ) {
  32302. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  32303. this.texture.generateMipmaps = value;
  32304. }
  32305. }
  32306. } );
  32307. //
  32308. Object.defineProperties( WebVRManager.prototype, {
  32309. standing: {
  32310. set: function ( /* value */ ) {
  32311. console.warn( 'THREE.WebVRManager: .standing has been removed.' );
  32312. }
  32313. },
  32314. userHeight: {
  32315. set: function ( /* value */ ) {
  32316. console.warn( 'THREE.WebVRManager: .userHeight has been removed.' );
  32317. }
  32318. }
  32319. } );
  32320. //
  32321. Audio.prototype.load = function ( file ) {
  32322. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  32323. var scope = this;
  32324. var audioLoader = new AudioLoader();
  32325. audioLoader.load( file, function ( buffer ) {
  32326. scope.setBuffer( buffer );
  32327. } );
  32328. return this;
  32329. };
  32330. AudioAnalyser.prototype.getData = function () {
  32331. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  32332. return this.getFrequencyData();
  32333. };
  32334. //
  32335. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  32336. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  32337. return this.update( renderer, scene );
  32338. };
  32339. //
  32340. var GeometryUtils = {
  32341. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  32342. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  32343. var matrix;
  32344. if ( geometry2.isMesh ) {
  32345. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  32346. matrix = geometry2.matrix;
  32347. geometry2 = geometry2.geometry;
  32348. }
  32349. geometry1.merge( geometry2, matrix, materialIndexOffset );
  32350. },
  32351. center: function ( geometry ) {
  32352. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  32353. return geometry.center();
  32354. }
  32355. };
  32356. ImageUtils.crossOrigin = undefined;
  32357. ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {
  32358. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  32359. var loader = new TextureLoader();
  32360. loader.setCrossOrigin( this.crossOrigin );
  32361. var texture = loader.load( url, onLoad, undefined, onError );
  32362. if ( mapping ) texture.mapping = mapping;
  32363. return texture;
  32364. };
  32365. ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {
  32366. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  32367. var loader = new CubeTextureLoader();
  32368. loader.setCrossOrigin( this.crossOrigin );
  32369. var texture = loader.load( urls, onLoad, undefined, onError );
  32370. if ( mapping ) texture.mapping = mapping;
  32371. return texture;
  32372. };
  32373. ImageUtils.loadCompressedTexture = function () {
  32374. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  32375. };
  32376. ImageUtils.loadCompressedTextureCube = function () {
  32377. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  32378. };
  32379. //
  32380. function Projector() {
  32381. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  32382. this.projectVector = function ( vector, camera ) {
  32383. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  32384. vector.project( camera );
  32385. };
  32386. this.unprojectVector = function ( vector, camera ) {
  32387. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  32388. vector.unproject( camera );
  32389. };
  32390. this.pickingRay = function () {
  32391. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  32392. };
  32393. }
  32394. //
  32395. function CanvasRenderer() {
  32396. console.error( 'THREE.CanvasRenderer has been removed' );
  32397. }
  32398. //
  32399. var SceneUtils = {
  32400. createMultiMaterialObject: function ( /* geometry, materials */ ) {
  32401. console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' );
  32402. },
  32403. detach: function ( /* child, parent, scene */ ) {
  32404. console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' );
  32405. },
  32406. attach: function ( /* child, scene, parent */ ) {
  32407. console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' );
  32408. }
  32409. };
  32410. //
  32411. function LensFlare() {
  32412. console.error( 'THREE.LensFlare has been moved to /examples/js/objects/Lensflare.js' );
  32413. }
  32414. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  32415. exports.WebGLRenderTarget = WebGLRenderTarget;
  32416. exports.WebGLRenderer = WebGLRenderer;
  32417. exports.ShaderLib = ShaderLib;
  32418. exports.UniformsLib = UniformsLib;
  32419. exports.UniformsUtils = UniformsUtils;
  32420. exports.ShaderChunk = ShaderChunk;
  32421. exports.FogExp2 = FogExp2;
  32422. exports.Fog = Fog;
  32423. exports.Scene = Scene;
  32424. exports.Sprite = Sprite;
  32425. exports.LOD = LOD;
  32426. exports.SkinnedMesh = SkinnedMesh;
  32427. exports.Skeleton = Skeleton;
  32428. exports.Bone = Bone;
  32429. exports.Mesh = Mesh;
  32430. exports.LineSegments = LineSegments;
  32431. exports.LineLoop = LineLoop;
  32432. exports.Line = Line;
  32433. exports.Points = Points;
  32434. exports.Group = Group;
  32435. exports.VideoTexture = VideoTexture;
  32436. exports.DataTexture = DataTexture;
  32437. exports.DataTexture3D = DataTexture3D;
  32438. exports.CompressedTexture = CompressedTexture;
  32439. exports.CubeTexture = CubeTexture;
  32440. exports.CanvasTexture = CanvasTexture;
  32441. exports.DepthTexture = DepthTexture;
  32442. exports.Texture = Texture;
  32443. exports.AnimationLoader = AnimationLoader;
  32444. exports.CompressedTextureLoader = CompressedTextureLoader;
  32445. exports.DataTextureLoader = DataTextureLoader;
  32446. exports.CubeTextureLoader = CubeTextureLoader;
  32447. exports.TextureLoader = TextureLoader;
  32448. exports.ObjectLoader = ObjectLoader;
  32449. exports.MaterialLoader = MaterialLoader;
  32450. exports.BufferGeometryLoader = BufferGeometryLoader;
  32451. exports.DefaultLoadingManager = DefaultLoadingManager;
  32452. exports.LoadingManager = LoadingManager;
  32453. exports.JSONLoader = JSONLoader;
  32454. exports.ImageLoader = ImageLoader;
  32455. exports.ImageBitmapLoader = ImageBitmapLoader;
  32456. exports.FontLoader = FontLoader;
  32457. exports.FileLoader = FileLoader;
  32458. exports.Loader = Loader;
  32459. exports.LoaderUtils = LoaderUtils;
  32460. exports.Cache = Cache;
  32461. exports.AudioLoader = AudioLoader;
  32462. exports.SpotLightShadow = SpotLightShadow;
  32463. exports.SpotLight = SpotLight;
  32464. exports.PointLight = PointLight;
  32465. exports.RectAreaLight = RectAreaLight;
  32466. exports.HemisphereLight = HemisphereLight;
  32467. exports.DirectionalLightShadow = DirectionalLightShadow;
  32468. exports.DirectionalLight = DirectionalLight;
  32469. exports.AmbientLight = AmbientLight;
  32470. exports.LightShadow = LightShadow;
  32471. exports.Light = Light;
  32472. exports.StereoCamera = StereoCamera;
  32473. exports.PerspectiveCamera = PerspectiveCamera;
  32474. exports.OrthographicCamera = OrthographicCamera;
  32475. exports.CubeCamera = CubeCamera;
  32476. exports.ArrayCamera = ArrayCamera;
  32477. exports.Camera = Camera;
  32478. exports.AudioListener = AudioListener;
  32479. exports.PositionalAudio = PositionalAudio;
  32480. exports.AudioContext = AudioContext;
  32481. exports.AudioAnalyser = AudioAnalyser;
  32482. exports.Audio = Audio;
  32483. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  32484. exports.StringKeyframeTrack = StringKeyframeTrack;
  32485. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  32486. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  32487. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  32488. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  32489. exports.PropertyMixer = PropertyMixer;
  32490. exports.PropertyBinding = PropertyBinding;
  32491. exports.KeyframeTrack = KeyframeTrack;
  32492. exports.AnimationUtils = AnimationUtils;
  32493. exports.AnimationObjectGroup = AnimationObjectGroup;
  32494. exports.AnimationMixer = AnimationMixer;
  32495. exports.AnimationClip = AnimationClip;
  32496. exports.Uniform = Uniform;
  32497. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  32498. exports.BufferGeometry = BufferGeometry;
  32499. exports.Geometry = Geometry;
  32500. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  32501. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  32502. exports.InterleavedBuffer = InterleavedBuffer;
  32503. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  32504. exports.Face3 = Face3;
  32505. exports.Object3D = Object3D;
  32506. exports.Raycaster = Raycaster;
  32507. exports.Layers = Layers;
  32508. exports.EventDispatcher = EventDispatcher;
  32509. exports.Clock = Clock;
  32510. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  32511. exports.LinearInterpolant = LinearInterpolant;
  32512. exports.DiscreteInterpolant = DiscreteInterpolant;
  32513. exports.CubicInterpolant = CubicInterpolant;
  32514. exports.Interpolant = Interpolant;
  32515. exports.Triangle = Triangle;
  32516. exports.Math = _Math;
  32517. exports.Spherical = Spherical;
  32518. exports.Cylindrical = Cylindrical;
  32519. exports.Plane = Plane;
  32520. exports.Frustum = Frustum;
  32521. exports.Sphere = Sphere;
  32522. exports.Ray = Ray;
  32523. exports.Matrix4 = Matrix4;
  32524. exports.Matrix3 = Matrix3;
  32525. exports.Box3 = Box3;
  32526. exports.Box2 = Box2;
  32527. exports.Line3 = Line3;
  32528. exports.Euler = Euler;
  32529. exports.Vector4 = Vector4;
  32530. exports.Vector3 = Vector3;
  32531. exports.Vector2 = Vector2;
  32532. exports.Quaternion = Quaternion;
  32533. exports.Color = Color;
  32534. exports.ImmediateRenderObject = ImmediateRenderObject;
  32535. exports.VertexNormalsHelper = VertexNormalsHelper;
  32536. exports.SpotLightHelper = SpotLightHelper;
  32537. exports.SkeletonHelper = SkeletonHelper;
  32538. exports.PointLightHelper = PointLightHelper;
  32539. exports.RectAreaLightHelper = RectAreaLightHelper;
  32540. exports.HemisphereLightHelper = HemisphereLightHelper;
  32541. exports.GridHelper = GridHelper;
  32542. exports.PolarGridHelper = PolarGridHelper;
  32543. exports.FaceNormalsHelper = FaceNormalsHelper;
  32544. exports.DirectionalLightHelper = DirectionalLightHelper;
  32545. exports.CameraHelper = CameraHelper;
  32546. exports.BoxHelper = BoxHelper;
  32547. exports.Box3Helper = Box3Helper;
  32548. exports.PlaneHelper = PlaneHelper;
  32549. exports.ArrowHelper = ArrowHelper;
  32550. exports.AxesHelper = AxesHelper;
  32551. exports.Shape = Shape;
  32552. exports.Path = Path;
  32553. exports.ShapePath = ShapePath;
  32554. exports.Font = Font;
  32555. exports.CurvePath = CurvePath;
  32556. exports.Curve = Curve;
  32557. exports.ImageUtils = ImageUtils;
  32558. exports.ShapeUtils = ShapeUtils;
  32559. exports.WebGLUtils = WebGLUtils;
  32560. exports.WireframeGeometry = WireframeGeometry;
  32561. exports.ParametricGeometry = ParametricGeometry;
  32562. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  32563. exports.TetrahedronGeometry = TetrahedronGeometry;
  32564. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  32565. exports.OctahedronGeometry = OctahedronGeometry;
  32566. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  32567. exports.IcosahedronGeometry = IcosahedronGeometry;
  32568. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  32569. exports.DodecahedronGeometry = DodecahedronGeometry;
  32570. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  32571. exports.PolyhedronGeometry = PolyhedronGeometry;
  32572. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  32573. exports.TubeGeometry = TubeGeometry;
  32574. exports.TubeBufferGeometry = TubeBufferGeometry;
  32575. exports.TorusKnotGeometry = TorusKnotGeometry;
  32576. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  32577. exports.TorusGeometry = TorusGeometry;
  32578. exports.TorusBufferGeometry = TorusBufferGeometry;
  32579. exports.TextGeometry = TextGeometry;
  32580. exports.TextBufferGeometry = TextBufferGeometry;
  32581. exports.SphereGeometry = SphereGeometry;
  32582. exports.SphereBufferGeometry = SphereBufferGeometry;
  32583. exports.RingGeometry = RingGeometry;
  32584. exports.RingBufferGeometry = RingBufferGeometry;
  32585. exports.PlaneGeometry = PlaneGeometry;
  32586. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  32587. exports.LatheGeometry = LatheGeometry;
  32588. exports.LatheBufferGeometry = LatheBufferGeometry;
  32589. exports.ShapeGeometry = ShapeGeometry;
  32590. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  32591. exports.ExtrudeGeometry = ExtrudeGeometry;
  32592. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  32593. exports.EdgesGeometry = EdgesGeometry;
  32594. exports.ConeGeometry = ConeGeometry;
  32595. exports.ConeBufferGeometry = ConeBufferGeometry;
  32596. exports.CylinderGeometry = CylinderGeometry;
  32597. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  32598. exports.CircleGeometry = CircleGeometry;
  32599. exports.CircleBufferGeometry = CircleBufferGeometry;
  32600. exports.BoxGeometry = BoxGeometry;
  32601. exports.BoxBufferGeometry = BoxBufferGeometry;
  32602. exports.ShadowMaterial = ShadowMaterial;
  32603. exports.SpriteMaterial = SpriteMaterial;
  32604. exports.RawShaderMaterial = RawShaderMaterial;
  32605. exports.ShaderMaterial = ShaderMaterial;
  32606. exports.PointsMaterial = PointsMaterial;
  32607. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  32608. exports.MeshStandardMaterial = MeshStandardMaterial;
  32609. exports.MeshPhongMaterial = MeshPhongMaterial;
  32610. exports.MeshToonMaterial = MeshToonMaterial;
  32611. exports.MeshNormalMaterial = MeshNormalMaterial;
  32612. exports.MeshLambertMaterial = MeshLambertMaterial;
  32613. exports.MeshDepthMaterial = MeshDepthMaterial;
  32614. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  32615. exports.MeshBasicMaterial = MeshBasicMaterial;
  32616. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  32617. exports.LineDashedMaterial = LineDashedMaterial;
  32618. exports.LineBasicMaterial = LineBasicMaterial;
  32619. exports.Material = Material;
  32620. exports.Float64BufferAttribute = Float64BufferAttribute;
  32621. exports.Float32BufferAttribute = Float32BufferAttribute;
  32622. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  32623. exports.Int32BufferAttribute = Int32BufferAttribute;
  32624. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  32625. exports.Int16BufferAttribute = Int16BufferAttribute;
  32626. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  32627. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  32628. exports.Int8BufferAttribute = Int8BufferAttribute;
  32629. exports.BufferAttribute = BufferAttribute;
  32630. exports.ArcCurve = ArcCurve;
  32631. exports.CatmullRomCurve3 = CatmullRomCurve3;
  32632. exports.CubicBezierCurve = CubicBezierCurve;
  32633. exports.CubicBezierCurve3 = CubicBezierCurve3;
  32634. exports.EllipseCurve = EllipseCurve;
  32635. exports.LineCurve = LineCurve;
  32636. exports.LineCurve3 = LineCurve3;
  32637. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  32638. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  32639. exports.SplineCurve = SplineCurve;
  32640. exports.REVISION = REVISION;
  32641. exports.MOUSE = MOUSE;
  32642. exports.CullFaceNone = CullFaceNone;
  32643. exports.CullFaceBack = CullFaceBack;
  32644. exports.CullFaceFront = CullFaceFront;
  32645. exports.CullFaceFrontBack = CullFaceFrontBack;
  32646. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  32647. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  32648. exports.BasicShadowMap = BasicShadowMap;
  32649. exports.PCFShadowMap = PCFShadowMap;
  32650. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  32651. exports.FrontSide = FrontSide;
  32652. exports.BackSide = BackSide;
  32653. exports.DoubleSide = DoubleSide;
  32654. exports.FlatShading = FlatShading;
  32655. exports.SmoothShading = SmoothShading;
  32656. exports.NoColors = NoColors;
  32657. exports.FaceColors = FaceColors;
  32658. exports.VertexColors = VertexColors;
  32659. exports.NoBlending = NoBlending;
  32660. exports.NormalBlending = NormalBlending;
  32661. exports.AdditiveBlending = AdditiveBlending;
  32662. exports.SubtractiveBlending = SubtractiveBlending;
  32663. exports.MultiplyBlending = MultiplyBlending;
  32664. exports.CustomBlending = CustomBlending;
  32665. exports.AddEquation = AddEquation;
  32666. exports.SubtractEquation = SubtractEquation;
  32667. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  32668. exports.MinEquation = MinEquation;
  32669. exports.MaxEquation = MaxEquation;
  32670. exports.ZeroFactor = ZeroFactor;
  32671. exports.OneFactor = OneFactor;
  32672. exports.SrcColorFactor = SrcColorFactor;
  32673. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  32674. exports.SrcAlphaFactor = SrcAlphaFactor;
  32675. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  32676. exports.DstAlphaFactor = DstAlphaFactor;
  32677. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  32678. exports.DstColorFactor = DstColorFactor;
  32679. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  32680. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  32681. exports.NeverDepth = NeverDepth;
  32682. exports.AlwaysDepth = AlwaysDepth;
  32683. exports.LessDepth = LessDepth;
  32684. exports.LessEqualDepth = LessEqualDepth;
  32685. exports.EqualDepth = EqualDepth;
  32686. exports.GreaterEqualDepth = GreaterEqualDepth;
  32687. exports.GreaterDepth = GreaterDepth;
  32688. exports.NotEqualDepth = NotEqualDepth;
  32689. exports.MultiplyOperation = MultiplyOperation;
  32690. exports.MixOperation = MixOperation;
  32691. exports.AddOperation = AddOperation;
  32692. exports.NoToneMapping = NoToneMapping;
  32693. exports.LinearToneMapping = LinearToneMapping;
  32694. exports.ReinhardToneMapping = ReinhardToneMapping;
  32695. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  32696. exports.CineonToneMapping = CineonToneMapping;
  32697. exports.UVMapping = UVMapping;
  32698. exports.CubeReflectionMapping = CubeReflectionMapping;
  32699. exports.CubeRefractionMapping = CubeRefractionMapping;
  32700. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  32701. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  32702. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  32703. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  32704. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  32705. exports.RepeatWrapping = RepeatWrapping;
  32706. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  32707. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  32708. exports.NearestFilter = NearestFilter;
  32709. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  32710. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  32711. exports.LinearFilter = LinearFilter;
  32712. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  32713. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  32714. exports.UnsignedByteType = UnsignedByteType;
  32715. exports.ByteType = ByteType;
  32716. exports.ShortType = ShortType;
  32717. exports.UnsignedShortType = UnsignedShortType;
  32718. exports.IntType = IntType;
  32719. exports.UnsignedIntType = UnsignedIntType;
  32720. exports.FloatType = FloatType;
  32721. exports.HalfFloatType = HalfFloatType;
  32722. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  32723. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  32724. exports.UnsignedShort565Type = UnsignedShort565Type;
  32725. exports.UnsignedInt248Type = UnsignedInt248Type;
  32726. exports.AlphaFormat = AlphaFormat;
  32727. exports.RGBFormat = RGBFormat;
  32728. exports.RGBAFormat = RGBAFormat;
  32729. exports.LuminanceFormat = LuminanceFormat;
  32730. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  32731. exports.RGBEFormat = RGBEFormat;
  32732. exports.DepthFormat = DepthFormat;
  32733. exports.DepthStencilFormat = DepthStencilFormat;
  32734. exports.RedFormat = RedFormat;
  32735. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  32736. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  32737. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  32738. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  32739. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  32740. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  32741. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  32742. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  32743. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  32744. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  32745. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  32746. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  32747. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  32748. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  32749. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  32750. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  32751. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  32752. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  32753. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  32754. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  32755. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  32756. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  32757. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  32758. exports.LoopOnce = LoopOnce;
  32759. exports.LoopRepeat = LoopRepeat;
  32760. exports.LoopPingPong = LoopPingPong;
  32761. exports.InterpolateDiscrete = InterpolateDiscrete;
  32762. exports.InterpolateLinear = InterpolateLinear;
  32763. exports.InterpolateSmooth = InterpolateSmooth;
  32764. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  32765. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  32766. exports.WrapAroundEnding = WrapAroundEnding;
  32767. exports.TrianglesDrawMode = TrianglesDrawMode;
  32768. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  32769. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  32770. exports.LinearEncoding = LinearEncoding;
  32771. exports.sRGBEncoding = sRGBEncoding;
  32772. exports.GammaEncoding = GammaEncoding;
  32773. exports.RGBEEncoding = RGBEEncoding;
  32774. exports.LogLuvEncoding = LogLuvEncoding;
  32775. exports.RGBM7Encoding = RGBM7Encoding;
  32776. exports.RGBM16Encoding = RGBM16Encoding;
  32777. exports.RGBDEncoding = RGBDEncoding;
  32778. exports.BasicDepthPacking = BasicDepthPacking;
  32779. exports.RGBADepthPacking = RGBADepthPacking;
  32780. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  32781. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  32782. exports.CubeGeometry = BoxGeometry;
  32783. exports.Face4 = Face4;
  32784. exports.LineStrip = LineStrip;
  32785. exports.LinePieces = LinePieces;
  32786. exports.MeshFaceMaterial = MeshFaceMaterial;
  32787. exports.MultiMaterial = MultiMaterial;
  32788. exports.PointCloud = PointCloud;
  32789. exports.Particle = Particle;
  32790. exports.ParticleSystem = ParticleSystem;
  32791. exports.PointCloudMaterial = PointCloudMaterial;
  32792. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  32793. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  32794. exports.Vertex = Vertex;
  32795. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  32796. exports.Int8Attribute = Int8Attribute;
  32797. exports.Uint8Attribute = Uint8Attribute;
  32798. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  32799. exports.Int16Attribute = Int16Attribute;
  32800. exports.Uint16Attribute = Uint16Attribute;
  32801. exports.Int32Attribute = Int32Attribute;
  32802. exports.Uint32Attribute = Uint32Attribute;
  32803. exports.Float32Attribute = Float32Attribute;
  32804. exports.Float64Attribute = Float64Attribute;
  32805. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  32806. exports.SplineCurve3 = SplineCurve3;
  32807. exports.Spline = Spline;
  32808. exports.AxisHelper = AxisHelper;
  32809. exports.BoundingBoxHelper = BoundingBoxHelper;
  32810. exports.EdgesHelper = EdgesHelper;
  32811. exports.WireframeHelper = WireframeHelper;
  32812. exports.XHRLoader = XHRLoader;
  32813. exports.BinaryTextureLoader = BinaryTextureLoader;
  32814. exports.GeometryUtils = GeometryUtils;
  32815. exports.Projector = Projector;
  32816. exports.CanvasRenderer = CanvasRenderer;
  32817. exports.SceneUtils = SceneUtils;
  32818. exports.LensFlare = LensFlare;
  32819. Object.defineProperty(exports, '__esModule', { value: true });
  32820. })));
  32821. },{}],40:[function(_dereq_,module,exports){
  32822. /**
  32823. * @author mrdoob / http://mrdoob.com/
  32824. * @author Mugen87 / https://github.com/Mugen87
  32825. */
  32826. THREE.ColladaLoader = function ( manager ) {
  32827. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  32828. };
  32829. THREE.ColladaLoader.prototype = {
  32830. constructor: THREE.ColladaLoader,
  32831. crossOrigin: 'anonymous',
  32832. load: function ( url, onLoad, onProgress, onError ) {
  32833. var scope = this;
  32834. var path = ( scope.path === undefined ) ? THREE.LoaderUtils.extractUrlBase( url ) : scope.path;
  32835. var loader = new THREE.FileLoader( scope.manager );
  32836. loader.setPath( scope.path );
  32837. loader.load( url, function ( text ) {
  32838. onLoad( scope.parse( text, path ) );
  32839. }, onProgress, onError );
  32840. },
  32841. setPath: function ( value ) {
  32842. this.path = value;
  32843. return this;
  32844. },
  32845. setResourcePath: function ( value ) {
  32846. this.resourcePath = value;
  32847. return this;
  32848. },
  32849. options: {
  32850. set convertUpAxis( value ) {
  32851. console.warn( 'THREE.ColladaLoader: options.convertUpAxis() has been removed. Up axis is converted automatically.' );
  32852. }
  32853. },
  32854. setCrossOrigin: function ( value ) {
  32855. this.crossOrigin = value;
  32856. return this;
  32857. },
  32858. parse: function ( text, path ) {
  32859. function getElementsByTagName( xml, name ) {
  32860. // Non recursive xml.getElementsByTagName() ...
  32861. var array = [];
  32862. var childNodes = xml.childNodes;
  32863. for ( var i = 0, l = childNodes.length; i < l; i ++ ) {
  32864. var child = childNodes[ i ];
  32865. if ( child.nodeName === name ) {
  32866. array.push( child );
  32867. }
  32868. }
  32869. return array;
  32870. }
  32871. function parseStrings( text ) {
  32872. if ( text.length === 0 ) return [];
  32873. var parts = text.trim().split( /\s+/ );
  32874. var array = new Array( parts.length );
  32875. for ( var i = 0, l = parts.length; i < l; i ++ ) {
  32876. array[ i ] = parts[ i ];
  32877. }
  32878. return array;
  32879. }
  32880. function parseFloats( text ) {
  32881. if ( text.length === 0 ) return [];
  32882. var parts = text.trim().split( /\s+/ );
  32883. var array = new Array( parts.length );
  32884. for ( var i = 0, l = parts.length; i < l; i ++ ) {
  32885. array[ i ] = parseFloat( parts[ i ] );
  32886. }
  32887. return array;
  32888. }
  32889. function parseInts( text ) {
  32890. if ( text.length === 0 ) return [];
  32891. var parts = text.trim().split( /\s+/ );
  32892. var array = new Array( parts.length );
  32893. for ( var i = 0, l = parts.length; i < l; i ++ ) {
  32894. array[ i ] = parseInt( parts[ i ] );
  32895. }
  32896. return array;
  32897. }
  32898. function parseId( text ) {
  32899. return text.substring( 1 );
  32900. }
  32901. function generateId() {
  32902. return 'three_default_' + ( count ++ );
  32903. }
  32904. function isEmpty( object ) {
  32905. return Object.keys( object ).length === 0;
  32906. }
  32907. // asset
  32908. function parseAsset( xml ) {
  32909. return {
  32910. unit: parseAssetUnit( getElementsByTagName( xml, 'unit' )[ 0 ] ),
  32911. upAxis: parseAssetUpAxis( getElementsByTagName( xml, 'up_axis' )[ 0 ] )
  32912. };
  32913. }
  32914. function parseAssetUnit( xml ) {
  32915. if ( ( xml !== undefined ) && ( xml.hasAttribute( 'meter' ) === true ) ) {
  32916. return parseFloat( xml.getAttribute( 'meter' ) );
  32917. } else {
  32918. return 1; // default 1 meter
  32919. }
  32920. }
  32921. function parseAssetUpAxis( xml ) {
  32922. return xml !== undefined ? xml.textContent : 'Y_UP';
  32923. }
  32924. // library
  32925. function parseLibrary( xml, libraryName, nodeName, parser ) {
  32926. var library = getElementsByTagName( xml, libraryName )[ 0 ];
  32927. if ( library !== undefined ) {
  32928. var elements = getElementsByTagName( library, nodeName );
  32929. for ( var i = 0; i < elements.length; i ++ ) {
  32930. parser( elements[ i ] );
  32931. }
  32932. }
  32933. }
  32934. function buildLibrary( data, builder ) {
  32935. for ( var name in data ) {
  32936. var object = data[ name ];
  32937. object.build = builder( data[ name ] );
  32938. }
  32939. }
  32940. // get
  32941. function getBuild( data, builder ) {
  32942. if ( data.build !== undefined ) return data.build;
  32943. data.build = builder( data );
  32944. return data.build;
  32945. }
  32946. // animation
  32947. function parseAnimation( xml ) {
  32948. var data = {
  32949. sources: {},
  32950. samplers: {},
  32951. channels: {}
  32952. };
  32953. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32954. var child = xml.childNodes[ i ];
  32955. if ( child.nodeType !== 1 ) continue;
  32956. var id;
  32957. switch ( child.nodeName ) {
  32958. case 'source':
  32959. id = child.getAttribute( 'id' );
  32960. data.sources[ id ] = parseSource( child );
  32961. break;
  32962. case 'sampler':
  32963. id = child.getAttribute( 'id' );
  32964. data.samplers[ id ] = parseAnimationSampler( child );
  32965. break;
  32966. case 'channel':
  32967. id = child.getAttribute( 'target' );
  32968. data.channels[ id ] = parseAnimationChannel( child );
  32969. break;
  32970. default:
  32971. console.log( child );
  32972. }
  32973. }
  32974. library.animations[ xml.getAttribute( 'id' ) ] = data;
  32975. }
  32976. function parseAnimationSampler( xml ) {
  32977. var data = {
  32978. inputs: {},
  32979. };
  32980. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32981. var child = xml.childNodes[ i ];
  32982. if ( child.nodeType !== 1 ) continue;
  32983. switch ( child.nodeName ) {
  32984. case 'input':
  32985. var id = parseId( child.getAttribute( 'source' ) );
  32986. var semantic = child.getAttribute( 'semantic' );
  32987. data.inputs[ semantic ] = id;
  32988. break;
  32989. }
  32990. }
  32991. return data;
  32992. }
  32993. function parseAnimationChannel( xml ) {
  32994. var data = {};
  32995. var target = xml.getAttribute( 'target' );
  32996. // parsing SID Addressing Syntax
  32997. var parts = target.split( '/' );
  32998. var id = parts.shift();
  32999. var sid = parts.shift();
  33000. // check selection syntax
  33001. var arraySyntax = ( sid.indexOf( '(' ) !== - 1 );
  33002. var memberSyntax = ( sid.indexOf( '.' ) !== - 1 );
  33003. if ( memberSyntax ) {
  33004. // member selection access
  33005. parts = sid.split( '.' );
  33006. sid = parts.shift();
  33007. data.member = parts.shift();
  33008. } else if ( arraySyntax ) {
  33009. // array-access syntax. can be used to express fields in one-dimensional vectors or two-dimensional matrices.
  33010. var indices = sid.split( '(' );
  33011. sid = indices.shift();
  33012. for ( var i = 0; i < indices.length; i ++ ) {
  33013. indices[ i ] = parseInt( indices[ i ].replace( /\)/, '' ) );
  33014. }
  33015. data.indices = indices;
  33016. }
  33017. data.id = id;
  33018. data.sid = sid;
  33019. data.arraySyntax = arraySyntax;
  33020. data.memberSyntax = memberSyntax;
  33021. data.sampler = parseId( xml.getAttribute( 'source' ) );
  33022. return data;
  33023. }
  33024. function buildAnimation( data ) {
  33025. var tracks = [];
  33026. var channels = data.channels;
  33027. var samplers = data.samplers;
  33028. var sources = data.sources;
  33029. for ( var target in channels ) {
  33030. if ( channels.hasOwnProperty( target ) ) {
  33031. var channel = channels[ target ];
  33032. var sampler = samplers[ channel.sampler ];
  33033. var inputId = sampler.inputs.INPUT;
  33034. var outputId = sampler.inputs.OUTPUT;
  33035. var inputSource = sources[ inputId ];
  33036. var outputSource = sources[ outputId ];
  33037. var animation = buildAnimationChannel( channel, inputSource, outputSource );
  33038. createKeyframeTracks( animation, tracks );
  33039. }
  33040. }
  33041. return tracks;
  33042. }
  33043. function getAnimation( id ) {
  33044. return getBuild( library.animations[ id ], buildAnimation );
  33045. }
  33046. function buildAnimationChannel( channel, inputSource, outputSource ) {
  33047. var node = library.nodes[ channel.id ];
  33048. var object3D = getNode( node.id );
  33049. var transform = node.transforms[ channel.sid ];
  33050. var defaultMatrix = node.matrix.clone().transpose();
  33051. var time, stride;
  33052. var i, il, j, jl;
  33053. var data = {};
  33054. // the collada spec allows the animation of data in various ways.
  33055. // depending on the transform type (matrix, translate, rotate, scale), we execute different logic
  33056. switch ( transform ) {
  33057. case 'matrix':
  33058. for ( i = 0, il = inputSource.array.length; i < il; i ++ ) {
  33059. time = inputSource.array[ i ];
  33060. stride = i * outputSource.stride;
  33061. if ( data[ time ] === undefined ) data[ time ] = {};
  33062. if ( channel.arraySyntax === true ) {
  33063. var value = outputSource.array[ stride ];
  33064. var index = channel.indices[ 0 ] + 4 * channel.indices[ 1 ];
  33065. data[ time ][ index ] = value;
  33066. } else {
  33067. for ( j = 0, jl = outputSource.stride; j < jl; j ++ ) {
  33068. data[ time ][ j ] = outputSource.array[ stride + j ];
  33069. }
  33070. }
  33071. }
  33072. break;
  33073. case 'translate':
  33074. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  33075. break;
  33076. case 'rotate':
  33077. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  33078. break;
  33079. case 'scale':
  33080. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  33081. break;
  33082. }
  33083. var keyframes = prepareAnimationData( data, defaultMatrix );
  33084. var animation = {
  33085. name: object3D.uuid,
  33086. keyframes: keyframes
  33087. };
  33088. return animation;
  33089. }
  33090. function prepareAnimationData( data, defaultMatrix ) {
  33091. var keyframes = [];
  33092. // transfer data into a sortable array
  33093. for ( var time in data ) {
  33094. keyframes.push( { time: parseFloat( time ), value: data[ time ] } );
  33095. }
  33096. // ensure keyframes are sorted by time
  33097. keyframes.sort( ascending );
  33098. // now we clean up all animation data, so we can use them for keyframe tracks
  33099. for ( var i = 0; i < 16; i ++ ) {
  33100. transformAnimationData( keyframes, i, defaultMatrix.elements[ i ] );
  33101. }
  33102. return keyframes;
  33103. // array sort function
  33104. function ascending( a, b ) {
  33105. return a.time - b.time;
  33106. }
  33107. }
  33108. var position = new THREE.Vector3();
  33109. var scale = new THREE.Vector3();
  33110. var quaternion = new THREE.Quaternion();
  33111. function createKeyframeTracks( animation, tracks ) {
  33112. var keyframes = animation.keyframes;
  33113. var name = animation.name;
  33114. var times = [];
  33115. var positionData = [];
  33116. var quaternionData = [];
  33117. var scaleData = [];
  33118. for ( var i = 0, l = keyframes.length; i < l; i ++ ) {
  33119. var keyframe = keyframes[ i ];
  33120. var time = keyframe.time;
  33121. var value = keyframe.value;
  33122. matrix.fromArray( value ).transpose();
  33123. matrix.decompose( position, quaternion, scale );
  33124. times.push( time );
  33125. positionData.push( position.x, position.y, position.z );
  33126. quaternionData.push( quaternion.x, quaternion.y, quaternion.z, quaternion.w );
  33127. scaleData.push( scale.x, scale.y, scale.z );
  33128. }
  33129. if ( positionData.length > 0 ) tracks.push( new THREE.VectorKeyframeTrack( name + '.position', times, positionData ) );
  33130. if ( quaternionData.length > 0 ) tracks.push( new THREE.QuaternionKeyframeTrack( name + '.quaternion', times, quaternionData ) );
  33131. if ( scaleData.length > 0 ) tracks.push( new THREE.VectorKeyframeTrack( name + '.scale', times, scaleData ) );
  33132. return tracks;
  33133. }
  33134. function transformAnimationData( keyframes, property, defaultValue ) {
  33135. var keyframe;
  33136. var empty = true;
  33137. var i, l;
  33138. // check, if values of a property are missing in our keyframes
  33139. for ( i = 0, l = keyframes.length; i < l; i ++ ) {
  33140. keyframe = keyframes[ i ];
  33141. if ( keyframe.value[ property ] === undefined ) {
  33142. keyframe.value[ property ] = null; // mark as missing
  33143. } else {
  33144. empty = false;
  33145. }
  33146. }
  33147. if ( empty === true ) {
  33148. // no values at all, so we set a default value
  33149. for ( i = 0, l = keyframes.length; i < l; i ++ ) {
  33150. keyframe = keyframes[ i ];
  33151. keyframe.value[ property ] = defaultValue;
  33152. }
  33153. } else {
  33154. // filling gaps
  33155. createMissingKeyframes( keyframes, property );
  33156. }
  33157. }
  33158. function createMissingKeyframes( keyframes, property ) {
  33159. var prev, next;
  33160. for ( var i = 0, l = keyframes.length; i < l; i ++ ) {
  33161. var keyframe = keyframes[ i ];
  33162. if ( keyframe.value[ property ] === null ) {
  33163. prev = getPrev( keyframes, i, property );
  33164. next = getNext( keyframes, i, property );
  33165. if ( prev === null ) {
  33166. keyframe.value[ property ] = next.value[ property ];
  33167. continue;
  33168. }
  33169. if ( next === null ) {
  33170. keyframe.value[ property ] = prev.value[ property ];
  33171. continue;
  33172. }
  33173. interpolate( keyframe, prev, next, property );
  33174. }
  33175. }
  33176. }
  33177. function getPrev( keyframes, i, property ) {
  33178. while ( i >= 0 ) {
  33179. var keyframe = keyframes[ i ];
  33180. if ( keyframe.value[ property ] !== null ) return keyframe;
  33181. i --;
  33182. }
  33183. return null;
  33184. }
  33185. function getNext( keyframes, i, property ) {
  33186. while ( i < keyframes.length ) {
  33187. var keyframe = keyframes[ i ];
  33188. if ( keyframe.value[ property ] !== null ) return keyframe;
  33189. i ++;
  33190. }
  33191. return null;
  33192. }
  33193. function interpolate( key, prev, next, property ) {
  33194. if ( ( next.time - prev.time ) === 0 ) {
  33195. key.value[ property ] = prev.value[ property ];
  33196. return;
  33197. }
  33198. key.value[ property ] = ( ( key.time - prev.time ) * ( next.value[ property ] - prev.value[ property ] ) / ( next.time - prev.time ) ) + prev.value[ property ];
  33199. }
  33200. // animation clips
  33201. function parseAnimationClip( xml ) {
  33202. var data = {
  33203. name: xml.getAttribute( 'id' ) || 'default',
  33204. start: parseFloat( xml.getAttribute( 'start' ) || 0 ),
  33205. end: parseFloat( xml.getAttribute( 'end' ) || 0 ),
  33206. animations: []
  33207. };
  33208. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33209. var child = xml.childNodes[ i ];
  33210. if ( child.nodeType !== 1 ) continue;
  33211. switch ( child.nodeName ) {
  33212. case 'instance_animation':
  33213. data.animations.push( parseId( child.getAttribute( 'url' ) ) );
  33214. break;
  33215. }
  33216. }
  33217. library.clips[ xml.getAttribute( 'id' ) ] = data;
  33218. }
  33219. function buildAnimationClip( data ) {
  33220. var tracks = [];
  33221. var name = data.name;
  33222. var duration = ( data.end - data.start ) || - 1;
  33223. var animations = data.animations;
  33224. for ( var i = 0, il = animations.length; i < il; i ++ ) {
  33225. var animationTracks = getAnimation( animations[ i ] );
  33226. for ( var j = 0, jl = animationTracks.length; j < jl; j ++ ) {
  33227. tracks.push( animationTracks[ j ] );
  33228. }
  33229. }
  33230. return new THREE.AnimationClip( name, duration, tracks );
  33231. }
  33232. function getAnimationClip( id ) {
  33233. return getBuild( library.clips[ id ], buildAnimationClip );
  33234. }
  33235. // controller
  33236. function parseController( xml ) {
  33237. var data = {};
  33238. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33239. var child = xml.childNodes[ i ];
  33240. if ( child.nodeType !== 1 ) continue;
  33241. switch ( child.nodeName ) {
  33242. case 'skin':
  33243. // there is exactly one skin per controller
  33244. data.id = parseId( child.getAttribute( 'source' ) );
  33245. data.skin = parseSkin( child );
  33246. break;
  33247. case 'morph':
  33248. data.id = parseId( child.getAttribute( 'source' ) );
  33249. console.warn( 'THREE.ColladaLoader: Morph target animation not supported yet.' );
  33250. break;
  33251. }
  33252. }
  33253. library.controllers[ xml.getAttribute( 'id' ) ] = data;
  33254. }
  33255. function parseSkin( xml ) {
  33256. var data = {
  33257. sources: {}
  33258. };
  33259. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33260. var child = xml.childNodes[ i ];
  33261. if ( child.nodeType !== 1 ) continue;
  33262. switch ( child.nodeName ) {
  33263. case 'bind_shape_matrix':
  33264. data.bindShapeMatrix = parseFloats( child.textContent );
  33265. break;
  33266. case 'source':
  33267. var id = child.getAttribute( 'id' );
  33268. data.sources[ id ] = parseSource( child );
  33269. break;
  33270. case 'joints':
  33271. data.joints = parseJoints( child );
  33272. break;
  33273. case 'vertex_weights':
  33274. data.vertexWeights = parseVertexWeights( child );
  33275. break;
  33276. }
  33277. }
  33278. return data;
  33279. }
  33280. function parseJoints( xml ) {
  33281. var data = {
  33282. inputs: {}
  33283. };
  33284. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33285. var child = xml.childNodes[ i ];
  33286. if ( child.nodeType !== 1 ) continue;
  33287. switch ( child.nodeName ) {
  33288. case 'input':
  33289. var semantic = child.getAttribute( 'semantic' );
  33290. var id = parseId( child.getAttribute( 'source' ) );
  33291. data.inputs[ semantic ] = id;
  33292. break;
  33293. }
  33294. }
  33295. return data;
  33296. }
  33297. function parseVertexWeights( xml ) {
  33298. var data = {
  33299. inputs: {}
  33300. };
  33301. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33302. var child = xml.childNodes[ i ];
  33303. if ( child.nodeType !== 1 ) continue;
  33304. switch ( child.nodeName ) {
  33305. case 'input':
  33306. var semantic = child.getAttribute( 'semantic' );
  33307. var id = parseId( child.getAttribute( 'source' ) );
  33308. var offset = parseInt( child.getAttribute( 'offset' ) );
  33309. data.inputs[ semantic ] = { id: id, offset: offset };
  33310. break;
  33311. case 'vcount':
  33312. data.vcount = parseInts( child.textContent );
  33313. break;
  33314. case 'v':
  33315. data.v = parseInts( child.textContent );
  33316. break;
  33317. }
  33318. }
  33319. return data;
  33320. }
  33321. function buildController( data ) {
  33322. var build = {
  33323. id: data.id
  33324. };
  33325. var geometry = library.geometries[ build.id ];
  33326. if ( data.skin !== undefined ) {
  33327. build.skin = buildSkin( data.skin );
  33328. // we enhance the 'sources' property of the corresponding geometry with our skin data
  33329. geometry.sources.skinIndices = build.skin.indices;
  33330. geometry.sources.skinWeights = build.skin.weights;
  33331. }
  33332. return build;
  33333. }
  33334. function buildSkin( data ) {
  33335. var BONE_LIMIT = 4;
  33336. var build = {
  33337. joints: [], // this must be an array to preserve the joint order
  33338. indices: {
  33339. array: [],
  33340. stride: BONE_LIMIT
  33341. },
  33342. weights: {
  33343. array: [],
  33344. stride: BONE_LIMIT
  33345. }
  33346. };
  33347. var sources = data.sources;
  33348. var vertexWeights = data.vertexWeights;
  33349. var vcount = vertexWeights.vcount;
  33350. var v = vertexWeights.v;
  33351. var jointOffset = vertexWeights.inputs.JOINT.offset;
  33352. var weightOffset = vertexWeights.inputs.WEIGHT.offset;
  33353. var jointSource = data.sources[ data.joints.inputs.JOINT ];
  33354. var inverseSource = data.sources[ data.joints.inputs.INV_BIND_MATRIX ];
  33355. var weights = sources[ vertexWeights.inputs.WEIGHT.id ].array;
  33356. var stride = 0;
  33357. var i, j, l;
  33358. // procces skin data for each vertex
  33359. for ( i = 0, l = vcount.length; i < l; i ++ ) {
  33360. var jointCount = vcount[ i ]; // this is the amount of joints that affect a single vertex
  33361. var vertexSkinData = [];
  33362. for ( j = 0; j < jointCount; j ++ ) {
  33363. var skinIndex = v[ stride + jointOffset ];
  33364. var weightId = v[ stride + weightOffset ];
  33365. var skinWeight = weights[ weightId ];
  33366. vertexSkinData.push( { index: skinIndex, weight: skinWeight } );
  33367. stride += 2;
  33368. }
  33369. // we sort the joints in descending order based on the weights.
  33370. // this ensures, we only procced the most important joints of the vertex
  33371. vertexSkinData.sort( descending );
  33372. // now we provide for each vertex a set of four index and weight values.
  33373. // the order of the skin data matches the order of vertices
  33374. for ( j = 0; j < BONE_LIMIT; j ++ ) {
  33375. var d = vertexSkinData[ j ];
  33376. if ( d !== undefined ) {
  33377. build.indices.array.push( d.index );
  33378. build.weights.array.push( d.weight );
  33379. } else {
  33380. build.indices.array.push( 0 );
  33381. build.weights.array.push( 0 );
  33382. }
  33383. }
  33384. }
  33385. // setup bind matrix
  33386. if ( data.bindShapeMatrix ) {
  33387. build.bindMatrix = new THREE.Matrix4().fromArray( data.bindShapeMatrix ).transpose();
  33388. } else {
  33389. build.bindMatrix = new THREE.Matrix4().identity();
  33390. }
  33391. // process bones and inverse bind matrix data
  33392. for ( i = 0, l = jointSource.array.length; i < l; i ++ ) {
  33393. var name = jointSource.array[ i ];
  33394. var boneInverse = new THREE.Matrix4().fromArray( inverseSource.array, i * inverseSource.stride ).transpose();
  33395. build.joints.push( { name: name, boneInverse: boneInverse } );
  33396. }
  33397. return build;
  33398. // array sort function
  33399. function descending( a, b ) {
  33400. return b.weight - a.weight;
  33401. }
  33402. }
  33403. function getController( id ) {
  33404. return getBuild( library.controllers[ id ], buildController );
  33405. }
  33406. // image
  33407. function parseImage( xml ) {
  33408. var data = {
  33409. init_from: getElementsByTagName( xml, 'init_from' )[ 0 ].textContent
  33410. };
  33411. library.images[ xml.getAttribute( 'id' ) ] = data;
  33412. }
  33413. function buildImage( data ) {
  33414. if ( data.build !== undefined ) return data.build;
  33415. return data.init_from;
  33416. }
  33417. function getImage( id ) {
  33418. var data = library.images[ id ];
  33419. if ( data !== undefined ) {
  33420. return getBuild( data, buildImage );
  33421. }
  33422. console.warn( 'THREE.ColladaLoader: Couldn\'t find image with ID:', id );
  33423. return null;
  33424. }
  33425. // effect
  33426. function parseEffect( xml ) {
  33427. var data = {};
  33428. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33429. var child = xml.childNodes[ i ];
  33430. if ( child.nodeType !== 1 ) continue;
  33431. switch ( child.nodeName ) {
  33432. case 'profile_COMMON':
  33433. data.profile = parseEffectProfileCOMMON( child );
  33434. break;
  33435. }
  33436. }
  33437. library.effects[ xml.getAttribute( 'id' ) ] = data;
  33438. }
  33439. function parseEffectProfileCOMMON( xml ) {
  33440. var data = {
  33441. surfaces: {},
  33442. samplers: {}
  33443. };
  33444. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33445. var child = xml.childNodes[ i ];
  33446. if ( child.nodeType !== 1 ) continue;
  33447. switch ( child.nodeName ) {
  33448. case 'newparam':
  33449. parseEffectNewparam( child, data );
  33450. break;
  33451. case 'technique':
  33452. data.technique = parseEffectTechnique( child );
  33453. break;
  33454. case 'extra':
  33455. data.extra = parseEffectExtra( child );
  33456. break;
  33457. }
  33458. }
  33459. return data;
  33460. }
  33461. function parseEffectNewparam( xml, data ) {
  33462. var sid = xml.getAttribute( 'sid' );
  33463. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33464. var child = xml.childNodes[ i ];
  33465. if ( child.nodeType !== 1 ) continue;
  33466. switch ( child.nodeName ) {
  33467. case 'surface':
  33468. data.surfaces[ sid ] = parseEffectSurface( child );
  33469. break;
  33470. case 'sampler2D':
  33471. data.samplers[ sid ] = parseEffectSampler( child );
  33472. break;
  33473. }
  33474. }
  33475. }
  33476. function parseEffectSurface( xml ) {
  33477. var data = {};
  33478. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33479. var child = xml.childNodes[ i ];
  33480. if ( child.nodeType !== 1 ) continue;
  33481. switch ( child.nodeName ) {
  33482. case 'init_from':
  33483. data.init_from = child.textContent;
  33484. break;
  33485. }
  33486. }
  33487. return data;
  33488. }
  33489. function parseEffectSampler( xml ) {
  33490. var data = {};
  33491. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33492. var child = xml.childNodes[ i ];
  33493. if ( child.nodeType !== 1 ) continue;
  33494. switch ( child.nodeName ) {
  33495. case 'source':
  33496. data.source = child.textContent;
  33497. break;
  33498. }
  33499. }
  33500. return data;
  33501. }
  33502. function parseEffectTechnique( xml ) {
  33503. var data = {};
  33504. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33505. var child = xml.childNodes[ i ];
  33506. if ( child.nodeType !== 1 ) continue;
  33507. switch ( child.nodeName ) {
  33508. case 'constant':
  33509. case 'lambert':
  33510. case 'blinn':
  33511. case 'phong':
  33512. data.type = child.nodeName;
  33513. data.parameters = parseEffectParameters( child );
  33514. break;
  33515. }
  33516. }
  33517. return data;
  33518. }
  33519. function parseEffectParameters( xml ) {
  33520. var data = {};
  33521. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33522. var child = xml.childNodes[ i ];
  33523. if ( child.nodeType !== 1 ) continue;
  33524. switch ( child.nodeName ) {
  33525. case 'emission':
  33526. case 'diffuse':
  33527. case 'specular':
  33528. case 'shininess':
  33529. case 'transparency':
  33530. data[ child.nodeName ] = parseEffectParameter( child );
  33531. break;
  33532. case 'transparent':
  33533. data[ child.nodeName ] = {
  33534. opaque: child.getAttribute( 'opaque' ),
  33535. data: parseEffectParameter( child )
  33536. };
  33537. break;
  33538. }
  33539. }
  33540. return data;
  33541. }
  33542. function parseEffectParameter( xml ) {
  33543. var data = {};
  33544. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33545. var child = xml.childNodes[ i ];
  33546. if ( child.nodeType !== 1 ) continue;
  33547. switch ( child.nodeName ) {
  33548. case 'color':
  33549. data[ child.nodeName ] = parseFloats( child.textContent );
  33550. break;
  33551. case 'float':
  33552. data[ child.nodeName ] = parseFloat( child.textContent );
  33553. break;
  33554. case 'texture':
  33555. data[ child.nodeName ] = { id: child.getAttribute( 'texture' ), extra: parseEffectParameterTexture( child ) };
  33556. break;
  33557. }
  33558. }
  33559. return data;
  33560. }
  33561. function parseEffectParameterTexture( xml ) {
  33562. var data = {
  33563. technique: {}
  33564. };
  33565. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33566. var child = xml.childNodes[ i ];
  33567. if ( child.nodeType !== 1 ) continue;
  33568. switch ( child.nodeName ) {
  33569. case 'extra':
  33570. parseEffectParameterTextureExtra( child, data );
  33571. break;
  33572. }
  33573. }
  33574. return data;
  33575. }
  33576. function parseEffectParameterTextureExtra( xml, data ) {
  33577. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33578. var child = xml.childNodes[ i ];
  33579. if ( child.nodeType !== 1 ) continue;
  33580. switch ( child.nodeName ) {
  33581. case 'technique':
  33582. parseEffectParameterTextureExtraTechnique( child, data );
  33583. break;
  33584. }
  33585. }
  33586. }
  33587. function parseEffectParameterTextureExtraTechnique( xml, data ) {
  33588. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33589. var child = xml.childNodes[ i ];
  33590. if ( child.nodeType !== 1 ) continue;
  33591. switch ( child.nodeName ) {
  33592. case 'repeatU':
  33593. case 'repeatV':
  33594. case 'offsetU':
  33595. case 'offsetV':
  33596. data.technique[ child.nodeName ] = parseFloat( child.textContent );
  33597. break;
  33598. case 'wrapU':
  33599. case 'wrapV':
  33600. // some files have values for wrapU/wrapV which become NaN via parseInt
  33601. if ( child.textContent.toUpperCase() === 'TRUE' ) {
  33602. data.technique[ child.nodeName ] = 1;
  33603. } else if ( child.textContent.toUpperCase() === 'FALSE' ) {
  33604. data.technique[ child.nodeName ] = 0;
  33605. } else {
  33606. data.technique[ child.nodeName ] = parseInt( child.textContent );
  33607. }
  33608. break;
  33609. }
  33610. }
  33611. }
  33612. function parseEffectExtra( xml ) {
  33613. var data = {};
  33614. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33615. var child = xml.childNodes[ i ];
  33616. if ( child.nodeType !== 1 ) continue;
  33617. switch ( child.nodeName ) {
  33618. case 'technique':
  33619. data.technique = parseEffectExtraTechnique( child );
  33620. break;
  33621. }
  33622. }
  33623. return data;
  33624. }
  33625. function parseEffectExtraTechnique( xml ) {
  33626. var data = {};
  33627. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33628. var child = xml.childNodes[ i ];
  33629. if ( child.nodeType !== 1 ) continue;
  33630. switch ( child.nodeName ) {
  33631. case 'double_sided':
  33632. data[ child.nodeName ] = parseInt( child.textContent );
  33633. break;
  33634. }
  33635. }
  33636. return data;
  33637. }
  33638. function buildEffect( data ) {
  33639. return data;
  33640. }
  33641. function getEffect( id ) {
  33642. return getBuild( library.effects[ id ], buildEffect );
  33643. }
  33644. // material
  33645. function parseMaterial( xml ) {
  33646. var data = {
  33647. name: xml.getAttribute( 'name' )
  33648. };
  33649. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33650. var child = xml.childNodes[ i ];
  33651. if ( child.nodeType !== 1 ) continue;
  33652. switch ( child.nodeName ) {
  33653. case 'instance_effect':
  33654. data.url = parseId( child.getAttribute( 'url' ) );
  33655. break;
  33656. }
  33657. }
  33658. library.materials[ xml.getAttribute( 'id' ) ] = data;
  33659. }
  33660. function getTextureLoader( image ) {
  33661. var loader;
  33662. var extension = image.slice( ( image.lastIndexOf( '.' ) - 1 >>> 0 ) + 2 ); // http://www.jstips.co/en/javascript/get-file-extension/
  33663. extension = extension.toLowerCase();
  33664. switch ( extension ) {
  33665. case 'tga':
  33666. loader = tgaLoader;
  33667. break;
  33668. default:
  33669. loader = textureLoader;
  33670. }
  33671. return loader;
  33672. }
  33673. function buildMaterial( data ) {
  33674. var effect = getEffect( data.url );
  33675. var technique = effect.profile.technique;
  33676. var extra = effect.profile.extra;
  33677. var material;
  33678. switch ( technique.type ) {
  33679. case 'phong':
  33680. case 'blinn':
  33681. material = new THREE.MeshPhongMaterial();
  33682. break;
  33683. case 'lambert':
  33684. material = new THREE.MeshLambertMaterial();
  33685. break;
  33686. default:
  33687. material = new THREE.MeshBasicMaterial();
  33688. break;
  33689. }
  33690. material.name = data.name;
  33691. function getTexture( textureObject ) {
  33692. var sampler = effect.profile.samplers[ textureObject.id ];
  33693. var image = null;
  33694. // get image
  33695. if ( sampler !== undefined ) {
  33696. var surface = effect.profile.surfaces[ sampler.source ];
  33697. image = getImage( surface.init_from );
  33698. } else {
  33699. console.warn( 'THREE.ColladaLoader: Undefined sampler. Access image directly (see #12530).' );
  33700. image = getImage( textureObject.id );
  33701. }
  33702. // create texture if image is avaiable
  33703. if ( image !== null ) {
  33704. var loader = getTextureLoader( image );
  33705. if ( loader !== undefined ) {
  33706. var texture = loader.load( image );
  33707. var extra = textureObject.extra;
  33708. if ( extra !== undefined && extra.technique !== undefined && isEmpty( extra.technique ) === false ) {
  33709. var technique = extra.technique;
  33710. texture.wrapS = technique.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  33711. texture.wrapT = technique.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  33712. texture.offset.set( technique.offsetU || 0, technique.offsetV || 0 );
  33713. texture.repeat.set( technique.repeatU || 1, technique.repeatV || 1 );
  33714. } else {
  33715. texture.wrapS = THREE.RepeatWrapping;
  33716. texture.wrapT = THREE.RepeatWrapping;
  33717. }
  33718. return texture;
  33719. } else {
  33720. console.warn( 'THREE.ColladaLoader: Loader for texture %s not found.', image );
  33721. return null;
  33722. }
  33723. } else {
  33724. console.warn( 'THREE.ColladaLoader: Couldn\'t create texture with ID:', textureObject.id );
  33725. return null;
  33726. }
  33727. }
  33728. var parameters = technique.parameters;
  33729. for ( var key in parameters ) {
  33730. var parameter = parameters[ key ];
  33731. switch ( key ) {
  33732. case 'diffuse':
  33733. if ( parameter.color ) material.color.fromArray( parameter.color );
  33734. if ( parameter.texture ) material.map = getTexture( parameter.texture );
  33735. break;
  33736. case 'specular':
  33737. if ( parameter.color && material.specular ) material.specular.fromArray( parameter.color );
  33738. if ( parameter.texture ) material.specularMap = getTexture( parameter.texture );
  33739. break;
  33740. case 'shininess':
  33741. if ( parameter.float && material.shininess ) material.shininess = parameter.float;
  33742. break;
  33743. case 'emission':
  33744. if ( parameter.color && material.emissive ) material.emissive.fromArray( parameter.color );
  33745. if ( parameter.texture ) material.emissiveMap = getTexture( parameter.texture );
  33746. break;
  33747. }
  33748. }
  33749. //
  33750. var transparent = parameters[ 'transparent' ];
  33751. var transparency = parameters[ 'transparency' ];
  33752. // <transparency> does not exist but <transparent>
  33753. if ( transparency === undefined && transparent ) {
  33754. transparency = {
  33755. float: 1
  33756. };
  33757. }
  33758. // <transparent> does not exist but <transparency>
  33759. if ( transparent === undefined && transparency ) {
  33760. transparent = {
  33761. opaque: 'A_ONE',
  33762. data: {
  33763. color: [ 1, 1, 1, 1 ]
  33764. } };
  33765. }
  33766. if ( transparent && transparency ) {
  33767. // handle case if a texture exists but no color
  33768. if ( transparent.data.texture ) {
  33769. // we do not set an alpha map (see #13792)
  33770. material.transparent = true;
  33771. } else {
  33772. var color = transparent.data.color;
  33773. switch ( transparent.opaque ) {
  33774. case 'A_ONE':
  33775. material.opacity = color[ 3 ] * transparency.float;
  33776. break;
  33777. case 'RGB_ZERO':
  33778. material.opacity = 1 - ( color[ 0 ] * transparency.float );
  33779. break;
  33780. case 'A_ZERO':
  33781. material.opacity = 1 - ( color[ 3 ] * transparency.float );
  33782. break;
  33783. case 'RGB_ONE':
  33784. material.opacity = color[ 0 ] * transparency.float;
  33785. break;
  33786. default:
  33787. console.warn( 'THREE.ColladaLoader: Invalid opaque type "%s" of transparent tag.', transparent.opaque );
  33788. }
  33789. if ( material.opacity < 1 ) material.transparent = true;
  33790. }
  33791. }
  33792. //
  33793. if ( extra !== undefined && extra.technique !== undefined && extra.technique.double_sided === 1 ) {
  33794. material.side = THREE.DoubleSide;
  33795. }
  33796. return material;
  33797. }
  33798. function getMaterial( id ) {
  33799. return getBuild( library.materials[ id ], buildMaterial );
  33800. }
  33801. // camera
  33802. function parseCamera( xml ) {
  33803. var data = {
  33804. name: xml.getAttribute( 'name' )
  33805. };
  33806. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33807. var child = xml.childNodes[ i ];
  33808. if ( child.nodeType !== 1 ) continue;
  33809. switch ( child.nodeName ) {
  33810. case 'optics':
  33811. data.optics = parseCameraOptics( child );
  33812. break;
  33813. }
  33814. }
  33815. library.cameras[ xml.getAttribute( 'id' ) ] = data;
  33816. }
  33817. function parseCameraOptics( xml ) {
  33818. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33819. var child = xml.childNodes[ i ];
  33820. switch ( child.nodeName ) {
  33821. case 'technique_common':
  33822. return parseCameraTechnique( child );
  33823. }
  33824. }
  33825. return {};
  33826. }
  33827. function parseCameraTechnique( xml ) {
  33828. var data = {};
  33829. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33830. var child = xml.childNodes[ i ];
  33831. switch ( child.nodeName ) {
  33832. case 'perspective':
  33833. case 'orthographic':
  33834. data.technique = child.nodeName;
  33835. data.parameters = parseCameraParameters( child );
  33836. break;
  33837. }
  33838. }
  33839. return data;
  33840. }
  33841. function parseCameraParameters( xml ) {
  33842. var data = {};
  33843. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33844. var child = xml.childNodes[ i ];
  33845. switch ( child.nodeName ) {
  33846. case 'xfov':
  33847. case 'yfov':
  33848. case 'xmag':
  33849. case 'ymag':
  33850. case 'znear':
  33851. case 'zfar':
  33852. case 'aspect_ratio':
  33853. data[ child.nodeName ] = parseFloat( child.textContent );
  33854. break;
  33855. }
  33856. }
  33857. return data;
  33858. }
  33859. function buildCamera( data ) {
  33860. var camera;
  33861. switch ( data.optics.technique ) {
  33862. case 'perspective':
  33863. camera = new THREE.PerspectiveCamera(
  33864. data.optics.parameters.yfov,
  33865. data.optics.parameters.aspect_ratio,
  33866. data.optics.parameters.znear,
  33867. data.optics.parameters.zfar
  33868. );
  33869. break;
  33870. case 'orthographic':
  33871. var ymag = data.optics.parameters.ymag;
  33872. var xmag = data.optics.parameters.xmag;
  33873. var aspectRatio = data.optics.parameters.aspect_ratio;
  33874. xmag = ( xmag === undefined ) ? ( ymag * aspectRatio ) : xmag;
  33875. ymag = ( ymag === undefined ) ? ( xmag / aspectRatio ) : ymag;
  33876. xmag *= 0.5;
  33877. ymag *= 0.5;
  33878. camera = new THREE.OrthographicCamera(
  33879. - xmag, xmag, ymag, - ymag, // left, right, top, bottom
  33880. data.optics.parameters.znear,
  33881. data.optics.parameters.zfar
  33882. );
  33883. break;
  33884. default:
  33885. camera = new THREE.PerspectiveCamera();
  33886. break;
  33887. }
  33888. camera.name = data.name;
  33889. return camera;
  33890. }
  33891. function getCamera( id ) {
  33892. var data = library.cameras[ id ];
  33893. if ( data !== undefined ) {
  33894. return getBuild( data, buildCamera );
  33895. }
  33896. console.warn( 'THREE.ColladaLoader: Couldn\'t find camera with ID:', id );
  33897. return null;
  33898. }
  33899. // light
  33900. function parseLight( xml ) {
  33901. var data = {};
  33902. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33903. var child = xml.childNodes[ i ];
  33904. if ( child.nodeType !== 1 ) continue;
  33905. switch ( child.nodeName ) {
  33906. case 'technique_common':
  33907. data = parseLightTechnique( child );
  33908. break;
  33909. }
  33910. }
  33911. library.lights[ xml.getAttribute( 'id' ) ] = data;
  33912. }
  33913. function parseLightTechnique( xml ) {
  33914. var data = {};
  33915. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33916. var child = xml.childNodes[ i ];
  33917. if ( child.nodeType !== 1 ) continue;
  33918. switch ( child.nodeName ) {
  33919. case 'directional':
  33920. case 'point':
  33921. case 'spot':
  33922. case 'ambient':
  33923. data.technique = child.nodeName;
  33924. data.parameters = parseLightParameters( child );
  33925. }
  33926. }
  33927. return data;
  33928. }
  33929. function parseLightParameters( xml ) {
  33930. var data = {};
  33931. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33932. var child = xml.childNodes[ i ];
  33933. if ( child.nodeType !== 1 ) continue;
  33934. switch ( child.nodeName ) {
  33935. case 'color':
  33936. var array = parseFloats( child.textContent );
  33937. data.color = new THREE.Color().fromArray( array );
  33938. break;
  33939. case 'falloff_angle':
  33940. data.falloffAngle = parseFloat( child.textContent );
  33941. break;
  33942. case 'quadratic_attenuation':
  33943. var f = parseFloat( child.textContent );
  33944. data.distance = f ? Math.sqrt( 1 / f ) : 0;
  33945. break;
  33946. }
  33947. }
  33948. return data;
  33949. }
  33950. function buildLight( data ) {
  33951. var light;
  33952. switch ( data.technique ) {
  33953. case 'directional':
  33954. light = new THREE.DirectionalLight();
  33955. break;
  33956. case 'point':
  33957. light = new THREE.PointLight();
  33958. break;
  33959. case 'spot':
  33960. light = new THREE.SpotLight();
  33961. break;
  33962. case 'ambient':
  33963. light = new THREE.AmbientLight();
  33964. break;
  33965. }
  33966. if ( data.parameters.color ) light.color.copy( data.parameters.color );
  33967. if ( data.parameters.distance ) light.distance = data.parameters.distance;
  33968. return light;
  33969. }
  33970. function getLight( id ) {
  33971. var data = library.lights[ id ];
  33972. if ( data !== undefined ) {
  33973. return getBuild( data, buildLight );
  33974. }
  33975. console.warn( 'THREE.ColladaLoader: Couldn\'t find light with ID:', id );
  33976. return null;
  33977. }
  33978. // geometry
  33979. function parseGeometry( xml ) {
  33980. var data = {
  33981. name: xml.getAttribute( 'name' ),
  33982. sources: {},
  33983. vertices: {},
  33984. primitives: []
  33985. };
  33986. var mesh = getElementsByTagName( xml, 'mesh' )[ 0 ];
  33987. // the following tags inside geometry are not supported yet (see https://github.com/mrdoob/three.js/pull/12606): convex_mesh, spline, brep
  33988. if ( mesh === undefined ) return;
  33989. for ( var i = 0; i < mesh.childNodes.length; i ++ ) {
  33990. var child = mesh.childNodes[ i ];
  33991. if ( child.nodeType !== 1 ) continue;
  33992. var id = child.getAttribute( 'id' );
  33993. switch ( child.nodeName ) {
  33994. case 'source':
  33995. data.sources[ id ] = parseSource( child );
  33996. break;
  33997. case 'vertices':
  33998. // data.sources[ id ] = data.sources[ parseId( getElementsByTagName( child, 'input' )[ 0 ].getAttribute( 'source' ) ) ];
  33999. data.vertices = parseGeometryVertices( child );
  34000. break;
  34001. case 'polygons':
  34002. console.warn( 'THREE.ColladaLoader: Unsupported primitive type: ', child.nodeName );
  34003. break;
  34004. case 'lines':
  34005. case 'linestrips':
  34006. case 'polylist':
  34007. case 'triangles':
  34008. data.primitives.push( parseGeometryPrimitive( child ) );
  34009. break;
  34010. default:
  34011. console.log( child );
  34012. }
  34013. }
  34014. library.geometries[ xml.getAttribute( 'id' ) ] = data;
  34015. }
  34016. function parseSource( xml ) {
  34017. var data = {
  34018. array: [],
  34019. stride: 3
  34020. };
  34021. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  34022. var child = xml.childNodes[ i ];
  34023. if ( child.nodeType !== 1 ) continue;
  34024. switch ( child.nodeName ) {
  34025. case 'float_array':
  34026. data.array = parseFloats( child.textContent );
  34027. break;
  34028. case 'Name_array':
  34029. data.array = parseStrings( child.textContent );
  34030. break;
  34031. case 'technique_common':
  34032. var accessor = getElementsByTagName( child, 'accessor' )[ 0 ];
  34033. if ( accessor !== undefined ) {
  34034. data.stride = parseInt( accessor.getAttribute( 'stride' ) );
  34035. }
  34036. break;
  34037. }
  34038. }
  34039. return data;
  34040. }
  34041. function parseGeometryVertices( xml ) {
  34042. var data = {};
  34043. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  34044. var child = xml.childNodes[ i ];
  34045. if ( child.nodeType !== 1 ) continue;
  34046. data[ child.getAttribute( 'semantic' ) ] = parseId( child.getAttribute( 'source' ) );
  34047. }
  34048. return data;
  34049. }
  34050. function parseGeometryPrimitive( xml ) {
  34051. var primitive = {
  34052. type: xml.nodeName,
  34053. material: xml.getAttribute( 'material' ),
  34054. count: parseInt( xml.getAttribute( 'count' ) ),
  34055. inputs: {},
  34056. stride: 0,
  34057. hasUV: false
  34058. };
  34059. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  34060. var child = xml.childNodes[ i ];
  34061. if ( child.nodeType !== 1 ) continue;
  34062. switch ( child.nodeName ) {
  34063. case 'input':
  34064. var id = parseId( child.getAttribute( 'source' ) );
  34065. var semantic = child.getAttribute( 'semantic' );
  34066. var offset = parseInt( child.getAttribute( 'offset' ) );
  34067. primitive.inputs[ semantic ] = { id: id, offset: offset };
  34068. primitive.stride = Math.max( primitive.stride, offset + 1 );
  34069. if ( semantic === 'TEXCOORD' ) primitive.hasUV = true;
  34070. break;
  34071. case 'vcount':
  34072. primitive.vcount = parseInts( child.textContent );
  34073. break;
  34074. case 'p':
  34075. primitive.p = parseInts( child.textContent );
  34076. break;
  34077. }
  34078. }
  34079. return primitive;
  34080. }
  34081. function groupPrimitives( primitives ) {
  34082. var build = {};
  34083. for ( var i = 0; i < primitives.length; i ++ ) {
  34084. var primitive = primitives[ i ];
  34085. if ( build[ primitive.type ] === undefined ) build[ primitive.type ] = [];
  34086. build[ primitive.type ].push( primitive );
  34087. }
  34088. return build;
  34089. }
  34090. function checkUVCoordinates( primitives ) {
  34091. var count = 0;
  34092. for ( var i = 0, l = primitives.length; i < l; i ++ ) {
  34093. var primitive = primitives[ i ];
  34094. if ( primitive.hasUV === true ) {
  34095. count ++;
  34096. }
  34097. }
  34098. if ( count > 0 && count < primitives.length ) {
  34099. primitives.uvsNeedsFix = true;
  34100. }
  34101. }
  34102. function buildGeometry( data ) {
  34103. var build = {};
  34104. var sources = data.sources;
  34105. var vertices = data.vertices;
  34106. var primitives = data.primitives;
  34107. if ( primitives.length === 0 ) return {};
  34108. // our goal is to create one buffer geometry for a single type of primitives
  34109. // first, we group all primitives by their type
  34110. var groupedPrimitives = groupPrimitives( primitives );
  34111. for ( var type in groupedPrimitives ) {
  34112. var primitiveType = groupedPrimitives[ type ];
  34113. // second, ensure consistent uv coordinates for each type of primitives (polylist,triangles or lines)
  34114. checkUVCoordinates( primitiveType );
  34115. // third, create a buffer geometry for each type of primitives
  34116. build[ type ] = buildGeometryType( primitiveType, sources, vertices );
  34117. }
  34118. return build;
  34119. }
  34120. function buildGeometryType( primitives, sources, vertices ) {
  34121. var build = {};
  34122. var position = { array: [], stride: 0 };
  34123. var normal = { array: [], stride: 0 };
  34124. var uv = { array: [], stride: 0 };
  34125. var color = { array: [], stride: 0 };
  34126. var skinIndex = { array: [], stride: 4 };
  34127. var skinWeight = { array: [], stride: 4 };
  34128. var geometry = new THREE.BufferGeometry();
  34129. var materialKeys = [];
  34130. var start = 0;
  34131. for ( var p = 0; p < primitives.length; p ++ ) {
  34132. var primitive = primitives[ p ];
  34133. var inputs = primitive.inputs;
  34134. // groups
  34135. var count = 0;
  34136. switch ( primitive.type ) {
  34137. case 'lines':
  34138. case 'linestrips':
  34139. count = primitive.count * 2;
  34140. break;
  34141. case 'triangles':
  34142. count = primitive.count * 3;
  34143. break;
  34144. case 'polylist':
  34145. for ( var g = 0; g < primitive.count; g ++ ) {
  34146. var vc = primitive.vcount[ g ];
  34147. switch ( vc ) {
  34148. case 3:
  34149. count += 3; // single triangle
  34150. break;
  34151. case 4:
  34152. count += 6; // quad, subdivided into two triangles
  34153. break;
  34154. default:
  34155. count += ( vc - 2 ) * 3; // polylist with more than four vertices
  34156. break;
  34157. }
  34158. }
  34159. break;
  34160. default:
  34161. console.warn( 'THREE.ColladaLoader: Unknow primitive type:', primitive.type );
  34162. }
  34163. geometry.addGroup( start, count, p );
  34164. start += count;
  34165. // material
  34166. if ( primitive.material ) {
  34167. materialKeys.push( primitive.material );
  34168. }
  34169. // geometry data
  34170. for ( var name in inputs ) {
  34171. var input = inputs[ name ];
  34172. switch ( name ) {
  34173. case 'VERTEX':
  34174. for ( var key in vertices ) {
  34175. var id = vertices[ key ];
  34176. switch ( key ) {
  34177. case 'POSITION':
  34178. var prevLength = position.array.length;
  34179. buildGeometryData( primitive, sources[ id ], input.offset, position.array );
  34180. position.stride = sources[ id ].stride;
  34181. if ( sources.skinWeights && sources.skinIndices ) {
  34182. buildGeometryData( primitive, sources.skinIndices, input.offset, skinIndex.array );
  34183. buildGeometryData( primitive, sources.skinWeights, input.offset, skinWeight.array );
  34184. }
  34185. // see #3803
  34186. if ( primitive.hasUV === false && primitives.uvsNeedsFix === true ) {
  34187. var count = ( position.array.length - prevLength ) / position.stride;
  34188. for ( var i = 0; i < count; i ++ ) {
  34189. // fill missing uv coordinates
  34190. uv.array.push( 0, 0 );
  34191. }
  34192. }
  34193. break;
  34194. case 'NORMAL':
  34195. buildGeometryData( primitive, sources[ id ], input.offset, normal.array );
  34196. normal.stride = sources[ id ].stride;
  34197. break;
  34198. case 'COLOR':
  34199. buildGeometryData( primitive, sources[ id ], input.offset, color.array );
  34200. color.stride = sources[ id ].stride;
  34201. break;
  34202. case 'TEXCOORD':
  34203. buildGeometryData( primitive, sources[ id ], input.offset, uv.array );
  34204. uv.stride = sources[ id ].stride;
  34205. break;
  34206. default:
  34207. console.warn( 'THREE.ColladaLoader: Semantic "%s" not handled in geometry build process.', key );
  34208. }
  34209. }
  34210. break;
  34211. case 'NORMAL':
  34212. buildGeometryData( primitive, sources[ input.id ], input.offset, normal.array );
  34213. normal.stride = sources[ input.id ].stride;
  34214. break;
  34215. case 'COLOR':
  34216. buildGeometryData( primitive, sources[ input.id ], input.offset, color.array );
  34217. color.stride = sources[ input.id ].stride;
  34218. break;
  34219. case 'TEXCOORD':
  34220. buildGeometryData( primitive, sources[ input.id ], input.offset, uv.array );
  34221. uv.stride = sources[ input.id ].stride;
  34222. break;
  34223. }
  34224. }
  34225. }
  34226. // build geometry
  34227. if ( position.array.length > 0 ) geometry.addAttribute( 'position', new THREE.Float32BufferAttribute( position.array, position.stride ) );
  34228. if ( normal.array.length > 0 ) geometry.addAttribute( 'normal', new THREE.Float32BufferAttribute( normal.array, normal.stride ) );
  34229. if ( color.array.length > 0 ) geometry.addAttribute( 'color', new THREE.Float32BufferAttribute( color.array, color.stride ) );
  34230. if ( uv.array.length > 0 ) geometry.addAttribute( 'uv', new THREE.Float32BufferAttribute( uv.array, uv.stride ) );
  34231. if ( skinIndex.array.length > 0 ) geometry.addAttribute( 'skinIndex', new THREE.Float32BufferAttribute( skinIndex.array, skinIndex.stride ) );
  34232. if ( skinWeight.array.length > 0 ) geometry.addAttribute( 'skinWeight', new THREE.Float32BufferAttribute( skinWeight.array, skinWeight.stride ) );
  34233. build.data = geometry;
  34234. build.type = primitives[ 0 ].type;
  34235. build.materialKeys = materialKeys;
  34236. return build;
  34237. }
  34238. function buildGeometryData( primitive, source, offset, array ) {
  34239. var indices = primitive.p;
  34240. var stride = primitive.stride;
  34241. var vcount = primitive.vcount;
  34242. function pushVector( i ) {
  34243. var index = indices[ i + offset ] * sourceStride;
  34244. var length = index + sourceStride;
  34245. for ( ; index < length; index ++ ) {
  34246. array.push( sourceArray[ index ] );
  34247. }
  34248. }
  34249. var sourceArray = source.array;
  34250. var sourceStride = source.stride;
  34251. if ( primitive.vcount !== undefined ) {
  34252. var index = 0;
  34253. for ( var i = 0, l = vcount.length; i < l; i ++ ) {
  34254. var count = vcount[ i ];
  34255. if ( count === 4 ) {
  34256. var a = index + stride * 0;
  34257. var b = index + stride * 1;
  34258. var c = index + stride * 2;
  34259. var d = index + stride * 3;
  34260. pushVector( a ); pushVector( b ); pushVector( d );
  34261. pushVector( b ); pushVector( c ); pushVector( d );
  34262. } else if ( count === 3 ) {
  34263. var a = index + stride * 0;
  34264. var b = index + stride * 1;
  34265. var c = index + stride * 2;
  34266. pushVector( a ); pushVector( b ); pushVector( c );
  34267. } else if ( count > 4 ) {
  34268. for ( var k = 1, kl = ( count - 2 ); k <= kl; k ++ ) {
  34269. var a = index + stride * 0;
  34270. var b = index + stride * k;
  34271. var c = index + stride * ( k + 1 );
  34272. pushVector( a ); pushVector( b ); pushVector( c );
  34273. }
  34274. }
  34275. index += stride * count;
  34276. }
  34277. } else {
  34278. for ( var i = 0, l = indices.length; i < l; i += stride ) {
  34279. pushVector( i );
  34280. }
  34281. }
  34282. }
  34283. function getGeometry( id ) {
  34284. return getBuild( library.geometries[ id ], buildGeometry );
  34285. }
  34286. // kinematics
  34287. function parseKinematicsModel( xml ) {
  34288. var data = {
  34289. name: xml.getAttribute( 'name' ) || '',
  34290. joints: {},
  34291. links: []
  34292. };
  34293. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  34294. var child = xml.childNodes[ i ];
  34295. if ( child.nodeType !== 1 ) continue;
  34296. switch ( child.nodeName ) {
  34297. case 'technique_common':
  34298. parseKinematicsTechniqueCommon( child, data );
  34299. break;
  34300. }
  34301. }
  34302. library.kinematicsModels[ xml.getAttribute( 'id' ) ] = data;
  34303. }
  34304. function buildKinematicsModel( data ) {
  34305. if ( data.build !== undefined ) return data.build;
  34306. return data;
  34307. }
  34308. function getKinematicsModel( id ) {
  34309. return getBuild( library.kinematicsModels[ id ], buildKinematicsModel );
  34310. }
  34311. function parseKinematicsTechniqueCommon( xml, data ) {
  34312. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  34313. var child = xml.childNodes[ i ];
  34314. if ( child.nodeType !== 1 ) continue;
  34315. switch ( child.nodeName ) {
  34316. case 'joint':
  34317. data.joints[ child.getAttribute( 'sid' ) ] = parseKinematicsJoint( child );
  34318. break;
  34319. case 'link':
  34320. data.links.push( parseKinematicsLink( child ) );
  34321. break;
  34322. }
  34323. }
  34324. }
  34325. function parseKinematicsJoint( xml ) {
  34326. var data;
  34327. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  34328. var child = xml.childNodes[ i ];
  34329. if ( child.nodeType !== 1 ) continue;
  34330. switch ( child.nodeName ) {
  34331. case 'prismatic':
  34332. case 'revolute':
  34333. data = parseKinematicsJointParameter( child );
  34334. break;
  34335. }
  34336. }
  34337. return data;
  34338. }
  34339. function parseKinematicsJointParameter( xml, data ) {
  34340. var data = {
  34341. sid: xml.getAttribute( 'sid' ),
  34342. name: xml.getAttribute( 'name' ) || '',
  34343. axis: new THREE.Vector3(),
  34344. limits: {
  34345. min: 0,
  34346. max: 0
  34347. },
  34348. type: xml.nodeName,
  34349. static: false,
  34350. zeroPosition: 0,
  34351. middlePosition: 0
  34352. };
  34353. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  34354. var child = xml.childNodes[ i ];
  34355. if ( child.nodeType !== 1 ) continue;
  34356. switch ( child.nodeName ) {
  34357. case 'axis':
  34358. var array = parseFloats( child.textContent );
  34359. data.axis.fromArray( array );
  34360. break;
  34361. case 'limits':
  34362. var max = child.getElementsByTagName( 'max' )[ 0 ];
  34363. var min = child.getElementsByTagName( 'min' )[ 0 ];
  34364. data.limits.max = parseFloat( max.textContent );
  34365. data.limits.min = parseFloat( min.textContent );
  34366. break;
  34367. }
  34368. }
  34369. // if min is equal to or greater than max, consider the joint static
  34370. if ( data.limits.min >= data.limits.max ) {
  34371. data.static = true;
  34372. }
  34373. // calculate middle position
  34374. data.middlePosition = ( data.limits.min + data.limits.max ) / 2.0;
  34375. return data;
  34376. }
  34377. function parseKinematicsLink( xml ) {
  34378. var data = {
  34379. sid: xml.getAttribute( 'sid' ),
  34380. name: xml.getAttribute( 'name' ) || '',
  34381. attachments: [],
  34382. transforms: []
  34383. };
  34384. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  34385. var child = xml.childNodes[ i ];
  34386. if ( child.nodeType !== 1 ) continue;
  34387. switch ( child.nodeName ) {
  34388. case 'attachment_full':
  34389. data.attachments.push( parseKinematicsAttachment( child ) );
  34390. break;
  34391. case 'matrix':
  34392. case 'translate':
  34393. case 'rotate':
  34394. data.transforms.push( parseKinematicsTransform( child ) );
  34395. break;
  34396. }
  34397. }
  34398. return data;
  34399. }
  34400. function parseKinematicsAttachment( xml ) {
  34401. var data = {
  34402. joint: xml.getAttribute( 'joint' ).split( '/' ).pop(),
  34403. transforms: [],
  34404. links: []
  34405. };
  34406. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  34407. var child = xml.childNodes[ i ];
  34408. if ( child.nodeType !== 1 ) continue;
  34409. switch ( child.nodeName ) {
  34410. case 'link':
  34411. data.links.push( parseKinematicsLink( child ) );
  34412. break;
  34413. case 'matrix':
  34414. case 'translate':
  34415. case 'rotate':
  34416. data.transforms.push( parseKinematicsTransform( child ) );
  34417. break;
  34418. }
  34419. }
  34420. return data;
  34421. }
  34422. function parseKinematicsTransform( xml ) {
  34423. var data = {
  34424. type: xml.nodeName
  34425. };
  34426. var array = parseFloats( xml.textContent );
  34427. switch ( data.type ) {
  34428. case 'matrix':
  34429. data.obj = new THREE.Matrix4();
  34430. data.obj.fromArray( array ).transpose();
  34431. break;
  34432. case 'translate':
  34433. data.obj = new THREE.Vector3();
  34434. data.obj.fromArray( array );
  34435. break;
  34436. case 'rotate':
  34437. data.obj = new THREE.Vector3();
  34438. data.obj.fromArray( array );
  34439. data.angle = THREE.Math.degToRad( array[ 3 ] );
  34440. break;
  34441. }
  34442. return data;
  34443. }
  34444. // physics
  34445. function parsePhysicsModel( xml ) {
  34446. var data = {
  34447. name: xml.getAttribute( 'name' ) || '',
  34448. rigidBodies: {}
  34449. };
  34450. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  34451. var child = xml.childNodes[ i ];
  34452. if ( child.nodeType !== 1 ) continue;
  34453. switch ( child.nodeName ) {
  34454. case 'rigid_body':
  34455. data.rigidBodies[ child.getAttribute( 'name' ) ] = {};
  34456. parsePhysicsRigidBody( child, data.rigidBodies[ child.getAttribute( 'name' ) ] );
  34457. break;
  34458. }
  34459. }
  34460. library.physicsModels[ xml.getAttribute( 'id' ) ] = data;
  34461. }
  34462. function parsePhysicsRigidBody( xml, data ) {
  34463. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  34464. var child = xml.childNodes[ i ];
  34465. if ( child.nodeType !== 1 ) continue;
  34466. switch ( child.nodeName ) {
  34467. case 'technique_common':
  34468. parsePhysicsTechniqueCommon( child, data );
  34469. break;
  34470. }
  34471. }
  34472. }
  34473. function parsePhysicsTechniqueCommon( xml, data ) {
  34474. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  34475. var child = xml.childNodes[ i ];
  34476. if ( child.nodeType !== 1 ) continue;
  34477. switch ( child.nodeName ) {
  34478. case 'inertia':
  34479. data.inertia = parseFloats( child.textContent );
  34480. break;
  34481. case 'mass':
  34482. data.mass = parseFloats( child.textContent )[0];
  34483. break;
  34484. }
  34485. }
  34486. }
  34487. // scene
  34488. function parseKinematicsScene( xml ) {
  34489. var data = {
  34490. bindJointAxis: []
  34491. };
  34492. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  34493. var child = xml.childNodes[ i ];
  34494. if ( child.nodeType !== 1 ) continue;
  34495. switch ( child.nodeName ) {
  34496. case 'bind_joint_axis':
  34497. data.bindJointAxis.push( parseKinematicsBindJointAxis( child ) );
  34498. break;
  34499. }
  34500. }
  34501. library.kinematicsScenes[ parseId( xml.getAttribute( 'url' ) ) ] = data;
  34502. }
  34503. function parseKinematicsBindJointAxis( xml ) {
  34504. var data = {
  34505. target: xml.getAttribute( 'target' ).split( '/' ).pop()
  34506. };
  34507. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  34508. var child = xml.childNodes[ i ];
  34509. if ( child.nodeType !== 1 ) continue;
  34510. switch ( child.nodeName ) {
  34511. case 'axis':
  34512. var param = child.getElementsByTagName( 'param' )[ 0 ];
  34513. data.axis = param.textContent;
  34514. var tmpJointIndex = data.axis.split( 'inst_' ).pop().split( 'axis' )[ 0 ];
  34515. data.jointIndex = tmpJointIndex.substr( 0, tmpJointIndex.length - 1 );
  34516. break;
  34517. }
  34518. }
  34519. return data;
  34520. }
  34521. function buildKinematicsScene( data ) {
  34522. if ( data.build !== undefined ) return data.build;
  34523. return data;
  34524. }
  34525. function getKinematicsScene( id ) {
  34526. return getBuild( library.kinematicsScenes[ id ], buildKinematicsScene );
  34527. }
  34528. function setupKinematics() {
  34529. var kinematicsModelId = Object.keys( library.kinematicsModels )[ 0 ];
  34530. var kinematicsSceneId = Object.keys( library.kinematicsScenes )[ 0 ];
  34531. var visualSceneId = Object.keys( library.visualScenes )[ 0 ];
  34532. if ( kinematicsModelId === undefined || kinematicsSceneId === undefined ) return;
  34533. var kinematicsModel = getKinematicsModel( kinematicsModelId );
  34534. var kinematicsScene = getKinematicsScene( kinematicsSceneId );
  34535. var visualScene = getVisualScene( visualSceneId );
  34536. var bindJointAxis = kinematicsScene.bindJointAxis;
  34537. var jointMap = {};
  34538. for ( var i = 0, l = bindJointAxis.length; i < l; i ++ ) {
  34539. var axis = bindJointAxis[ i ];
  34540. // the result of the following query is an element of type 'translate', 'rotate','scale' or 'matrix'
  34541. var targetElement = collada.querySelector( '[sid="' + axis.target + '"]' );
  34542. if ( targetElement ) {
  34543. // get the parent of the transfrom element
  34544. var parentVisualElement = targetElement.parentElement;
  34545. // connect the joint of the kinematics model with the element in the visual scene
  34546. connect( axis.jointIndex, parentVisualElement );
  34547. }
  34548. }
  34549. function connect( jointIndex, visualElement ) {
  34550. var visualElementName = visualElement.getAttribute( 'name' );
  34551. var joint = kinematicsModel.joints[ jointIndex ];
  34552. visualScene.traverse( function ( object ) {
  34553. if ( object.name === visualElementName ) {
  34554. jointMap[ jointIndex ] = {
  34555. object: object,
  34556. transforms: buildTransformList( visualElement ),
  34557. joint: joint,
  34558. position: joint.zeroPosition
  34559. };
  34560. }
  34561. } );
  34562. }
  34563. var m0 = new THREE.Matrix4();
  34564. kinematics = {
  34565. joints: kinematicsModel && kinematicsModel.joints,
  34566. getJointValue: function ( jointIndex ) {
  34567. var jointData = jointMap[ jointIndex ];
  34568. if ( jointData ) {
  34569. return jointData.position;
  34570. } else {
  34571. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' doesn\'t exist.' );
  34572. }
  34573. },
  34574. setJointValue: function ( jointIndex, value ) {
  34575. var jointData = jointMap[ jointIndex ];
  34576. if ( jointData ) {
  34577. var joint = jointData.joint;
  34578. if ( value > joint.limits.max || value < joint.limits.min ) {
  34579. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ').' );
  34580. } else if ( joint.static ) {
  34581. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' is static.' );
  34582. } else {
  34583. var object = jointData.object;
  34584. var axis = joint.axis;
  34585. var transforms = jointData.transforms;
  34586. matrix.identity();
  34587. // each update, we have to apply all transforms in the correct order
  34588. for ( var i = 0; i < transforms.length; i ++ ) {
  34589. var transform = transforms[ i ];
  34590. // if there is a connection of the transform node with a joint, apply the joint value
  34591. if ( transform.sid && transform.sid.indexOf( jointIndex ) !== - 1 ) {
  34592. switch ( joint.type ) {
  34593. case 'revolute':
  34594. matrix.multiply( m0.makeRotationAxis( axis, THREE.Math.degToRad( value ) ) );
  34595. break;
  34596. case 'prismatic':
  34597. matrix.multiply( m0.makeTranslation( axis.x * value, axis.y * value, axis.z * value ) );
  34598. break;
  34599. default:
  34600. console.warn( 'THREE.ColladaLoader: Unknown joint type: ' + joint.type );
  34601. break;
  34602. }
  34603. } else {
  34604. switch ( transform.type ) {
  34605. case 'matrix':
  34606. matrix.multiply( transform.obj );
  34607. break;
  34608. case 'translate':
  34609. matrix.multiply( m0.makeTranslation( transform.obj.x, transform.obj.y, transform.obj.z ) );
  34610. break;
  34611. case 'scale':
  34612. matrix.scale( transform.obj );
  34613. break;
  34614. case 'rotate':
  34615. matrix.multiply( m0.makeRotationAxis( transform.obj, transform.angle ) );
  34616. break;
  34617. }
  34618. }
  34619. }
  34620. object.matrix.copy( matrix );
  34621. object.matrix.decompose( object.position, object.quaternion, object.scale );
  34622. jointMap[ jointIndex ].position = value;
  34623. }
  34624. } else {
  34625. console.log( 'THREE.ColladaLoader: ' + jointIndex + ' does not exist.' );
  34626. }
  34627. }
  34628. };
  34629. }
  34630. function buildTransformList( node ) {
  34631. var transforms = [];
  34632. var xml = collada.querySelector( '[id="' + node.id + '"]' );
  34633. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  34634. var child = xml.childNodes[ i ];
  34635. if ( child.nodeType !== 1 ) continue;
  34636. switch ( child.nodeName ) {
  34637. case 'matrix':
  34638. var array = parseFloats( child.textContent );
  34639. var matrix = new THREE.Matrix4().fromArray( array ).transpose();
  34640. transforms.push( {
  34641. sid: child.getAttribute( 'sid' ),
  34642. type: child.nodeName,
  34643. obj: matrix
  34644. } );
  34645. break;
  34646. case 'translate':
  34647. case 'scale':
  34648. var array = parseFloats( child.textContent );
  34649. var vector = new THREE.Vector3().fromArray( array );
  34650. transforms.push( {
  34651. sid: child.getAttribute( 'sid' ),
  34652. type: child.nodeName,
  34653. obj: vector
  34654. } );
  34655. break;
  34656. case 'rotate':
  34657. var array = parseFloats( child.textContent );
  34658. var vector = new THREE.Vector3().fromArray( array );
  34659. var angle = THREE.Math.degToRad( array[ 3 ] );
  34660. transforms.push( {
  34661. sid: child.getAttribute( 'sid' ),
  34662. type: child.nodeName,
  34663. obj: vector,
  34664. angle: angle
  34665. } );
  34666. break;
  34667. }
  34668. }
  34669. return transforms;
  34670. }
  34671. // nodes
  34672. function prepareNodes( xml ) {
  34673. var elements = xml.getElementsByTagName( 'node' );
  34674. // ensure all node elements have id attributes
  34675. for ( var i = 0; i < elements.length; i ++ ) {
  34676. var element = elements[ i ];
  34677. if ( element.hasAttribute( 'id' ) === false ) {
  34678. element.setAttribute( 'id', generateId() );
  34679. }
  34680. }
  34681. }
  34682. var matrix = new THREE.Matrix4();
  34683. var vector = new THREE.Vector3();
  34684. function parseNode( xml ) {
  34685. var data = {
  34686. name: xml.getAttribute( 'name' ) || '',
  34687. type: xml.getAttribute( 'type' ),
  34688. id: xml.getAttribute( 'id' ),
  34689. sid: xml.getAttribute( 'sid' ),
  34690. matrix: new THREE.Matrix4(),
  34691. nodes: [],
  34692. instanceCameras: [],
  34693. instanceControllers: [],
  34694. instanceLights: [],
  34695. instanceGeometries: [],
  34696. instanceNodes: [],
  34697. transforms: {}
  34698. };
  34699. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  34700. var child = xml.childNodes[ i ];
  34701. if ( child.nodeType !== 1 ) continue;
  34702. switch ( child.nodeName ) {
  34703. case 'node':
  34704. data.nodes.push( child.getAttribute( 'id' ) );
  34705. parseNode( child );
  34706. break;
  34707. case 'instance_camera':
  34708. data.instanceCameras.push( parseId( child.getAttribute( 'url' ) ) );
  34709. break;
  34710. case 'instance_controller':
  34711. data.instanceControllers.push( parseNodeInstance( child ) );
  34712. break;
  34713. case 'instance_light':
  34714. data.instanceLights.push( parseId( child.getAttribute( 'url' ) ) );
  34715. break;
  34716. case 'instance_geometry':
  34717. data.instanceGeometries.push( parseNodeInstance( child ) );
  34718. break;
  34719. case 'instance_node':
  34720. data.instanceNodes.push( parseId( child.getAttribute( 'url' ) ) );
  34721. break;
  34722. case 'matrix':
  34723. var array = parseFloats( child.textContent );
  34724. data.matrix.multiply( matrix.fromArray( array ).transpose() );
  34725. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  34726. break;
  34727. case 'translate':
  34728. var array = parseFloats( child.textContent );
  34729. vector.fromArray( array );
  34730. data.matrix.multiply( matrix.makeTranslation( vector.x, vector.y, vector.z ) );
  34731. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  34732. break;
  34733. case 'rotate':
  34734. var array = parseFloats( child.textContent );
  34735. var angle = THREE.Math.degToRad( array[ 3 ] );
  34736. data.matrix.multiply( matrix.makeRotationAxis( vector.fromArray( array ), angle ) );
  34737. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  34738. break;
  34739. case 'scale':
  34740. var array = parseFloats( child.textContent );
  34741. data.matrix.scale( vector.fromArray( array ) );
  34742. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  34743. break;
  34744. case 'extra':
  34745. break;
  34746. default:
  34747. console.log( child );
  34748. }
  34749. }
  34750. if ( hasNode( data.id ) ) {
  34751. console.warn( 'THREE.ColladaLoader: There is already a node with ID %s. Exclude current node from further processing.', data.id );
  34752. } else {
  34753. library.nodes[ data.id ] = data;
  34754. }
  34755. return data;
  34756. }
  34757. function parseNodeInstance( xml ) {
  34758. var data = {
  34759. id: parseId( xml.getAttribute( 'url' ) ),
  34760. materials: {},
  34761. skeletons: []
  34762. };
  34763. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  34764. var child = xml.childNodes[ i ];
  34765. switch ( child.nodeName ) {
  34766. case 'bind_material':
  34767. var instances = child.getElementsByTagName( 'instance_material' );
  34768. for ( var j = 0; j < instances.length; j ++ ) {
  34769. var instance = instances[ j ];
  34770. var symbol = instance.getAttribute( 'symbol' );
  34771. var target = instance.getAttribute( 'target' );
  34772. data.materials[ symbol ] = parseId( target );
  34773. }
  34774. break;
  34775. case 'skeleton':
  34776. data.skeletons.push( parseId( child.textContent ) );
  34777. break;
  34778. default:
  34779. break;
  34780. }
  34781. }
  34782. return data;
  34783. }
  34784. function buildSkeleton( skeletons, joints ) {
  34785. var boneData = [];
  34786. var sortedBoneData = [];
  34787. var i, j, data;
  34788. // a skeleton can have multiple root bones. collada expresses this
  34789. // situtation with multiple "skeleton" tags per controller instance
  34790. for ( i = 0; i < skeletons.length; i ++ ) {
  34791. var skeleton = skeletons[ i ];
  34792. var root;
  34793. if ( hasNode( skeleton ) ) {
  34794. root = getNode( skeleton );
  34795. buildBoneHierarchy( root, joints, boneData );
  34796. } else if ( hasVisualScene( skeleton ) ) {
  34797. // handle case where the skeleton refers to the visual scene (#13335)
  34798. var visualScene = library.visualScenes[ skeleton ];
  34799. var children = visualScene.children;
  34800. for ( var j = 0; j < children.length; j ++ ) {
  34801. var child = children[ j ];
  34802. if ( child.type === 'JOINT' ) {
  34803. var root = getNode( child.id );
  34804. buildBoneHierarchy( root, joints, boneData );
  34805. }
  34806. }
  34807. } else {
  34808. console.error( 'THREE.ColladaLoader: Unable to find root bone of skeleton with ID:', skeleton );
  34809. }
  34810. }
  34811. // sort bone data (the order is defined in the corresponding controller)
  34812. for ( i = 0; i < joints.length; i ++ ) {
  34813. for ( j = 0; j < boneData.length; j ++ ) {
  34814. data = boneData[ j ];
  34815. if ( data.bone.name === joints[ i ].name ) {
  34816. sortedBoneData[ i ] = data;
  34817. data.processed = true;
  34818. break;
  34819. }
  34820. }
  34821. }
  34822. // add unprocessed bone data at the end of the list
  34823. for ( i = 0; i < boneData.length; i ++ ) {
  34824. data = boneData[ i ];
  34825. if ( data.processed === false ) {
  34826. sortedBoneData.push( data );
  34827. data.processed = true;
  34828. }
  34829. }
  34830. // setup arrays for skeleton creation
  34831. var bones = [];
  34832. var boneInverses = [];
  34833. for ( i = 0; i < sortedBoneData.length; i ++ ) {
  34834. data = sortedBoneData[ i ];
  34835. bones.push( data.bone );
  34836. boneInverses.push( data.boneInverse );
  34837. }
  34838. return new THREE.Skeleton( bones, boneInverses );
  34839. }
  34840. function buildBoneHierarchy( root, joints, boneData ) {
  34841. // setup bone data from visual scene
  34842. root.traverse( function ( object ) {
  34843. if ( object.isBone === true ) {
  34844. var boneInverse;
  34845. // retrieve the boneInverse from the controller data
  34846. for ( var i = 0; i < joints.length; i ++ ) {
  34847. var joint = joints[ i ];
  34848. if ( joint.name === object.name ) {
  34849. boneInverse = joint.boneInverse;
  34850. break;
  34851. }
  34852. }
  34853. if ( boneInverse === undefined ) {
  34854. // Unfortunately, there can be joints in the visual scene that are not part of the
  34855. // corresponding controller. In this case, we have to create a dummy boneInverse matrix
  34856. // for the respective bone. This bone won't affect any vertices, because there are no skin indices
  34857. // and weights defined for it. But we still have to add the bone to the sorted bone list in order to
  34858. // ensure a correct animation of the model.
  34859. boneInverse = new THREE.Matrix4();
  34860. }
  34861. boneData.push( { bone: object, boneInverse: boneInverse, processed: false } );
  34862. }
  34863. } );
  34864. }
  34865. function buildNode( data ) {
  34866. var objects = [];
  34867. var matrix = data.matrix;
  34868. var nodes = data.nodes;
  34869. var type = data.type;
  34870. var instanceCameras = data.instanceCameras;
  34871. var instanceControllers = data.instanceControllers;
  34872. var instanceLights = data.instanceLights;
  34873. var instanceGeometries = data.instanceGeometries;
  34874. var instanceNodes = data.instanceNodes;
  34875. // nodes
  34876. for ( var i = 0, l = nodes.length; i < l; i ++ ) {
  34877. objects.push( getNode( nodes[ i ] ) );
  34878. }
  34879. // instance cameras
  34880. for ( var i = 0, l = instanceCameras.length; i < l; i ++ ) {
  34881. var instanceCamera = getCamera( instanceCameras[ i ] );
  34882. if ( instanceCamera !== null ) {
  34883. objects.push( instanceCamera.clone() );
  34884. }
  34885. }
  34886. // instance controllers
  34887. for ( var i = 0, l = instanceControllers.length; i < l; i ++ ) {
  34888. var instance = instanceControllers[ i ];
  34889. var controller = getController( instance.id );
  34890. var geometries = getGeometry( controller.id );
  34891. var newObjects = buildObjects( geometries, instance.materials );
  34892. var skeletons = instance.skeletons;
  34893. var joints = controller.skin.joints;
  34894. var skeleton = buildSkeleton( skeletons, joints );
  34895. for ( var j = 0, jl = newObjects.length; j < jl; j ++ ) {
  34896. var object = newObjects[ j ];
  34897. if ( object.isSkinnedMesh ) {
  34898. object.bind( skeleton, controller.skin.bindMatrix );
  34899. object.normalizeSkinWeights();
  34900. }
  34901. objects.push( object );
  34902. }
  34903. }
  34904. // instance lights
  34905. for ( var i = 0, l = instanceLights.length; i < l; i ++ ) {
  34906. var instanceLight = getLight( instanceLights[ i ] );
  34907. if ( instanceLight !== null ) {
  34908. objects.push( instanceLight.clone() );
  34909. }
  34910. }
  34911. // instance geometries
  34912. for ( var i = 0, l = instanceGeometries.length; i < l; i ++ ) {
  34913. var instance = instanceGeometries[ i ];
  34914. // a single geometry instance in collada can lead to multiple object3Ds.
  34915. // this is the case when primitives are combined like triangles and lines
  34916. var geometries = getGeometry( instance.id );
  34917. var newObjects = buildObjects( geometries, instance.materials );
  34918. for ( var j = 0, jl = newObjects.length; j < jl; j ++ ) {
  34919. objects.push( newObjects[ j ] );
  34920. }
  34921. }
  34922. // instance nodes
  34923. for ( var i = 0, l = instanceNodes.length; i < l; i ++ ) {
  34924. objects.push( getNode( instanceNodes[ i ] ).clone() );
  34925. }
  34926. var object;
  34927. if ( nodes.length === 0 && objects.length === 1 ) {
  34928. object = objects[ 0 ];
  34929. } else {
  34930. object = ( type === 'JOINT' ) ? new THREE.Bone() : new THREE.Group();
  34931. for ( var i = 0; i < objects.length; i ++ ) {
  34932. object.add( objects[ i ] );
  34933. }
  34934. }
  34935. if ( object.name === '' ) {
  34936. object.name = ( type === 'JOINT' ) ? data.sid : data.name;
  34937. }
  34938. object.matrix.copy( matrix );
  34939. object.matrix.decompose( object.position, object.quaternion, object.scale );
  34940. return object;
  34941. }
  34942. var fallbackMaterial = new THREE.MeshBasicMaterial( { color: 0xff00ff } );
  34943. function resolveMaterialBinding( keys, instanceMaterials ) {
  34944. var materials = [];
  34945. for ( var i = 0, l = keys.length; i < l; i ++ ) {
  34946. var id = instanceMaterials[ keys[ i ] ];
  34947. if ( id === undefined ) {
  34948. console.warn( 'THREE.ColladaLoader: Material with key %s not found. Apply fallback material.', keys[ i ] );
  34949. materials.push( fallbackMaterial );
  34950. } else {
  34951. materials.push( getMaterial( id ) );
  34952. }
  34953. }
  34954. return materials;
  34955. }
  34956. function buildObjects( geometries, instanceMaterials ) {
  34957. var objects = [];
  34958. for ( var type in geometries ) {
  34959. var geometry = geometries[ type ];
  34960. var materials = resolveMaterialBinding( geometry.materialKeys, instanceMaterials );
  34961. // handle case if no materials are defined
  34962. if ( materials.length === 0 ) {
  34963. if ( type === 'lines' || type === 'linestrips' ) {
  34964. materials.push( new THREE.LineBasicMaterial() );
  34965. } else {
  34966. materials.push( new THREE.MeshPhongMaterial() );
  34967. }
  34968. }
  34969. // regard skinning
  34970. var skinning = ( geometry.data.attributes.skinIndex !== undefined );
  34971. if ( skinning ) {
  34972. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  34973. materials[ i ].skinning = true;
  34974. }
  34975. }
  34976. // choose between a single or multi materials (material array)
  34977. var material = ( materials.length === 1 ) ? materials[ 0 ] : materials;
  34978. // now create a specific 3D object
  34979. var object;
  34980. switch ( type ) {
  34981. case 'lines':
  34982. object = new THREE.LineSegments( geometry.data, material );
  34983. break;
  34984. case 'linestrips':
  34985. object = new THREE.Line( geometry.data, material );
  34986. break;
  34987. case 'triangles':
  34988. case 'polylist':
  34989. if ( skinning ) {
  34990. object = new THREE.SkinnedMesh( geometry.data, material );
  34991. } else {
  34992. object = new THREE.Mesh( geometry.data, material );
  34993. }
  34994. break;
  34995. }
  34996. objects.push( object );
  34997. }
  34998. return objects;
  34999. }
  35000. function hasNode( id ) {
  35001. return library.nodes[ id ] !== undefined;
  35002. }
  35003. function getNode( id ) {
  35004. return getBuild( library.nodes[ id ], buildNode );
  35005. }
  35006. // visual scenes
  35007. function parseVisualScene( xml ) {
  35008. var data = {
  35009. name: xml.getAttribute( 'name' ),
  35010. children: []
  35011. };
  35012. prepareNodes( xml );
  35013. var elements = getElementsByTagName( xml, 'node' );
  35014. for ( var i = 0; i < elements.length; i ++ ) {
  35015. data.children.push( parseNode( elements[ i ] ) );
  35016. }
  35017. library.visualScenes[ xml.getAttribute( 'id' ) ] = data;
  35018. }
  35019. function buildVisualScene( data ) {
  35020. var group = new THREE.Group();
  35021. group.name = data.name;
  35022. var children = data.children;
  35023. for ( var i = 0; i < children.length; i ++ ) {
  35024. var child = children[ i ];
  35025. group.add( getNode( child.id ) );
  35026. }
  35027. return group;
  35028. }
  35029. function hasVisualScene( id ) {
  35030. return library.visualScenes[ id ] !== undefined;
  35031. }
  35032. function getVisualScene( id ) {
  35033. return getBuild( library.visualScenes[ id ], buildVisualScene );
  35034. }
  35035. // scenes
  35036. function parseScene( xml ) {
  35037. var instance = getElementsByTagName( xml, 'instance_visual_scene' )[ 0 ];
  35038. return getVisualScene( parseId( instance.getAttribute( 'url' ) ) );
  35039. }
  35040. function setupAnimations() {
  35041. var clips = library.clips;
  35042. if ( isEmpty( clips ) === true ) {
  35043. if ( isEmpty( library.animations ) === false ) {
  35044. // if there are animations but no clips, we create a default clip for playback
  35045. var tracks = [];
  35046. for ( var id in library.animations ) {
  35047. var animationTracks = getAnimation( id );
  35048. for ( var i = 0, l = animationTracks.length; i < l; i ++ ) {
  35049. tracks.push( animationTracks[ i ] );
  35050. }
  35051. }
  35052. animations.push( new THREE.AnimationClip( 'default', - 1, tracks ) );
  35053. }
  35054. } else {
  35055. for ( var id in clips ) {
  35056. animations.push( getAnimationClip( id ) );
  35057. }
  35058. }
  35059. }
  35060. if ( text.length === 0 ) {
  35061. return { scene: new THREE.Scene() };
  35062. }
  35063. var xml = new DOMParser().parseFromString( text, 'application/xml' );
  35064. var collada = getElementsByTagName( xml, 'COLLADA' )[ 0 ];
  35065. // metadata
  35066. var version = collada.getAttribute( 'version' );
  35067. console.log( 'THREE.ColladaLoader: File version', version );
  35068. var asset = parseAsset( getElementsByTagName( collada, 'asset' )[ 0 ] );
  35069. var textureLoader = new THREE.TextureLoader( this.manager );
  35070. textureLoader.setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );
  35071. var tgaLoader;
  35072. if ( THREE.TGALoader ) {
  35073. tgaLoader = new THREE.TGALoader( this.manager );
  35074. tgaLoader.setPath( this.resourcePath || path );
  35075. }
  35076. //
  35077. var animations = [];
  35078. var kinematics = {};
  35079. var count = 0;
  35080. //
  35081. var library = {
  35082. animations: {},
  35083. clips: {},
  35084. controllers: {},
  35085. images: {},
  35086. effects: {},
  35087. materials: {},
  35088. cameras: {},
  35089. lights: {},
  35090. geometries: {},
  35091. nodes: {},
  35092. visualScenes: {},
  35093. kinematicsModels: {},
  35094. physicsModels: {},
  35095. kinematicsScenes: {}
  35096. };
  35097. parseLibrary( collada, 'library_animations', 'animation', parseAnimation );
  35098. parseLibrary( collada, 'library_animation_clips', 'animation_clip', parseAnimationClip );
  35099. parseLibrary( collada, 'library_controllers', 'controller', parseController );
  35100. parseLibrary( collada, 'library_images', 'image', parseImage );
  35101. parseLibrary( collada, 'library_effects', 'effect', parseEffect );
  35102. parseLibrary( collada, 'library_materials', 'material', parseMaterial );
  35103. parseLibrary( collada, 'library_cameras', 'camera', parseCamera );
  35104. parseLibrary( collada, 'library_lights', 'light', parseLight );
  35105. parseLibrary( collada, 'library_geometries', 'geometry', parseGeometry );
  35106. parseLibrary( collada, 'library_nodes', 'node', parseNode );
  35107. parseLibrary( collada, 'library_visual_scenes', 'visual_scene', parseVisualScene );
  35108. parseLibrary( collada, 'library_kinematics_models', 'kinematics_model', parseKinematicsModel );
  35109. parseLibrary( collada, 'library_physics_models', 'physics_model', parsePhysicsModel );
  35110. parseLibrary( collada, 'scene', 'instance_kinematics_scene', parseKinematicsScene );
  35111. buildLibrary( library.animations, buildAnimation );
  35112. buildLibrary( library.clips, buildAnimationClip );
  35113. buildLibrary( library.controllers, buildController );
  35114. buildLibrary( library.images, buildImage );
  35115. buildLibrary( library.effects, buildEffect );
  35116. buildLibrary( library.materials, buildMaterial );
  35117. buildLibrary( library.cameras, buildCamera );
  35118. buildLibrary( library.lights, buildLight );
  35119. buildLibrary( library.geometries, buildGeometry );
  35120. buildLibrary( library.visualScenes, buildVisualScene );
  35121. setupAnimations();
  35122. setupKinematics();
  35123. var scene = parseScene( getElementsByTagName( collada, 'scene' )[ 0 ] );
  35124. if ( asset.upAxis === 'Z_UP' ) {
  35125. scene.quaternion.setFromEuler( new THREE.Euler( - Math.PI / 2, 0, 0 ) );
  35126. }
  35127. scene.scale.multiplyScalar( asset.unit );
  35128. return {
  35129. animations: animations,
  35130. kinematics: kinematics,
  35131. library: library,
  35132. scene: scene
  35133. };
  35134. }
  35135. };
  35136. },{}],41:[function(_dereq_,module,exports){
  35137. // Copyright 2016 The Draco Authors.
  35138. //
  35139. // Licensed under the Apache License, Version 2.0 (the "License");
  35140. // you may not use this file except in compliance with the License.
  35141. // You may obtain a copy of the License at
  35142. //
  35143. // http://www.apache.org/licenses/LICENSE-2.0
  35144. //
  35145. // Unless required by applicable law or agreed to in writing, software
  35146. // distributed under the License is distributed on an "AS IS" BASIS,
  35147. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  35148. // See the License for the specific language governing permissions and
  35149. // limitations under the License.
  35150. //
  35151. 'use strict';
  35152. /**
  35153. * @param {THREE.LoadingManager} manager
  35154. */
  35155. THREE.DRACOLoader = function(manager) {
  35156. this.timeLoaded = 0;
  35157. this.manager = manager || THREE.DefaultLoadingManager;
  35158. this.materials = null;
  35159. this.verbosity = 0;
  35160. this.attributeOptions = {};
  35161. this.drawMode = THREE.TrianglesDrawMode;
  35162. // Native Draco attribute type to Three.JS attribute type.
  35163. this.nativeAttributeMap = {
  35164. 'position' : 'POSITION',
  35165. 'normal' : 'NORMAL',
  35166. 'color' : 'COLOR',
  35167. 'uv' : 'TEX_COORD'
  35168. };
  35169. };
  35170. THREE.DRACOLoader.prototype = {
  35171. constructor: THREE.DRACOLoader,
  35172. load: function(url, onLoad, onProgress, onError) {
  35173. var scope = this;
  35174. var loader = new THREE.FileLoader(scope.manager);
  35175. loader.setPath(this.path);
  35176. loader.setResponseType('arraybuffer');
  35177. loader.load(url, function(blob) {
  35178. scope.decodeDracoFile(blob, onLoad);
  35179. }, onProgress, onError);
  35180. },
  35181. setPath: function(value) {
  35182. this.path = value;
  35183. return this;
  35184. },
  35185. setVerbosity: function(level) {
  35186. this.verbosity = level;
  35187. return this;
  35188. },
  35189. /**
  35190. * Sets desired mode for generated geometry indices.
  35191. * Can be either:
  35192. * THREE.TrianglesDrawMode
  35193. * THREE.TriangleStripDrawMode
  35194. */
  35195. setDrawMode: function(drawMode) {
  35196. this.drawMode = drawMode;
  35197. return this;
  35198. },
  35199. /**
  35200. * Skips dequantization for a specific attribute.
  35201. * |attributeName| is the THREE.js name of the given attribute type.
  35202. * The only currently supported |attributeName| is 'position', more may be
  35203. * added in future.
  35204. */
  35205. setSkipDequantization: function(attributeName, skip) {
  35206. var skipDequantization = true;
  35207. if (typeof skip !== 'undefined')
  35208. skipDequantization = skip;
  35209. this.getAttributeOptions(attributeName).skipDequantization =
  35210. skipDequantization;
  35211. return this;
  35212. },
  35213. /**
  35214. * Decompresses a Draco buffer. Names of attributes (for ID and type maps)
  35215. * must be one of the supported three.js types, including: position, color,
  35216. * normal, uv, uv2, skinIndex, skinWeight.
  35217. *
  35218. * @param {ArrayBuffer} rawBuffer
  35219. * @param {Function} callback
  35220. * @param {Object|undefined} attributeUniqueIdMap Provides a pre-defined ID
  35221. * for each attribute in the geometry to be decoded. If given,
  35222. * `attributeTypeMap` is required and `nativeAttributeMap` will be
  35223. * ignored.
  35224. * @param {Object|undefined} attributeTypeMap Provides a predefined data
  35225. * type (as a typed array constructor) for each attribute in the
  35226. * geometry to be decoded.
  35227. */
  35228. decodeDracoFile: function(rawBuffer, callback, attributeUniqueIdMap,
  35229. attributeTypeMap) {
  35230. var scope = this;
  35231. THREE.DRACOLoader.getDecoderModule()
  35232. .then( function ( module ) {
  35233. scope.decodeDracoFileInternal( rawBuffer, module.decoder, callback,
  35234. attributeUniqueIdMap, attributeTypeMap);
  35235. });
  35236. },
  35237. decodeDracoFileInternal: function(rawBuffer, dracoDecoder, callback,
  35238. attributeUniqueIdMap, attributeTypeMap) {
  35239. /*
  35240. * Here is how to use Draco Javascript decoder and get the geometry.
  35241. */
  35242. var buffer = new dracoDecoder.DecoderBuffer();
  35243. buffer.Init(new Int8Array(rawBuffer), rawBuffer.byteLength);
  35244. var decoder = new dracoDecoder.Decoder();
  35245. /*
  35246. * Determine what type is this file: mesh or point cloud.
  35247. */
  35248. var geometryType = decoder.GetEncodedGeometryType(buffer);
  35249. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  35250. if (this.verbosity > 0) {
  35251. console.log('Loaded a mesh.');
  35252. }
  35253. } else if (geometryType == dracoDecoder.POINT_CLOUD) {
  35254. if (this.verbosity > 0) {
  35255. console.log('Loaded a point cloud.');
  35256. }
  35257. } else {
  35258. var errorMsg = 'THREE.DRACOLoader: Unknown geometry type.';
  35259. console.error(errorMsg);
  35260. throw new Error(errorMsg);
  35261. }
  35262. callback(this.convertDracoGeometryTo3JS(dracoDecoder, decoder,
  35263. geometryType, buffer, attributeUniqueIdMap, attributeTypeMap));
  35264. },
  35265. addAttributeToGeometry: function(dracoDecoder, decoder, dracoGeometry,
  35266. attributeName, attributeType, attribute,
  35267. geometry, geometryBuffer) {
  35268. if (attribute.ptr === 0) {
  35269. var errorMsg = 'THREE.DRACOLoader: No attribute ' + attributeName;
  35270. console.error(errorMsg);
  35271. throw new Error(errorMsg);
  35272. }
  35273. var numComponents = attribute.num_components();
  35274. var numPoints = dracoGeometry.num_points();
  35275. var numValues = numPoints * numComponents;
  35276. var attributeData;
  35277. var TypedBufferAttribute;
  35278. switch ( attributeType ) {
  35279. case Float32Array:
  35280. attributeData = new dracoDecoder.DracoFloat32Array();
  35281. decoder.GetAttributeFloatForAllPoints(
  35282. dracoGeometry, attribute, attributeData);
  35283. geometryBuffer[ attributeName ] = new Float32Array( numValues );
  35284. TypedBufferAttribute = THREE.Float32BufferAttribute;
  35285. break;
  35286. case Int8Array:
  35287. attributeData = new dracoDecoder.DracoInt8Array();
  35288. decoder.GetAttributeInt8ForAllPoints(
  35289. dracoGeometry, attribute, attributeData );
  35290. geometryBuffer[ attributeName ] = new Int8Array( numValues );
  35291. TypedBufferAttribute = THREE.Int8BufferAttribute;
  35292. break;
  35293. case Int16Array:
  35294. attributeData = new dracoDecoder.DracoInt16Array();
  35295. decoder.GetAttributeInt16ForAllPoints(
  35296. dracoGeometry, attribute, attributeData);
  35297. geometryBuffer[ attributeName ] = new Int16Array( numValues );
  35298. TypedBufferAttribute = THREE.Int16BufferAttribute;
  35299. break;
  35300. case Int32Array:
  35301. attributeData = new dracoDecoder.DracoInt32Array();
  35302. decoder.GetAttributeInt32ForAllPoints(
  35303. dracoGeometry, attribute, attributeData);
  35304. geometryBuffer[ attributeName ] = new Int32Array( numValues );
  35305. TypedBufferAttribute = THREE.Int32BufferAttribute;
  35306. break;
  35307. case Uint8Array:
  35308. attributeData = new dracoDecoder.DracoUInt8Array();
  35309. decoder.GetAttributeUInt8ForAllPoints(
  35310. dracoGeometry, attribute, attributeData);
  35311. geometryBuffer[ attributeName ] = new Uint8Array( numValues );
  35312. TypedBufferAttribute = THREE.Uint8BufferAttribute;
  35313. break;
  35314. case Uint16Array:
  35315. attributeData = new dracoDecoder.DracoUInt16Array();
  35316. decoder.GetAttributeUInt16ForAllPoints(
  35317. dracoGeometry, attribute, attributeData);
  35318. geometryBuffer[ attributeName ] = new Uint16Array( numValues );
  35319. TypedBufferAttribute = THREE.Uint16BufferAttribute;
  35320. break;
  35321. case Uint32Array:
  35322. attributeData = new dracoDecoder.DracoUInt32Array();
  35323. decoder.GetAttributeUInt32ForAllPoints(
  35324. dracoGeometry, attribute, attributeData);
  35325. geometryBuffer[ attributeName ] = new Uint32Array( numValues );
  35326. TypedBufferAttribute = THREE.Uint32BufferAttribute;
  35327. break;
  35328. default:
  35329. var errorMsg = 'THREE.DRACOLoader: Unexpected attribute type.';
  35330. console.error( errorMsg );
  35331. throw new Error( errorMsg );
  35332. }
  35333. // Copy data from decoder.
  35334. for (var i = 0; i < numValues; i++) {
  35335. geometryBuffer[attributeName][i] = attributeData.GetValue(i);
  35336. }
  35337. // Add attribute to THREEJS geometry for rendering.
  35338. geometry.addAttribute(attributeName,
  35339. new TypedBufferAttribute(geometryBuffer[attributeName],
  35340. numComponents));
  35341. dracoDecoder.destroy(attributeData);
  35342. },
  35343. convertDracoGeometryTo3JS: function(dracoDecoder, decoder, geometryType,
  35344. buffer, attributeUniqueIdMap,
  35345. attributeTypeMap) {
  35346. // TODO: Should not assume native Draco attribute IDs apply.
  35347. if (this.getAttributeOptions('position').skipDequantization === true) {
  35348. decoder.SkipAttributeTransform(dracoDecoder.POSITION);
  35349. }
  35350. var dracoGeometry;
  35351. var decodingStatus;
  35352. var start_time = performance.now();
  35353. if (geometryType === dracoDecoder.TRIANGULAR_MESH) {
  35354. dracoGeometry = new dracoDecoder.Mesh();
  35355. decodingStatus = decoder.DecodeBufferToMesh(buffer, dracoGeometry);
  35356. } else {
  35357. dracoGeometry = new dracoDecoder.PointCloud();
  35358. decodingStatus =
  35359. decoder.DecodeBufferToPointCloud(buffer, dracoGeometry);
  35360. }
  35361. if (!decodingStatus.ok() || dracoGeometry.ptr == 0) {
  35362. var errorMsg = 'THREE.DRACOLoader: Decoding failed: ';
  35363. errorMsg += decodingStatus.error_msg();
  35364. console.error(errorMsg);
  35365. dracoDecoder.destroy(decoder);
  35366. dracoDecoder.destroy(dracoGeometry);
  35367. throw new Error(errorMsg);
  35368. }
  35369. var decode_end = performance.now();
  35370. dracoDecoder.destroy(buffer);
  35371. /*
  35372. * Example on how to retrieve mesh and attributes.
  35373. */
  35374. var numFaces;
  35375. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  35376. numFaces = dracoGeometry.num_faces();
  35377. if (this.verbosity > 0) {
  35378. console.log('Number of faces loaded: ' + numFaces.toString());
  35379. }
  35380. } else {
  35381. numFaces = 0;
  35382. }
  35383. var numPoints = dracoGeometry.num_points();
  35384. var numAttributes = dracoGeometry.num_attributes();
  35385. if (this.verbosity > 0) {
  35386. console.log('Number of points loaded: ' + numPoints.toString());
  35387. console.log('Number of attributes loaded: ' +
  35388. numAttributes.toString());
  35389. }
  35390. // Verify if there is position attribute.
  35391. // TODO: Should not assume native Draco attribute IDs apply.
  35392. var posAttId = decoder.GetAttributeId(dracoGeometry,
  35393. dracoDecoder.POSITION);
  35394. if (posAttId == -1) {
  35395. var errorMsg = 'THREE.DRACOLoader: No position attribute found.';
  35396. console.error(errorMsg);
  35397. dracoDecoder.destroy(decoder);
  35398. dracoDecoder.destroy(dracoGeometry);
  35399. throw new Error(errorMsg);
  35400. }
  35401. var posAttribute = decoder.GetAttribute(dracoGeometry, posAttId);
  35402. // Structure for converting to THREEJS geometry later.
  35403. var geometryBuffer = {};
  35404. // Import data to Three JS geometry.
  35405. var geometry = new THREE.BufferGeometry();
  35406. // Do not use both the native attribute map and a provided (e.g. glTF) map.
  35407. if ( attributeUniqueIdMap ) {
  35408. // Add attributes of user specified unique id. E.g. GLTF models.
  35409. for (var attributeName in attributeUniqueIdMap) {
  35410. var attributeType = attributeTypeMap[attributeName];
  35411. var attributeId = attributeUniqueIdMap[attributeName];
  35412. var attribute = decoder.GetAttributeByUniqueId(dracoGeometry,
  35413. attributeId);
  35414. this.addAttributeToGeometry(dracoDecoder, decoder, dracoGeometry,
  35415. attributeName, attributeType, attribute, geometry, geometryBuffer);
  35416. }
  35417. } else {
  35418. // Add native Draco attribute type to geometry.
  35419. for (var attributeName in this.nativeAttributeMap) {
  35420. var attId = decoder.GetAttributeId(dracoGeometry,
  35421. dracoDecoder[this.nativeAttributeMap[attributeName]]);
  35422. if (attId !== -1) {
  35423. if (this.verbosity > 0) {
  35424. console.log('Loaded ' + attributeName + ' attribute.');
  35425. }
  35426. var attribute = decoder.GetAttribute(dracoGeometry, attId);
  35427. this.addAttributeToGeometry(dracoDecoder, decoder, dracoGeometry,
  35428. attributeName, Float32Array, attribute, geometry, geometryBuffer);
  35429. }
  35430. }
  35431. }
  35432. // For mesh, we need to generate the faces.
  35433. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  35434. if (this.drawMode === THREE.TriangleStripDrawMode) {
  35435. var stripsArray = new dracoDecoder.DracoInt32Array();
  35436. var numStrips = decoder.GetTriangleStripsFromMesh(
  35437. dracoGeometry, stripsArray);
  35438. geometryBuffer.indices = new Uint32Array(stripsArray.size());
  35439. for (var i = 0; i < stripsArray.size(); ++i) {
  35440. geometryBuffer.indices[i] = stripsArray.GetValue(i);
  35441. }
  35442. dracoDecoder.destroy(stripsArray);
  35443. } else {
  35444. var numIndices = numFaces * 3;
  35445. geometryBuffer.indices = new Uint32Array(numIndices);
  35446. var ia = new dracoDecoder.DracoInt32Array();
  35447. for (var i = 0; i < numFaces; ++i) {
  35448. decoder.GetFaceFromMesh(dracoGeometry, i, ia);
  35449. var index = i * 3;
  35450. geometryBuffer.indices[index] = ia.GetValue(0);
  35451. geometryBuffer.indices[index + 1] = ia.GetValue(1);
  35452. geometryBuffer.indices[index + 2] = ia.GetValue(2);
  35453. }
  35454. dracoDecoder.destroy(ia);
  35455. }
  35456. }
  35457. geometry.drawMode = this.drawMode;
  35458. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  35459. geometry.setIndex(new(geometryBuffer.indices.length > 65535 ?
  35460. THREE.Uint32BufferAttribute : THREE.Uint16BufferAttribute)
  35461. (geometryBuffer.indices, 1));
  35462. }
  35463. // TODO: Should not assume native Draco attribute IDs apply.
  35464. // TODO: Can other attribute types be quantized?
  35465. var posTransform = new dracoDecoder.AttributeQuantizationTransform();
  35466. if (posTransform.InitFromAttribute(posAttribute)) {
  35467. // Quantized attribute. Store the quantization parameters into the
  35468. // THREE.js attribute.
  35469. geometry.attributes['position'].isQuantized = true;
  35470. geometry.attributes['position'].maxRange = posTransform.range();
  35471. geometry.attributes['position'].numQuantizationBits =
  35472. posTransform.quantization_bits();
  35473. geometry.attributes['position'].minValues = new Float32Array(3);
  35474. for (var i = 0; i < 3; ++i) {
  35475. geometry.attributes['position'].minValues[i] =
  35476. posTransform.min_value(i);
  35477. }
  35478. }
  35479. dracoDecoder.destroy(posTransform);
  35480. dracoDecoder.destroy(decoder);
  35481. dracoDecoder.destroy(dracoGeometry);
  35482. this.decode_time = decode_end - start_time;
  35483. this.import_time = performance.now() - decode_end;
  35484. if (this.verbosity > 0) {
  35485. console.log('Decode time: ' + this.decode_time);
  35486. console.log('Import time: ' + this.import_time);
  35487. }
  35488. return geometry;
  35489. },
  35490. isVersionSupported: function(version, callback) {
  35491. THREE.DRACOLoader.getDecoderModule()
  35492. .then( function ( module ) {
  35493. callback( module.decoder.isVersionSupported( version ) );
  35494. });
  35495. },
  35496. getAttributeOptions: function(attributeName) {
  35497. if (typeof this.attributeOptions[attributeName] === 'undefined')
  35498. this.attributeOptions[attributeName] = {};
  35499. return this.attributeOptions[attributeName];
  35500. }
  35501. };
  35502. THREE.DRACOLoader.decoderPath = './';
  35503. THREE.DRACOLoader.decoderConfig = {};
  35504. THREE.DRACOLoader.decoderModulePromise = null;
  35505. /**
  35506. * Sets the base path for decoder source files.
  35507. * @param {string} path
  35508. */
  35509. THREE.DRACOLoader.setDecoderPath = function ( path ) {
  35510. THREE.DRACOLoader.decoderPath = path;
  35511. };
  35512. /**
  35513. * Sets decoder configuration and releases singleton decoder module. Module
  35514. * will be recreated with the next decoding call.
  35515. * @param {Object} config
  35516. */
  35517. THREE.DRACOLoader.setDecoderConfig = function ( config ) {
  35518. var wasmBinary = THREE.DRACOLoader.decoderConfig.wasmBinary;
  35519. THREE.DRACOLoader.decoderConfig = config || {};
  35520. THREE.DRACOLoader.releaseDecoderModule();
  35521. // Reuse WASM binary.
  35522. if ( wasmBinary ) THREE.DRACOLoader.decoderConfig.wasmBinary = wasmBinary;
  35523. };
  35524. /**
  35525. * Releases the singleton DracoDecoderModule instance. Module will be recreated
  35526. * with the next decoding call.
  35527. */
  35528. THREE.DRACOLoader.releaseDecoderModule = function () {
  35529. THREE.DRACOLoader.decoderModulePromise = null;
  35530. };
  35531. /**
  35532. * Gets WebAssembly or asm.js singleton instance of DracoDecoderModule
  35533. * after testing for browser support. Returns Promise that resolves when
  35534. * module is available.
  35535. * @return {Promise<{decoder: DracoDecoderModule}>}
  35536. */
  35537. THREE.DRACOLoader.getDecoderModule = function () {
  35538. var scope = this;
  35539. var path = THREE.DRACOLoader.decoderPath;
  35540. var config = THREE.DRACOLoader.decoderConfig;
  35541. var promise = THREE.DRACOLoader.decoderModulePromise;
  35542. if ( promise ) return promise;
  35543. // Load source files.
  35544. if ( typeof DracoDecoderModule !== 'undefined' ) {
  35545. // Loaded externally.
  35546. promise = Promise.resolve();
  35547. } else if ( typeof WebAssembly !== 'object' || config.type === 'js' ) {
  35548. // Load with asm.js.
  35549. promise = THREE.DRACOLoader._loadScript( path + 'draco_decoder.js' );
  35550. } else {
  35551. // Load with WebAssembly.
  35552. config.wasmBinaryFile = path + 'draco_decoder.wasm';
  35553. promise = THREE.DRACOLoader._loadScript( path + 'draco_wasm_wrapper.js' )
  35554. .then( function () {
  35555. return THREE.DRACOLoader._loadArrayBuffer( config.wasmBinaryFile );
  35556. } )
  35557. .then( function ( wasmBinary ) {
  35558. config.wasmBinary = wasmBinary;
  35559. } );
  35560. }
  35561. // Wait for source files, then create and return a decoder.
  35562. promise = promise.then( function () {
  35563. return new Promise( function ( resolve ) {
  35564. config.onModuleLoaded = function ( decoder ) {
  35565. scope.timeLoaded = performance.now();
  35566. // Module is Promise-like. Wrap before resolving to avoid loop.
  35567. resolve( { decoder: decoder } );
  35568. };
  35569. DracoDecoderModule( config );
  35570. } );
  35571. } );
  35572. THREE.DRACOLoader.decoderModulePromise = promise;
  35573. return promise;
  35574. };
  35575. /**
  35576. * @param {string} src
  35577. * @return {Promise}
  35578. */
  35579. THREE.DRACOLoader._loadScript = function ( src ) {
  35580. var prevScript = document.getElementById( 'decoder_script' );
  35581. if ( prevScript !== null ) {
  35582. prevScript.parentNode.removeChild( prevScript );
  35583. }
  35584. var head = document.getElementsByTagName( 'head' )[ 0 ];
  35585. var script = document.createElement( 'script' );
  35586. script.id = 'decoder_script';
  35587. script.type = 'text/javascript';
  35588. script.src = src;
  35589. return new Promise( function ( resolve ) {
  35590. script.onload = resolve;
  35591. head.appendChild( script );
  35592. });
  35593. };
  35594. /**
  35595. * @param {string} src
  35596. * @return {Promise}
  35597. */
  35598. THREE.DRACOLoader._loadArrayBuffer = function ( src ) {
  35599. var loader = new THREE.FileLoader();
  35600. loader.setResponseType( 'arraybuffer' );
  35601. return new Promise( function( resolve, reject ) {
  35602. loader.load( src, resolve, undefined, reject );
  35603. });
  35604. };
  35605. },{}],42:[function(_dereq_,module,exports){
  35606. /**
  35607. * @author Rich Tibbett / https://github.com/richtr
  35608. * @author mrdoob / http://mrdoob.com/
  35609. * @author Tony Parisi / http://www.tonyparisi.com/
  35610. * @author Takahiro / https://github.com/takahirox
  35611. * @author Don McCurdy / https://www.donmccurdy.com
  35612. */
  35613. THREE.GLTFLoader = ( function () {
  35614. function GLTFLoader( manager ) {
  35615. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  35616. this.dracoLoader = null;
  35617. }
  35618. GLTFLoader.prototype = {
  35619. constructor: GLTFLoader,
  35620. crossOrigin: 'anonymous',
  35621. load: function ( url, onLoad, onProgress, onError ) {
  35622. var scope = this;
  35623. var resourcePath;
  35624. if ( this.resourcePath !== undefined ) {
  35625. resourcePath = this.resourcePath;
  35626. } else if ( this.path !== undefined ) {
  35627. resourcePath = this.path;
  35628. } else {
  35629. resourcePath = THREE.LoaderUtils.extractUrlBase( url );
  35630. }
  35631. // Tells the LoadingManager to track an extra item, which resolves after
  35632. // the model is fully loaded. This means the count of items loaded will
  35633. // be incorrect, but ensures manager.onLoad() does not fire early.
  35634. scope.manager.itemStart( url );
  35635. var _onError = function ( e ) {
  35636. if ( onError ) {
  35637. onError( e );
  35638. } else {
  35639. console.error( e );
  35640. }
  35641. scope.manager.itemError( url );
  35642. scope.manager.itemEnd( url );
  35643. };
  35644. var loader = new THREE.FileLoader( scope.manager );
  35645. loader.setPath( this.path );
  35646. loader.setResponseType( 'arraybuffer' );
  35647. loader.load( url, function ( data ) {
  35648. try {
  35649. scope.parse( data, resourcePath, function ( gltf ) {
  35650. onLoad( gltf );
  35651. scope.manager.itemEnd( url );
  35652. }, _onError );
  35653. } catch ( e ) {
  35654. _onError( e );
  35655. }
  35656. }, onProgress, _onError );
  35657. },
  35658. setCrossOrigin: function ( value ) {
  35659. this.crossOrigin = value;
  35660. return this;
  35661. },
  35662. setPath: function ( value ) {
  35663. this.path = value;
  35664. return this;
  35665. },
  35666. setResourcePath: function ( value ) {
  35667. this.resourcePath = value;
  35668. return this;
  35669. },
  35670. setDRACOLoader: function ( dracoLoader ) {
  35671. this.dracoLoader = dracoLoader;
  35672. return this;
  35673. },
  35674. parse: function ( data, path, onLoad, onError ) {
  35675. var content;
  35676. var extensions = {};
  35677. if ( typeof data === 'string' ) {
  35678. content = data;
  35679. } else {
  35680. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  35681. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  35682. try {
  35683. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  35684. } catch ( error ) {
  35685. if ( onError ) onError( error );
  35686. return;
  35687. }
  35688. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  35689. } else {
  35690. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  35691. }
  35692. }
  35693. var json = JSON.parse( content );
  35694. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  35695. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.' ) );
  35696. return;
  35697. }
  35698. if ( json.extensionsUsed ) {
  35699. for ( var i = 0; i < json.extensionsUsed.length; ++ i ) {
  35700. var extensionName = json.extensionsUsed[ i ];
  35701. var extensionsRequired = json.extensionsRequired || [];
  35702. switch ( extensionName ) {
  35703. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  35704. extensions[ extensionName ] = new GLTFLightsExtension( json );
  35705. break;
  35706. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  35707. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension( json );
  35708. break;
  35709. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  35710. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension( json );
  35711. break;
  35712. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  35713. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  35714. break;
  35715. case EXTENSIONS.MSFT_TEXTURE_DDS:
  35716. extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] = new GLTFTextureDDSExtension( json );
  35717. break;
  35718. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  35719. extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] = new GLTFTextureTransformExtension( json );
  35720. break;
  35721. default:
  35722. if ( extensionsRequired.indexOf( extensionName ) >= 0 ) {
  35723. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  35724. }
  35725. }
  35726. }
  35727. }
  35728. var parser = new GLTFParser( json, extensions, {
  35729. path: path || this.resourcePath || '',
  35730. crossOrigin: this.crossOrigin,
  35731. manager: this.manager
  35732. } );
  35733. parser.parse( function ( scene, scenes, cameras, animations, json ) {
  35734. var glTF = {
  35735. scene: scene,
  35736. scenes: scenes,
  35737. cameras: cameras,
  35738. animations: animations,
  35739. asset: json.asset,
  35740. parser: parser,
  35741. userData: {}
  35742. };
  35743. addUnknownExtensionsToUserData( extensions, glTF, json );
  35744. onLoad( glTF );
  35745. }, onError );
  35746. }
  35747. };
  35748. /* GLTFREGISTRY */
  35749. function GLTFRegistry() {
  35750. var objects = {};
  35751. return {
  35752. get: function ( key ) {
  35753. return objects[ key ];
  35754. },
  35755. add: function ( key, object ) {
  35756. objects[ key ] = object;
  35757. },
  35758. remove: function ( key ) {
  35759. delete objects[ key ];
  35760. },
  35761. removeAll: function () {
  35762. objects = {};
  35763. }
  35764. };
  35765. }
  35766. /*********************************/
  35767. /********** EXTENSIONS ***********/
  35768. /*********************************/
  35769. var EXTENSIONS = {
  35770. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  35771. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  35772. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  35773. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  35774. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  35775. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  35776. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  35777. };
  35778. /**
  35779. * DDS Texture Extension
  35780. *
  35781. * Specification:
  35782. * https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  35783. *
  35784. */
  35785. function GLTFTextureDDSExtension() {
  35786. if ( ! THREE.DDSLoader ) {
  35787. throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' );
  35788. }
  35789. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  35790. this.ddsLoader = new THREE.DDSLoader();
  35791. }
  35792. /**
  35793. * Lights Extension
  35794. *
  35795. * Specification: PENDING
  35796. */
  35797. function GLTFLightsExtension( json ) {
  35798. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  35799. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ] ) || {};
  35800. this.lightDefs = extension.lights || [];
  35801. }
  35802. GLTFLightsExtension.prototype.loadLight = function ( lightIndex ) {
  35803. var lightDef = this.lightDefs[ lightIndex ];
  35804. var lightNode;
  35805. var color = new THREE.Color( 0xffffff );
  35806. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  35807. var range = lightDef.range !== undefined ? lightDef.range : 0;
  35808. switch ( lightDef.type ) {
  35809. case 'directional':
  35810. lightNode = new THREE.DirectionalLight( color );
  35811. lightNode.target.position.set( 0, 0, -1 );
  35812. lightNode.add( lightNode.target );
  35813. break;
  35814. case 'point':
  35815. lightNode = new THREE.PointLight( color );
  35816. lightNode.distance = range;
  35817. break;
  35818. case 'spot':
  35819. lightNode = new THREE.SpotLight( color );
  35820. lightNode.distance = range;
  35821. // Handle spotlight properties.
  35822. lightDef.spot = lightDef.spot || {};
  35823. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  35824. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  35825. lightNode.angle = lightDef.spot.outerConeAngle;
  35826. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  35827. lightNode.target.position.set( 0, 0, -1 );
  35828. lightNode.add( lightNode.target );
  35829. break;
  35830. default:
  35831. throw new Error( 'THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".' );
  35832. }
  35833. lightNode.decay = 2;
  35834. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  35835. lightNode.name = lightDef.name || ( 'light_' + lightIndex );
  35836. return Promise.resolve( lightNode );
  35837. };
  35838. /**
  35839. * Unlit Materials Extension (pending)
  35840. *
  35841. * PR: https://github.com/KhronosGroup/glTF/pull/1163
  35842. */
  35843. function GLTFMaterialsUnlitExtension( json ) {
  35844. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  35845. }
  35846. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function ( material ) {
  35847. return THREE.MeshBasicMaterial;
  35848. };
  35849. GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, material, parser ) {
  35850. var pending = [];
  35851. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  35852. materialParams.opacity = 1.0;
  35853. var metallicRoughness = material.pbrMetallicRoughness;
  35854. if ( metallicRoughness ) {
  35855. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  35856. var array = metallicRoughness.baseColorFactor;
  35857. materialParams.color.fromArray( array );
  35858. materialParams.opacity = array[ 3 ];
  35859. }
  35860. if ( metallicRoughness.baseColorTexture !== undefined ) {
  35861. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  35862. }
  35863. }
  35864. return Promise.all( pending );
  35865. };
  35866. /* BINARY EXTENSION */
  35867. var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF';
  35868. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  35869. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  35870. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  35871. function GLTFBinaryExtension( data ) {
  35872. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  35873. this.content = null;
  35874. this.body = null;
  35875. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  35876. this.header = {
  35877. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  35878. version: headerView.getUint32( 4, true ),
  35879. length: headerView.getUint32( 8, true )
  35880. };
  35881. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  35882. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  35883. } else if ( this.header.version < 2.0 ) {
  35884. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.' );
  35885. }
  35886. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  35887. var chunkIndex = 0;
  35888. while ( chunkIndex < chunkView.byteLength ) {
  35889. var chunkLength = chunkView.getUint32( chunkIndex, true );
  35890. chunkIndex += 4;
  35891. var chunkType = chunkView.getUint32( chunkIndex, true );
  35892. chunkIndex += 4;
  35893. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  35894. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  35895. this.content = THREE.LoaderUtils.decodeText( contentArray );
  35896. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  35897. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  35898. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  35899. }
  35900. // Clients must ignore chunks with unknown types.
  35901. chunkIndex += chunkLength;
  35902. }
  35903. if ( this.content === null ) {
  35904. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  35905. }
  35906. }
  35907. /**
  35908. * DRACO Mesh Compression Extension
  35909. *
  35910. * Specification: https://github.com/KhronosGroup/glTF/pull/874
  35911. */
  35912. function GLTFDracoMeshCompressionExtension( json, dracoLoader ) {
  35913. if ( ! dracoLoader ) {
  35914. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  35915. }
  35916. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  35917. this.json = json;
  35918. this.dracoLoader = dracoLoader;
  35919. THREE.DRACOLoader.getDecoderModule();
  35920. }
  35921. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) {
  35922. var json = this.json;
  35923. var dracoLoader = this.dracoLoader;
  35924. var bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  35925. var gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  35926. var threeAttributeMap = {};
  35927. var attributeNormalizedMap = {};
  35928. var attributeTypeMap = {};
  35929. for ( var attributeName in gltfAttributeMap ) {
  35930. if ( ! ( attributeName in ATTRIBUTES ) ) continue;
  35931. threeAttributeMap[ ATTRIBUTES[ attributeName ] ] = gltfAttributeMap[ attributeName ];
  35932. }
  35933. for ( attributeName in primitive.attributes ) {
  35934. if ( ATTRIBUTES[ attributeName ] !== undefined && gltfAttributeMap[ attributeName ] !== undefined ) {
  35935. var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  35936. var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  35937. attributeTypeMap[ ATTRIBUTES[ attributeName ] ] = componentType;
  35938. attributeNormalizedMap[ ATTRIBUTES[ attributeName ] ] = accessorDef.normalized === true;
  35939. }
  35940. }
  35941. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  35942. return new Promise( function ( resolve ) {
  35943. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  35944. for ( var attributeName in geometry.attributes ) {
  35945. var attribute = geometry.attributes[ attributeName ];
  35946. var normalized = attributeNormalizedMap[ attributeName ];
  35947. if ( normalized !== undefined ) attribute.normalized = normalized;
  35948. }
  35949. resolve( geometry );
  35950. }, threeAttributeMap, attributeTypeMap );
  35951. } );
  35952. } );
  35953. };
  35954. /**
  35955. * Texture Transform Extension
  35956. *
  35957. * Specification:
  35958. */
  35959. function GLTFTextureTransformExtension( json ) {
  35960. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  35961. }
  35962. GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) {
  35963. texture = texture.clone();
  35964. if ( transform.offset !== undefined ) {
  35965. texture.offset.fromArray( transform.offset );
  35966. }
  35967. if ( transform.rotation !== undefined ) {
  35968. texture.rotation = transform.rotation;
  35969. }
  35970. if ( transform.scale !== undefined ) {
  35971. texture.repeat.fromArray( transform.scale );
  35972. }
  35973. if ( transform.texCoord !== undefined ) {
  35974. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  35975. }
  35976. texture.needsUpdate = true;
  35977. return texture;
  35978. };
  35979. /**
  35980. * Specular-Glossiness Extension
  35981. *
  35982. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  35983. */
  35984. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  35985. return {
  35986. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  35987. specularGlossinessParams: [
  35988. 'color',
  35989. 'map',
  35990. 'lightMap',
  35991. 'lightMapIntensity',
  35992. 'aoMap',
  35993. 'aoMapIntensity',
  35994. 'emissive',
  35995. 'emissiveIntensity',
  35996. 'emissiveMap',
  35997. 'bumpMap',
  35998. 'bumpScale',
  35999. 'normalMap',
  36000. 'displacementMap',
  36001. 'displacementScale',
  36002. 'displacementBias',
  36003. 'specularMap',
  36004. 'specular',
  36005. 'glossinessMap',
  36006. 'glossiness',
  36007. 'alphaMap',
  36008. 'envMap',
  36009. 'envMapIntensity',
  36010. 'refractionRatio',
  36011. ],
  36012. getMaterialType: function () {
  36013. return THREE.ShaderMaterial;
  36014. },
  36015. extendParams: function ( params, material, parser ) {
  36016. var pbrSpecularGlossiness = material.extensions[ this.name ];
  36017. var shader = THREE.ShaderLib[ 'standard' ];
  36018. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  36019. var specularMapParsFragmentChunk = [
  36020. '#ifdef USE_SPECULARMAP',
  36021. ' uniform sampler2D specularMap;',
  36022. '#endif'
  36023. ].join( '\n' );
  36024. var glossinessMapParsFragmentChunk = [
  36025. '#ifdef USE_GLOSSINESSMAP',
  36026. ' uniform sampler2D glossinessMap;',
  36027. '#endif'
  36028. ].join( '\n' );
  36029. var specularMapFragmentChunk = [
  36030. 'vec3 specularFactor = specular;',
  36031. '#ifdef USE_SPECULARMAP',
  36032. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  36033. ' texelSpecular = sRGBToLinear( texelSpecular );',
  36034. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  36035. ' specularFactor *= texelSpecular.rgb;',
  36036. '#endif'
  36037. ].join( '\n' );
  36038. var glossinessMapFragmentChunk = [
  36039. 'float glossinessFactor = glossiness;',
  36040. '#ifdef USE_GLOSSINESSMAP',
  36041. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  36042. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  36043. ' glossinessFactor *= texelGlossiness.a;',
  36044. '#endif'
  36045. ].join( '\n' );
  36046. var lightPhysicalFragmentChunk = [
  36047. 'PhysicalMaterial material;',
  36048. 'material.diffuseColor = diffuseColor.rgb;',
  36049. 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );',
  36050. 'material.specularColor = specularFactor.rgb;',
  36051. ].join( '\n' );
  36052. var fragmentShader = shader.fragmentShader
  36053. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  36054. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  36055. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  36056. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  36057. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  36058. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  36059. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  36060. delete uniforms.roughness;
  36061. delete uniforms.metalness;
  36062. delete uniforms.roughnessMap;
  36063. delete uniforms.metalnessMap;
  36064. uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) };
  36065. uniforms.glossiness = { value: 0.5 };
  36066. uniforms.specularMap = { value: null };
  36067. uniforms.glossinessMap = { value: null };
  36068. params.vertexShader = shader.vertexShader;
  36069. params.fragmentShader = fragmentShader;
  36070. params.uniforms = uniforms;
  36071. params.defines = { 'STANDARD': '' };
  36072. params.color = new THREE.Color( 1.0, 1.0, 1.0 );
  36073. params.opacity = 1.0;
  36074. var pending = [];
  36075. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  36076. var array = pbrSpecularGlossiness.diffuseFactor;
  36077. params.color.fromArray( array );
  36078. params.opacity = array[ 3 ];
  36079. }
  36080. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  36081. pending.push( parser.assignTexture( params, 'map', pbrSpecularGlossiness.diffuseTexture ) );
  36082. }
  36083. params.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  36084. params.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  36085. params.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  36086. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  36087. params.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  36088. }
  36089. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  36090. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  36091. pending.push( parser.assignTexture( params, 'glossinessMap', specGlossMapDef ) );
  36092. pending.push( parser.assignTexture( params, 'specularMap', specGlossMapDef ) );
  36093. }
  36094. return Promise.all( pending );
  36095. },
  36096. createMaterial: function ( params ) {
  36097. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  36098. var material = new THREE.ShaderMaterial( {
  36099. defines: params.defines,
  36100. vertexShader: params.vertexShader,
  36101. fragmentShader: params.fragmentShader,
  36102. uniforms: params.uniforms,
  36103. fog: true,
  36104. lights: true,
  36105. opacity: params.opacity,
  36106. transparent: params.transparent
  36107. } );
  36108. material.isGLTFSpecularGlossinessMaterial = true;
  36109. material.color = params.color;
  36110. material.map = params.map === undefined ? null : params.map;
  36111. material.lightMap = null;
  36112. material.lightMapIntensity = 1.0;
  36113. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  36114. material.aoMapIntensity = 1.0;
  36115. material.emissive = params.emissive;
  36116. material.emissiveIntensity = 1.0;
  36117. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  36118. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  36119. material.bumpScale = 1;
  36120. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  36121. if ( params.normalScale ) material.normalScale = params.normalScale;
  36122. material.displacementMap = null;
  36123. material.displacementScale = 1;
  36124. material.displacementBias = 0;
  36125. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  36126. material.specular = params.specular;
  36127. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  36128. material.glossiness = params.glossiness;
  36129. material.alphaMap = null;
  36130. material.envMap = params.envMap === undefined ? null : params.envMap;
  36131. material.envMapIntensity = 1.0;
  36132. material.refractionRatio = 0.98;
  36133. material.extensions.derivatives = true;
  36134. return material;
  36135. },
  36136. /**
  36137. * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can
  36138. * copy only properties it knows about or inherits, and misses many properties that would
  36139. * normally be defined by MeshStandardMaterial.
  36140. *
  36141. * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of
  36142. * loading a glTF model, but cloning later (e.g. by the user) would require these changes
  36143. * AND also updating `.onBeforeRender` on the parent mesh.
  36144. *
  36145. * @param {THREE.ShaderMaterial} source
  36146. * @return {THREE.ShaderMaterial}
  36147. */
  36148. cloneMaterial: function ( source ) {
  36149. var target = source.clone();
  36150. target.isGLTFSpecularGlossinessMaterial = true;
  36151. var params = this.specularGlossinessParams;
  36152. for ( var i = 0, il = params.length; i < il; i ++ ) {
  36153. target[ params[ i ] ] = source[ params[ i ] ];
  36154. }
  36155. return target;
  36156. },
  36157. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  36158. refreshUniforms: function ( renderer, scene, camera, geometry, material, group ) {
  36159. if ( material.isGLTFSpecularGlossinessMaterial !== true ) {
  36160. return;
  36161. }
  36162. var uniforms = material.uniforms;
  36163. var defines = material.defines;
  36164. uniforms.opacity.value = material.opacity;
  36165. uniforms.diffuse.value.copy( material.color );
  36166. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  36167. uniforms.map.value = material.map;
  36168. uniforms.specularMap.value = material.specularMap;
  36169. uniforms.alphaMap.value = material.alphaMap;
  36170. uniforms.lightMap.value = material.lightMap;
  36171. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  36172. uniforms.aoMap.value = material.aoMap;
  36173. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  36174. // uv repeat and offset setting priorities
  36175. // 1. color map
  36176. // 2. specular map
  36177. // 3. normal map
  36178. // 4. bump map
  36179. // 5. alpha map
  36180. // 6. emissive map
  36181. var uvScaleMap;
  36182. if ( material.map ) {
  36183. uvScaleMap = material.map;
  36184. } else if ( material.specularMap ) {
  36185. uvScaleMap = material.specularMap;
  36186. } else if ( material.displacementMap ) {
  36187. uvScaleMap = material.displacementMap;
  36188. } else if ( material.normalMap ) {
  36189. uvScaleMap = material.normalMap;
  36190. } else if ( material.bumpMap ) {
  36191. uvScaleMap = material.bumpMap;
  36192. } else if ( material.glossinessMap ) {
  36193. uvScaleMap = material.glossinessMap;
  36194. } else if ( material.alphaMap ) {
  36195. uvScaleMap = material.alphaMap;
  36196. } else if ( material.emissiveMap ) {
  36197. uvScaleMap = material.emissiveMap;
  36198. }
  36199. if ( uvScaleMap !== undefined ) {
  36200. // backwards compatibility
  36201. if ( uvScaleMap.isWebGLRenderTarget ) {
  36202. uvScaleMap = uvScaleMap.texture;
  36203. }
  36204. if ( uvScaleMap.matrixAutoUpdate === true ) {
  36205. uvScaleMap.updateMatrix();
  36206. }
  36207. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  36208. }
  36209. uniforms.envMap.value = material.envMap;
  36210. uniforms.envMapIntensity.value = material.envMapIntensity;
  36211. uniforms.flipEnvMap.value = ( material.envMap && material.envMap.isCubeTexture ) ? - 1 : 1;
  36212. uniforms.refractionRatio.value = material.refractionRatio;
  36213. uniforms.specular.value.copy( material.specular );
  36214. uniforms.glossiness.value = material.glossiness;
  36215. uniforms.glossinessMap.value = material.glossinessMap;
  36216. uniforms.emissiveMap.value = material.emissiveMap;
  36217. uniforms.bumpMap.value = material.bumpMap;
  36218. uniforms.normalMap.value = material.normalMap;
  36219. uniforms.displacementMap.value = material.displacementMap;
  36220. uniforms.displacementScale.value = material.displacementScale;
  36221. uniforms.displacementBias.value = material.displacementBias;
  36222. if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) {
  36223. defines.USE_GLOSSINESSMAP = '';
  36224. // set USE_ROUGHNESSMAP to enable vUv
  36225. defines.USE_ROUGHNESSMAP = '';
  36226. }
  36227. if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) {
  36228. delete defines.USE_GLOSSINESSMAP;
  36229. delete defines.USE_ROUGHNESSMAP;
  36230. }
  36231. }
  36232. };
  36233. }
  36234. /*********************************/
  36235. /********** INTERPOLATION ********/
  36236. /*********************************/
  36237. // Spline Interpolation
  36238. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  36239. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  36240. THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  36241. }
  36242. GLTFCubicSplineInterpolant.prototype = Object.create( THREE.Interpolant.prototype );
  36243. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  36244. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) {
  36245. // Copies a sample value to the result buffer. See description of glTF
  36246. // CUBICSPLINE values layout in interpolate_() function below.
  36247. var result = this.resultBuffer,
  36248. values = this.sampleValues,
  36249. valueSize = this.valueSize,
  36250. offset = index * valueSize * 3 + valueSize;
  36251. for ( var i = 0; i !== valueSize; i ++ ) {
  36252. result[ i ] = values[ offset + i ];
  36253. }
  36254. return result;
  36255. };
  36256. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  36257. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  36258. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  36259. var result = this.resultBuffer;
  36260. var values = this.sampleValues;
  36261. var stride = this.valueSize;
  36262. var stride2 = stride * 2;
  36263. var stride3 = stride * 3;
  36264. var td = t1 - t0;
  36265. var p = ( t - t0 ) / td;
  36266. var pp = p * p;
  36267. var ppp = pp * p;
  36268. var offset1 = i1 * stride3;
  36269. var offset0 = offset1 - stride3;
  36270. var s0 = 2 * ppp - 3 * pp + 1;
  36271. var s1 = ppp - 2 * pp + p;
  36272. var s2 = - 2 * ppp + 3 * pp;
  36273. var s3 = ppp - pp;
  36274. // Layout of keyframe output values for CUBICSPLINE animations:
  36275. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  36276. for ( var i = 0; i !== stride; i ++ ) {
  36277. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  36278. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  36279. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  36280. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  36281. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  36282. }
  36283. return result;
  36284. };
  36285. /*********************************/
  36286. /********** INTERNALS ************/
  36287. /*********************************/
  36288. /* CONSTANTS */
  36289. var WEBGL_CONSTANTS = {
  36290. FLOAT: 5126,
  36291. //FLOAT_MAT2: 35674,
  36292. FLOAT_MAT3: 35675,
  36293. FLOAT_MAT4: 35676,
  36294. FLOAT_VEC2: 35664,
  36295. FLOAT_VEC3: 35665,
  36296. FLOAT_VEC4: 35666,
  36297. LINEAR: 9729,
  36298. REPEAT: 10497,
  36299. SAMPLER_2D: 35678,
  36300. POINTS: 0,
  36301. LINES: 1,
  36302. LINE_LOOP: 2,
  36303. LINE_STRIP: 3,
  36304. TRIANGLES: 4,
  36305. TRIANGLE_STRIP: 5,
  36306. TRIANGLE_FAN: 6,
  36307. UNSIGNED_BYTE: 5121,
  36308. UNSIGNED_SHORT: 5123
  36309. };
  36310. var WEBGL_TYPE = {
  36311. 5126: Number,
  36312. //35674: THREE.Matrix2,
  36313. 35675: THREE.Matrix3,
  36314. 35676: THREE.Matrix4,
  36315. 35664: THREE.Vector2,
  36316. 35665: THREE.Vector3,
  36317. 35666: THREE.Vector4,
  36318. 35678: THREE.Texture
  36319. };
  36320. var WEBGL_COMPONENT_TYPES = {
  36321. 5120: Int8Array,
  36322. 5121: Uint8Array,
  36323. 5122: Int16Array,
  36324. 5123: Uint16Array,
  36325. 5125: Uint32Array,
  36326. 5126: Float32Array
  36327. };
  36328. var WEBGL_FILTERS = {
  36329. 9728: THREE.NearestFilter,
  36330. 9729: THREE.LinearFilter,
  36331. 9984: THREE.NearestMipMapNearestFilter,
  36332. 9985: THREE.LinearMipMapNearestFilter,
  36333. 9986: THREE.NearestMipMapLinearFilter,
  36334. 9987: THREE.LinearMipMapLinearFilter
  36335. };
  36336. var WEBGL_WRAPPINGS = {
  36337. 33071: THREE.ClampToEdgeWrapping,
  36338. 33648: THREE.MirroredRepeatWrapping,
  36339. 10497: THREE.RepeatWrapping
  36340. };
  36341. var WEBGL_SIDES = {
  36342. 1028: THREE.BackSide, // Culling front
  36343. 1029: THREE.FrontSide // Culling back
  36344. //1032: THREE.NoSide // Culling front and back, what to do?
  36345. };
  36346. var WEBGL_DEPTH_FUNCS = {
  36347. 512: THREE.NeverDepth,
  36348. 513: THREE.LessDepth,
  36349. 514: THREE.EqualDepth,
  36350. 515: THREE.LessEqualDepth,
  36351. 516: THREE.GreaterEqualDepth,
  36352. 517: THREE.NotEqualDepth,
  36353. 518: THREE.GreaterEqualDepth,
  36354. 519: THREE.AlwaysDepth
  36355. };
  36356. var WEBGL_BLEND_EQUATIONS = {
  36357. 32774: THREE.AddEquation,
  36358. 32778: THREE.SubtractEquation,
  36359. 32779: THREE.ReverseSubtractEquation
  36360. };
  36361. var WEBGL_BLEND_FUNCS = {
  36362. 0: THREE.ZeroFactor,
  36363. 1: THREE.OneFactor,
  36364. 768: THREE.SrcColorFactor,
  36365. 769: THREE.OneMinusSrcColorFactor,
  36366. 770: THREE.SrcAlphaFactor,
  36367. 771: THREE.OneMinusSrcAlphaFactor,
  36368. 772: THREE.DstAlphaFactor,
  36369. 773: THREE.OneMinusDstAlphaFactor,
  36370. 774: THREE.DstColorFactor,
  36371. 775: THREE.OneMinusDstColorFactor,
  36372. 776: THREE.SrcAlphaSaturateFactor
  36373. // The followings are not supported by Three.js yet
  36374. //32769: CONSTANT_COLOR,
  36375. //32770: ONE_MINUS_CONSTANT_COLOR,
  36376. //32771: CONSTANT_ALPHA,
  36377. //32772: ONE_MINUS_CONSTANT_COLOR
  36378. };
  36379. var WEBGL_TYPE_SIZES = {
  36380. 'SCALAR': 1,
  36381. 'VEC2': 2,
  36382. 'VEC3': 3,
  36383. 'VEC4': 4,
  36384. 'MAT2': 4,
  36385. 'MAT3': 9,
  36386. 'MAT4': 16
  36387. };
  36388. var ATTRIBUTES = {
  36389. POSITION: 'position',
  36390. NORMAL: 'normal',
  36391. TEXCOORD_0: 'uv',
  36392. TEXCOORD_1: 'uv2',
  36393. COLOR_0: 'color',
  36394. WEIGHTS_0: 'skinWeight',
  36395. JOINTS_0: 'skinIndex',
  36396. };
  36397. var PATH_PROPERTIES = {
  36398. scale: 'scale',
  36399. translation: 'position',
  36400. rotation: 'quaternion',
  36401. weights: 'morphTargetInfluences'
  36402. };
  36403. var INTERPOLATION = {
  36404. CUBICSPLINE: THREE.InterpolateSmooth, // We use custom interpolation GLTFCubicSplineInterpolation for CUBICSPLINE.
  36405. // KeyframeTrack.optimize() can't handle glTF Cubic Spline output values layout,
  36406. // using THREE.InterpolateSmooth for KeyframeTrack instantiation to prevent optimization.
  36407. // See KeyframeTrack.optimize() for the detail.
  36408. LINEAR: THREE.InterpolateLinear,
  36409. STEP: THREE.InterpolateDiscrete
  36410. };
  36411. var STATES_ENABLES = {
  36412. 2884: 'CULL_FACE',
  36413. 2929: 'DEPTH_TEST',
  36414. 3042: 'BLEND',
  36415. 3089: 'SCISSOR_TEST',
  36416. 32823: 'POLYGON_OFFSET_FILL',
  36417. 32926: 'SAMPLE_ALPHA_TO_COVERAGE'
  36418. };
  36419. var ALPHA_MODES = {
  36420. OPAQUE: 'OPAQUE',
  36421. MASK: 'MASK',
  36422. BLEND: 'BLEND'
  36423. };
  36424. var MIME_TYPE_FORMATS = {
  36425. 'image/png': THREE.RGBAFormat,
  36426. 'image/jpeg': THREE.RGBFormat
  36427. };
  36428. /* UTILITY FUNCTIONS */
  36429. function resolveURL( url, path ) {
  36430. // Invalid URL
  36431. if ( typeof url !== 'string' || url === '' ) return '';
  36432. // Absolute URL http://,https://,//
  36433. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  36434. // Data URI
  36435. if ( /^data:.*,.*$/i.test( url ) ) return url;
  36436. // Blob URL
  36437. if ( /^blob:.*$/i.test( url ) ) return url;
  36438. // Relative URL
  36439. return path + url;
  36440. }
  36441. /**
  36442. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  36443. */
  36444. function createDefaultMaterial() {
  36445. return new THREE.MeshStandardMaterial( {
  36446. color: 0xFFFFFF,
  36447. emissive: 0x000000,
  36448. metalness: 1,
  36449. roughness: 1,
  36450. transparent: false,
  36451. depthTest: true,
  36452. side: THREE.FrontSide
  36453. } );
  36454. }
  36455. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  36456. // Add unknown glTF extensions to an object's userData.
  36457. for ( var name in objectDef.extensions ) {
  36458. if ( knownExtensions[ name ] === undefined ) {
  36459. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  36460. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  36461. }
  36462. }
  36463. }
  36464. /**
  36465. * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object
  36466. * @param {GLTF.definition} gltfDef
  36467. */
  36468. function assignExtrasToUserData( object, gltfDef ) {
  36469. if ( gltfDef.extras !== undefined ) {
  36470. if ( typeof gltfDef.extras === 'object' ) {
  36471. object.userData = gltfDef.extras;
  36472. } else {
  36473. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  36474. }
  36475. }
  36476. }
  36477. /**
  36478. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  36479. *
  36480. * @param {THREE.BufferGeometry} geometry
  36481. * @param {Array<GLTF.Target>} targets
  36482. * @param {GLTFParser} parser
  36483. * @return {Promise<THREE.BufferGeometry>}
  36484. */
  36485. function addMorphTargets( geometry, targets, parser ) {
  36486. var hasMorphPosition = false;
  36487. var hasMorphNormal = false;
  36488. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  36489. var target = targets[ i ];
  36490. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  36491. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  36492. if ( hasMorphPosition && hasMorphNormal ) break;
  36493. }
  36494. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  36495. var pendingPositionAccessors = [];
  36496. var pendingNormalAccessors = [];
  36497. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  36498. var target = targets[ i ];
  36499. if ( hasMorphPosition ) {
  36500. // TODO: Error-prone use of a callback inside a loop.
  36501. var accessor = target.POSITION !== undefined
  36502. ? parser.getDependency( 'accessor', target.POSITION )
  36503. .then( function ( accessor ) {
  36504. // Cloning not to pollute original accessor below
  36505. return cloneBufferAttribute( accessor );
  36506. } )
  36507. : geometry.attributes.position;
  36508. pendingPositionAccessors.push( accessor );
  36509. }
  36510. if ( hasMorphNormal ) {
  36511. // TODO: Error-prone use of a callback inside a loop.
  36512. var accessor = target.NORMAL !== undefined
  36513. ? parser.getDependency( 'accessor', target.NORMAL )
  36514. .then( function ( accessor ) {
  36515. return cloneBufferAttribute( accessor );
  36516. } )
  36517. : geometry.attributes.normal;
  36518. pendingNormalAccessors.push( accessor );
  36519. }
  36520. }
  36521. return Promise.all( [
  36522. Promise.all( pendingPositionAccessors ),
  36523. Promise.all( pendingNormalAccessors )
  36524. ] ).then( function ( accessors ) {
  36525. var morphPositions = accessors[ 0 ];
  36526. var morphNormals = accessors[ 1 ];
  36527. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  36528. var target = targets[ i ];
  36529. var attributeName = 'morphTarget' + i;
  36530. if ( hasMorphPosition ) {
  36531. // Three.js morph position is absolute value. The formula is
  36532. // basePosition
  36533. // + weight0 * ( morphPosition0 - basePosition )
  36534. // + weight1 * ( morphPosition1 - basePosition )
  36535. // ...
  36536. // while the glTF one is relative
  36537. // basePosition
  36538. // + weight0 * glTFmorphPosition0
  36539. // + weight1 * glTFmorphPosition1
  36540. // ...
  36541. // then we need to convert from relative to absolute here.
  36542. if ( target.POSITION !== undefined ) {
  36543. var positionAttribute = morphPositions[ i ];
  36544. positionAttribute.name = attributeName;
  36545. var position = geometry.attributes.position;
  36546. for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) {
  36547. positionAttribute.setXYZ(
  36548. j,
  36549. positionAttribute.getX( j ) + position.getX( j ),
  36550. positionAttribute.getY( j ) + position.getY( j ),
  36551. positionAttribute.getZ( j ) + position.getZ( j )
  36552. );
  36553. }
  36554. }
  36555. }
  36556. if ( hasMorphNormal ) {
  36557. // see target.POSITION's comment
  36558. if ( target.NORMAL !== undefined ) {
  36559. var normalAttribute = morphNormals[ i ];
  36560. normalAttribute.name = attributeName;
  36561. var normal = geometry.attributes.normal;
  36562. for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) {
  36563. normalAttribute.setXYZ(
  36564. j,
  36565. normalAttribute.getX( j ) + normal.getX( j ),
  36566. normalAttribute.getY( j ) + normal.getY( j ),
  36567. normalAttribute.getZ( j ) + normal.getZ( j )
  36568. );
  36569. }
  36570. }
  36571. }
  36572. }
  36573. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  36574. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  36575. return geometry;
  36576. } );
  36577. }
  36578. /**
  36579. * @param {THREE.Mesh} mesh
  36580. * @param {GLTF.Mesh} meshDef
  36581. */
  36582. function updateMorphTargets( mesh, meshDef ) {
  36583. mesh.updateMorphTargets();
  36584. if ( meshDef.weights !== undefined ) {
  36585. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  36586. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  36587. }
  36588. }
  36589. // .extras has user-defined data, so check that .extras.targetNames is an array.
  36590. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  36591. var targetNames = meshDef.extras.targetNames;
  36592. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  36593. mesh.morphTargetDictionary = {};
  36594. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  36595. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  36596. }
  36597. } else {
  36598. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  36599. }
  36600. }
  36601. }
  36602. function isPrimitiveEqual( a, b ) {
  36603. var dracoExtA = a.extensions ? a.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] : undefined;
  36604. var dracoExtB = b.extensions ? b.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] : undefined;
  36605. if ( dracoExtA && dracoExtB ) {
  36606. if ( dracoExtA.bufferView !== dracoExtB.bufferView ) return false;
  36607. return isObjectEqual( dracoExtA.attributes, dracoExtB.attributes );
  36608. }
  36609. if ( a.indices !== b.indices ) {
  36610. return false;
  36611. }
  36612. return isObjectEqual( a.attributes, b.attributes );
  36613. }
  36614. function isObjectEqual( a, b ) {
  36615. if ( Object.keys( a ).length !== Object.keys( b ).length ) return false;
  36616. for ( var key in a ) {
  36617. if ( a[ key ] !== b[ key ] ) return false;
  36618. }
  36619. return true;
  36620. }
  36621. function isArrayEqual( a, b ) {
  36622. if ( a.length !== b.length ) return false;
  36623. for ( var i = 0, il = a.length; i < il; i ++ ) {
  36624. if ( a[ i ] !== b[ i ] ) return false;
  36625. }
  36626. return true;
  36627. }
  36628. function getCachedGeometry( cache, newPrimitive ) {
  36629. for ( var i = 0, il = cache.length; i < il; i ++ ) {
  36630. var cached = cache[ i ];
  36631. if ( isPrimitiveEqual( cached.primitive, newPrimitive ) ) return cached.promise;
  36632. }
  36633. return null;
  36634. }
  36635. function getCachedCombinedGeometry( cache, geometries ) {
  36636. for ( var i = 0, il = cache.length; i < il; i ++ ) {
  36637. var cached = cache[ i ];
  36638. if ( isArrayEqual( geometries, cached.baseGeometries ) ) return cached.geometry;
  36639. }
  36640. return null;
  36641. }
  36642. function getCachedMultiPassGeometry( cache, geometry, primitives ) {
  36643. for ( var i = 0, il = cache.length; i < il; i ++ ) {
  36644. var cached = cache[ i ];
  36645. if ( geometry === cached.baseGeometry && isArrayEqual( primitives, cached.primitives ) ) return cached.geometry;
  36646. }
  36647. return null;
  36648. }
  36649. function cloneBufferAttribute( attribute ) {
  36650. if ( attribute.isInterleavedBufferAttribute ) {
  36651. var count = attribute.count;
  36652. var itemSize = attribute.itemSize;
  36653. var array = attribute.array.slice( 0, count * itemSize );
  36654. for ( var i = 0; i < count; ++ i ) {
  36655. array[ i ] = attribute.getX( i );
  36656. if ( itemSize >= 2 ) array[ i + 1 ] = attribute.getY( i );
  36657. if ( itemSize >= 3 ) array[ i + 2 ] = attribute.getZ( i );
  36658. if ( itemSize >= 4 ) array[ i + 3 ] = attribute.getW( i );
  36659. }
  36660. return new THREE.BufferAttribute( array, itemSize, attribute.normalized );
  36661. }
  36662. return attribute.clone();
  36663. }
  36664. /**
  36665. * Checks if we can build a single Mesh with MultiMaterial from multiple primitives.
  36666. * Returns true if all primitives use the same attributes/morphAttributes/mode
  36667. * and also have index. Otherwise returns false.
  36668. *
  36669. * @param {Array<GLTF.Primitive>} primitives
  36670. * @return {Boolean}
  36671. */
  36672. function isMultiPassGeometry( primitives ) {
  36673. if ( primitives.length < 2 ) return false;
  36674. var primitive0 = primitives[ 0 ];
  36675. var targets0 = primitive0.targets || [];
  36676. if ( primitive0.indices === undefined ) return false;
  36677. for ( var i = 1, il = primitives.length; i < il; i ++ ) {
  36678. var primitive = primitives[ i ];
  36679. if ( primitive0.mode !== primitive.mode ) return false;
  36680. if ( primitive.indices === undefined ) return false;
  36681. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) return false;
  36682. if ( ! isObjectEqual( primitive0.attributes, primitive.attributes ) ) return false;
  36683. var targets = primitive.targets || [];
  36684. if ( targets0.length !== targets.length ) return false;
  36685. for ( var j = 0, jl = targets0.length; j < jl; j ++ ) {
  36686. if ( ! isObjectEqual( targets0[ j ], targets[ j ] ) ) return false;
  36687. }
  36688. }
  36689. return true;
  36690. }
  36691. /* GLTF PARSER */
  36692. function GLTFParser( json, extensions, options ) {
  36693. this.json = json || {};
  36694. this.extensions = extensions || {};
  36695. this.options = options || {};
  36696. // loader object cache
  36697. this.cache = new GLTFRegistry();
  36698. // BufferGeometry caching
  36699. this.primitiveCache = [];
  36700. this.multiplePrimitivesCache = [];
  36701. this.multiPassGeometryCache = [];
  36702. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  36703. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  36704. this.fileLoader = new THREE.FileLoader( this.options.manager );
  36705. this.fileLoader.setResponseType( 'arraybuffer' );
  36706. }
  36707. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  36708. var json = this.json;
  36709. // Clear the loader cache
  36710. this.cache.removeAll();
  36711. // Mark the special nodes/meshes in json for efficient parse
  36712. this.markDefs();
  36713. // Fire the callback on complete
  36714. this.getMultiDependencies( [
  36715. 'scene',
  36716. 'animation',
  36717. 'camera'
  36718. ] ).then( function ( dependencies ) {
  36719. var scenes = dependencies.scenes || [];
  36720. var scene = scenes[ json.scene || 0 ];
  36721. var animations = dependencies.animations || [];
  36722. var cameras = dependencies.cameras || [];
  36723. onLoad( scene, scenes, cameras, animations, json );
  36724. } ).catch( onError );
  36725. };
  36726. /**
  36727. * Marks the special nodes/meshes in json for efficient parse.
  36728. */
  36729. GLTFParser.prototype.markDefs = function () {
  36730. var nodeDefs = this.json.nodes || [];
  36731. var skinDefs = this.json.skins || [];
  36732. var meshDefs = this.json.meshes || [];
  36733. var meshReferences = {};
  36734. var meshUses = {};
  36735. // Nothing in the node definition indicates whether it is a Bone or an
  36736. // Object3D. Use the skins' joint references to mark bones.
  36737. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  36738. var joints = skinDefs[ skinIndex ].joints;
  36739. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  36740. nodeDefs[ joints[ i ] ].isBone = true;
  36741. }
  36742. }
  36743. // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  36744. // avoid having more than one THREE.Mesh with the same name, count
  36745. // references and rename instances below.
  36746. //
  36747. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  36748. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  36749. var nodeDef = nodeDefs[ nodeIndex ];
  36750. if ( nodeDef.mesh !== undefined ) {
  36751. if ( meshReferences[ nodeDef.mesh ] === undefined ) {
  36752. meshReferences[ nodeDef.mesh ] = meshUses[ nodeDef.mesh ] = 0;
  36753. }
  36754. meshReferences[ nodeDef.mesh ] ++;
  36755. // Nothing in the mesh definition indicates whether it is
  36756. // a SkinnedMesh or Mesh. Use the node's mesh reference
  36757. // to mark SkinnedMesh if node has skin.
  36758. if ( nodeDef.skin !== undefined ) {
  36759. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  36760. }
  36761. }
  36762. }
  36763. this.json.meshReferences = meshReferences;
  36764. this.json.meshUses = meshUses;
  36765. };
  36766. /**
  36767. * Requests the specified dependency asynchronously, with caching.
  36768. * @param {string} type
  36769. * @param {number} index
  36770. * @return {Promise<THREE.Object3D|THREE.Material|THREE.Texture|THREE.AnimationClip|ArrayBuffer|Object>}
  36771. */
  36772. GLTFParser.prototype.getDependency = function ( type, index ) {
  36773. var cacheKey = type + ':' + index;
  36774. var dependency = this.cache.get( cacheKey );
  36775. if ( ! dependency ) {
  36776. switch ( type ) {
  36777. case 'scene':
  36778. dependency = this.loadScene( index );
  36779. break;
  36780. case 'node':
  36781. dependency = this.loadNode( index );
  36782. break;
  36783. case 'mesh':
  36784. dependency = this.loadMesh( index );
  36785. break;
  36786. case 'accessor':
  36787. dependency = this.loadAccessor( index );
  36788. break;
  36789. case 'bufferView':
  36790. dependency = this.loadBufferView( index );
  36791. break;
  36792. case 'buffer':
  36793. dependency = this.loadBuffer( index );
  36794. break;
  36795. case 'material':
  36796. dependency = this.loadMaterial( index );
  36797. break;
  36798. case 'texture':
  36799. dependency = this.loadTexture( index );
  36800. break;
  36801. case 'skin':
  36802. dependency = this.loadSkin( index );
  36803. break;
  36804. case 'animation':
  36805. dependency = this.loadAnimation( index );
  36806. break;
  36807. case 'camera':
  36808. dependency = this.loadCamera( index );
  36809. break;
  36810. case 'light':
  36811. dependency = this.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].loadLight( index );
  36812. break
  36813. default:
  36814. throw new Error( 'Unknown type: ' + type );
  36815. }
  36816. this.cache.add( cacheKey, dependency );
  36817. }
  36818. return dependency;
  36819. };
  36820. /**
  36821. * Requests all dependencies of the specified type asynchronously, with caching.
  36822. * @param {string} type
  36823. * @return {Promise<Array<Object>>}
  36824. */
  36825. GLTFParser.prototype.getDependencies = function ( type ) {
  36826. var dependencies = this.cache.get( type );
  36827. if ( ! dependencies ) {
  36828. var parser = this;
  36829. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  36830. dependencies = Promise.all( defs.map( function ( def, index ) {
  36831. return parser.getDependency( type, index );
  36832. } ) );
  36833. this.cache.add( type, dependencies );
  36834. }
  36835. return dependencies;
  36836. };
  36837. /**
  36838. * Requests all multiple dependencies of the specified types asynchronously, with caching.
  36839. * @param {Array<string>} types
  36840. * @return {Promise<Object<Array<Object>>>}
  36841. */
  36842. GLTFParser.prototype.getMultiDependencies = function ( types ) {
  36843. var results = {};
  36844. var pending = [];
  36845. for ( var i = 0, il = types.length; i < il; i ++ ) {
  36846. var type = types[ i ];
  36847. var value = this.getDependencies( type );
  36848. // TODO: Error-prone use of a callback inside a loop.
  36849. value = value.then( function ( key, value ) {
  36850. results[ key ] = value;
  36851. }.bind( this, type + ( type === 'mesh' ? 'es' : 's' ) ) );
  36852. pending.push( value );
  36853. }
  36854. return Promise.all( pending ).then( function () {
  36855. return results;
  36856. } );
  36857. };
  36858. /**
  36859. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  36860. * @param {number} bufferIndex
  36861. * @return {Promise<ArrayBuffer>}
  36862. */
  36863. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  36864. var bufferDef = this.json.buffers[ bufferIndex ];
  36865. var loader = this.fileLoader;
  36866. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  36867. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  36868. }
  36869. // If present, GLB container is required to be the first buffer.
  36870. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  36871. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  36872. }
  36873. var options = this.options;
  36874. return new Promise( function ( resolve, reject ) {
  36875. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  36876. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  36877. } );
  36878. } );
  36879. };
  36880. /**
  36881. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  36882. * @param {number} bufferViewIndex
  36883. * @return {Promise<ArrayBuffer>}
  36884. */
  36885. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  36886. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  36887. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  36888. var byteLength = bufferViewDef.byteLength || 0;
  36889. var byteOffset = bufferViewDef.byteOffset || 0;
  36890. return buffer.slice( byteOffset, byteOffset + byteLength );
  36891. } );
  36892. };
  36893. /**
  36894. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  36895. * @param {number} accessorIndex
  36896. * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
  36897. */
  36898. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  36899. var parser = this;
  36900. var json = this.json;
  36901. var accessorDef = this.json.accessors[ accessorIndex ];
  36902. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  36903. // Ignore empty accessors, which may be used to declare runtime
  36904. // information about attributes coming from another source (e.g. Draco
  36905. // compression extension).
  36906. return Promise.resolve( null );
  36907. }
  36908. var pendingBufferViews = [];
  36909. if ( accessorDef.bufferView !== undefined ) {
  36910. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  36911. } else {
  36912. pendingBufferViews.push( null );
  36913. }
  36914. if ( accessorDef.sparse !== undefined ) {
  36915. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  36916. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  36917. }
  36918. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  36919. var bufferView = bufferViews[ 0 ];
  36920. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  36921. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  36922. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  36923. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  36924. var itemBytes = elementBytes * itemSize;
  36925. var byteOffset = accessorDef.byteOffset || 0;
  36926. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  36927. var normalized = accessorDef.normalized === true;
  36928. var array, bufferAttribute;
  36929. // The buffer is not interleaved if the stride is the item size in bytes.
  36930. if ( byteStride && byteStride !== itemBytes ) {
  36931. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType;
  36932. var ib = parser.cache.get( ibCacheKey );
  36933. if ( ! ib ) {
  36934. // Use the full buffer if it's interleaved.
  36935. array = new TypedArray( bufferView );
  36936. // Integer parameters to IB/IBA are in array elements, not bytes.
  36937. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  36938. parser.cache.add( ibCacheKey, ib );
  36939. }
  36940. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, byteOffset / elementBytes, normalized );
  36941. } else {
  36942. if ( bufferView === null ) {
  36943. array = new TypedArray( accessorDef.count * itemSize );
  36944. } else {
  36945. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  36946. }
  36947. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  36948. }
  36949. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  36950. if ( accessorDef.sparse !== undefined ) {
  36951. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  36952. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  36953. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  36954. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  36955. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  36956. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  36957. if ( bufferView !== null ) {
  36958. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  36959. bufferAttribute.setArray( bufferAttribute.array.slice() );
  36960. }
  36961. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  36962. var index = sparseIndices[ i ];
  36963. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  36964. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  36965. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  36966. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  36967. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  36968. }
  36969. }
  36970. return bufferAttribute;
  36971. } );
  36972. };
  36973. /**
  36974. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  36975. * @param {number} textureIndex
  36976. * @return {Promise<THREE.Texture>}
  36977. */
  36978. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  36979. var parser = this;
  36980. var json = this.json;
  36981. var options = this.options;
  36982. var textureLoader = this.textureLoader;
  36983. var URL = window.URL || window.webkitURL;
  36984. var textureDef = json.textures[ textureIndex ];
  36985. var textureExtensions = textureDef.extensions || {};
  36986. var source;
  36987. if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  36988. source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ];
  36989. } else {
  36990. source = json.images[ textureDef.source ];
  36991. }
  36992. var sourceURI = source.uri;
  36993. var isObjectURL = false;
  36994. if ( source.bufferView !== undefined ) {
  36995. // Load binary image data from bufferView, if provided.
  36996. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  36997. isObjectURL = true;
  36998. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  36999. sourceURI = URL.createObjectURL( blob );
  37000. return sourceURI;
  37001. } );
  37002. }
  37003. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  37004. // Load Texture resource.
  37005. var loader = THREE.Loader.Handlers.get( sourceURI );
  37006. if ( ! loader ) {
  37007. loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ]
  37008. ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader
  37009. : textureLoader;
  37010. }
  37011. return new Promise( function ( resolve, reject ) {
  37012. loader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject );
  37013. } );
  37014. } ).then( function ( texture ) {
  37015. // Clean up resources and configure Texture.
  37016. if ( isObjectURL === true ) {
  37017. URL.revokeObjectURL( sourceURI );
  37018. }
  37019. texture.flipY = false;
  37020. if ( textureDef.name !== undefined ) texture.name = textureDef.name;
  37021. // Ignore unknown mime types, like DDS files.
  37022. if ( source.mimeType in MIME_TYPE_FORMATS ) {
  37023. texture.format = MIME_TYPE_FORMATS[ source.mimeType ];
  37024. }
  37025. var samplers = json.samplers || {};
  37026. var sampler = samplers[ textureDef.sampler ] || {};
  37027. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  37028. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipMapLinearFilter;
  37029. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  37030. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  37031. return texture;
  37032. } );
  37033. };
  37034. /**
  37035. * Asynchronously assigns a texture to the given material parameters.
  37036. * @param {Object} materialParams
  37037. * @param {string} mapName
  37038. * @param {Object} mapDef
  37039. * @return {Promise}
  37040. */
  37041. GLTFParser.prototype.assignTexture = function ( materialParams, mapName, mapDef ) {
  37042. var parser = this;
  37043. return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
  37044. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  37045. var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  37046. if ( transform ) {
  37047. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  37048. }
  37049. }
  37050. materialParams[ mapName ] = texture;
  37051. } );
  37052. };
  37053. /**
  37054. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  37055. * @param {number} materialIndex
  37056. * @return {Promise<THREE.Material>}
  37057. */
  37058. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  37059. var parser = this;
  37060. var json = this.json;
  37061. var extensions = this.extensions;
  37062. var materialDef = json.materials[ materialIndex ];
  37063. var materialType;
  37064. var materialParams = {};
  37065. var materialExtensions = materialDef.extensions || {};
  37066. var pending = [];
  37067. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  37068. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  37069. materialType = sgExtension.getMaterialType( materialDef );
  37070. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  37071. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  37072. var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  37073. materialType = kmuExtension.getMaterialType( materialDef );
  37074. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  37075. } else {
  37076. // Specification:
  37077. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  37078. materialType = THREE.MeshStandardMaterial;
  37079. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  37080. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  37081. materialParams.opacity = 1.0;
  37082. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  37083. var array = metallicRoughness.baseColorFactor;
  37084. materialParams.color.fromArray( array );
  37085. materialParams.opacity = array[ 3 ];
  37086. }
  37087. if ( metallicRoughness.baseColorTexture !== undefined ) {
  37088. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  37089. }
  37090. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  37091. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  37092. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  37093. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  37094. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  37095. }
  37096. }
  37097. if ( materialDef.doubleSided === true ) {
  37098. materialParams.side = THREE.DoubleSide;
  37099. }
  37100. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  37101. if ( alphaMode === ALPHA_MODES.BLEND ) {
  37102. materialParams.transparent = true;
  37103. } else {
  37104. materialParams.transparent = false;
  37105. if ( alphaMode === ALPHA_MODES.MASK ) {
  37106. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  37107. }
  37108. }
  37109. if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  37110. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  37111. materialParams.normalScale = new THREE.Vector2( 1, 1 );
  37112. if ( materialDef.normalTexture.scale !== undefined ) {
  37113. materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale );
  37114. }
  37115. }
  37116. if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  37117. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  37118. if ( materialDef.occlusionTexture.strength !== undefined ) {
  37119. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  37120. }
  37121. }
  37122. if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  37123. materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
  37124. }
  37125. if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  37126. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) );
  37127. }
  37128. return Promise.all( pending ).then( function () {
  37129. var material;
  37130. if ( materialType === THREE.ShaderMaterial ) {
  37131. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  37132. } else {
  37133. material = new materialType( materialParams );
  37134. }
  37135. if ( materialDef.name !== undefined ) material.name = materialDef.name;
  37136. // Normal map textures use OpenGL conventions:
  37137. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#materialnormaltexture
  37138. if ( material.normalScale ) {
  37139. material.normalScale.y = - material.normalScale.y;
  37140. }
  37141. // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  37142. if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
  37143. if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding;
  37144. if ( material.specularMap ) material.specularMap.encoding = THREE.sRGBEncoding;
  37145. assignExtrasToUserData( material, materialDef );
  37146. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  37147. return material;
  37148. } );
  37149. };
  37150. /**
  37151. * @param {THREE.BufferGeometry} geometry
  37152. * @param {GLTF.Primitive} primitiveDef
  37153. * @param {GLTFParser} parser
  37154. * @return {Promise<THREE.BufferGeometry>}
  37155. */
  37156. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  37157. var attributes = primitiveDef.attributes;
  37158. var pending = [];
  37159. function assignAttributeAccessor( accessorIndex, attributeName ) {
  37160. return parser.getDependency( 'accessor', accessorIndex )
  37161. .then( function ( accessor ) {
  37162. geometry.addAttribute( attributeName, accessor );
  37163. } );
  37164. }
  37165. for ( var gltfAttributeName in attributes ) {
  37166. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ];
  37167. if ( ! threeAttributeName ) continue;
  37168. // Skip attributes already provided by e.g. Draco extension.
  37169. if ( threeAttributeName in geometry.attributes ) continue;
  37170. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  37171. }
  37172. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  37173. var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  37174. geometry.setIndex( accessor );
  37175. } );
  37176. pending.push( accessor );
  37177. }
  37178. assignExtrasToUserData( geometry, primitiveDef );
  37179. return Promise.all( pending ).then( function () {
  37180. return primitiveDef.targets !== undefined
  37181. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  37182. : geometry;
  37183. } );
  37184. }
  37185. /**
  37186. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  37187. *
  37188. * Creates BufferGeometries from primitives.
  37189. * If we can build a single BufferGeometry with .groups from multiple primitives, returns one BufferGeometry.
  37190. * Otherwise, returns BufferGeometries without .groups as many as primitives.
  37191. *
  37192. * @param {Array<GLTF.Primitive>} primitives
  37193. * @return {Promise<Array<THREE.BufferGeometry>>}
  37194. */
  37195. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  37196. var parser = this;
  37197. var extensions = this.extensions;
  37198. var cache = this.primitiveCache;
  37199. var isMultiPass = isMultiPassGeometry( primitives );
  37200. var originalPrimitives;
  37201. if ( isMultiPass ) {
  37202. originalPrimitives = primitives; // save original primitives and use later
  37203. // We build a single BufferGeometry with .groups from multiple primitives
  37204. // because all primitives share the same attributes/morph/mode and have indices.
  37205. primitives = [ primitives[ 0 ] ];
  37206. // Sets .groups and combined indices to a geometry later in this method.
  37207. }
  37208. function createDracoPrimitive( primitive ) {
  37209. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  37210. .decodePrimitive( primitive, parser )
  37211. .then( function ( geometry ) {
  37212. return addPrimitiveAttributes( geometry, primitive, parser );
  37213. } );
  37214. }
  37215. var pending = [];
  37216. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  37217. var primitive = primitives[ i ];
  37218. // See if we've already created this geometry
  37219. var cached = getCachedGeometry( cache, primitive );
  37220. if ( cached ) {
  37221. // Use the cached geometry if it exists
  37222. pending.push( cached );
  37223. } else {
  37224. var geometryPromise;
  37225. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  37226. // Use DRACO geometry if available
  37227. geometryPromise = createDracoPrimitive( primitive );
  37228. } else {
  37229. // Otherwise create a new geometry
  37230. geometryPromise = addPrimitiveAttributes( new THREE.BufferGeometry(), primitive, parser );
  37231. }
  37232. // Cache this geometry
  37233. cache.push( { primitive: primitive, promise: geometryPromise } );
  37234. pending.push( geometryPromise );
  37235. }
  37236. }
  37237. return Promise.all( pending ).then( function ( geometries ) {
  37238. if ( isMultiPass ) {
  37239. var baseGeometry = geometries[ 0 ];
  37240. // See if we've already created this combined geometry
  37241. var cache = parser.multiPassGeometryCache;
  37242. var cached = getCachedMultiPassGeometry( cache, baseGeometry, originalPrimitives );
  37243. if ( cached !== null ) return [ cached.geometry ];
  37244. // Cloning geometry because of index override.
  37245. // Attributes can be reused so cloning by myself here.
  37246. var geometry = new THREE.BufferGeometry();
  37247. geometry.name = baseGeometry.name;
  37248. geometry.userData = baseGeometry.userData;
  37249. for ( var key in baseGeometry.attributes ) geometry.addAttribute( key, baseGeometry.attributes[ key ] );
  37250. for ( var key in baseGeometry.morphAttributes ) geometry.morphAttributes[ key ] = baseGeometry.morphAttributes[ key ];
  37251. var pendingIndices = [];
  37252. for ( var i = 0, il = originalPrimitives.length; i < il; i ++ ) {
  37253. pendingIndices.push( parser.getDependency( 'accessor', originalPrimitives[ i ].indices ) );
  37254. }
  37255. return Promise.all( pendingIndices ).then( function ( accessors ) {
  37256. var indices = [];
  37257. var offset = 0;
  37258. for ( var i = 0, il = originalPrimitives.length; i < il; i ++ ) {
  37259. var accessor = accessors[ i ];
  37260. for ( var j = 0, jl = accessor.count; j < jl; j ++ ) indices.push( accessor.array[ j ] );
  37261. geometry.addGroup( offset, accessor.count, i );
  37262. offset += accessor.count;
  37263. }
  37264. geometry.setIndex( indices );
  37265. cache.push( { geometry: geometry, baseGeometry: baseGeometry, primitives: originalPrimitives } );
  37266. return [ geometry ];
  37267. } );
  37268. } else if ( geometries.length > 1 && THREE.BufferGeometryUtils !== undefined ) {
  37269. // Tries to merge geometries with BufferGeometryUtils if possible
  37270. for ( var i = 1, il = primitives.length; i < il; i ++ ) {
  37271. // can't merge if draw mode is different
  37272. if ( primitives[ 0 ].mode !== primitives[ i ].mode ) return geometries;
  37273. }
  37274. // See if we've already created this combined geometry
  37275. var cache = parser.multiplePrimitivesCache;
  37276. var cached = getCachedCombinedGeometry( cache, geometries );
  37277. if ( cached ) {
  37278. if ( cached.geometry !== null ) return [ cached.geometry ];
  37279. } else {
  37280. var geometry = THREE.BufferGeometryUtils.mergeBufferGeometries( geometries, true );
  37281. cache.push( { geometry: geometry, baseGeometries: geometries } );
  37282. if ( geometry !== null ) return [ geometry ];
  37283. }
  37284. }
  37285. return geometries;
  37286. } );
  37287. };
  37288. /**
  37289. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  37290. * @param {number} meshIndex
  37291. * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>}
  37292. */
  37293. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  37294. var parser = this;
  37295. var json = this.json;
  37296. var extensions = this.extensions;
  37297. var meshDef = json.meshes[ meshIndex ];
  37298. var primitives = meshDef.primitives;
  37299. var pending = [];
  37300. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  37301. var material = primitives[ i ].material === undefined
  37302. ? createDefaultMaterial()
  37303. : this.getDependency( 'material', primitives[ i ].material );
  37304. pending.push( material );
  37305. }
  37306. return Promise.all( pending ).then( function ( originalMaterials ) {
  37307. return parser.loadGeometries( primitives ).then( function ( geometries ) {
  37308. var isMultiMaterial = geometries.length === 1 && geometries[ 0 ].groups.length > 0;
  37309. var meshes = [];
  37310. for ( var i = 0, il = geometries.length; i < il; i ++ ) {
  37311. var geometry = geometries[ i ];
  37312. var primitive = primitives[ i ];
  37313. // 1. create Mesh
  37314. var mesh;
  37315. var material = isMultiMaterial ? originalMaterials : originalMaterials[ i ];
  37316. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  37317. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  37318. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  37319. primitive.mode === undefined ) {
  37320. // .isSkinnedMesh isn't in glTF spec. See .markDefs()
  37321. mesh = meshDef.isSkinnedMesh === true
  37322. ? new THREE.SkinnedMesh( geometry, material )
  37323. : new THREE.Mesh( geometry, material );
  37324. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  37325. mesh.drawMode = THREE.TriangleStripDrawMode;
  37326. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  37327. mesh.drawMode = THREE.TriangleFanDrawMode;
  37328. }
  37329. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  37330. mesh = new THREE.LineSegments( geometry, material );
  37331. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  37332. mesh = new THREE.Line( geometry, material );
  37333. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  37334. mesh = new THREE.LineLoop( geometry, material );
  37335. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  37336. mesh = new THREE.Points( geometry, material );
  37337. } else {
  37338. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  37339. }
  37340. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  37341. updateMorphTargets( mesh, meshDef );
  37342. }
  37343. mesh.name = meshDef.name || ( 'mesh_' + meshIndex );
  37344. if ( geometries.length > 1 ) mesh.name += '_' + i;
  37345. assignExtrasToUserData( mesh, meshDef );
  37346. meshes.push( mesh );
  37347. // 2. update Material depending on Mesh and BufferGeometry
  37348. var materials = isMultiMaterial ? mesh.material : [ mesh.material ];
  37349. var useVertexColors = geometry.attributes.color !== undefined;
  37350. var useFlatShading = geometry.attributes.normal === undefined;
  37351. var useSkinning = mesh.isSkinnedMesh === true;
  37352. var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0;
  37353. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  37354. for ( var j = 0, jl = materials.length; j < jl; j ++ ) {
  37355. var material = materials[ j ];
  37356. if ( mesh.isPoints ) {
  37357. var cacheKey = 'PointsMaterial:' + material.uuid;
  37358. var pointsMaterial = parser.cache.get( cacheKey );
  37359. if ( ! pointsMaterial ) {
  37360. pointsMaterial = new THREE.PointsMaterial();
  37361. THREE.Material.prototype.copy.call( pointsMaterial, material );
  37362. pointsMaterial.color.copy( material.color );
  37363. pointsMaterial.map = material.map;
  37364. pointsMaterial.lights = false; // PointsMaterial doesn't support lights yet
  37365. parser.cache.add( cacheKey, pointsMaterial );
  37366. }
  37367. material = pointsMaterial;
  37368. } else if ( mesh.isLine ) {
  37369. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  37370. var lineMaterial = parser.cache.get( cacheKey );
  37371. if ( ! lineMaterial ) {
  37372. lineMaterial = new THREE.LineBasicMaterial();
  37373. THREE.Material.prototype.copy.call( lineMaterial, material );
  37374. lineMaterial.color.copy( material.color );
  37375. lineMaterial.lights = false; // LineBasicMaterial doesn't support lights yet
  37376. parser.cache.add( cacheKey, lineMaterial );
  37377. }
  37378. material = lineMaterial;
  37379. }
  37380. // Clone the material if it will be modified
  37381. if ( useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  37382. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  37383. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  37384. if ( useSkinning ) cacheKey += 'skinning:';
  37385. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  37386. if ( useFlatShading ) cacheKey += 'flat-shading:';
  37387. if ( useMorphTargets ) cacheKey += 'morph-targets:';
  37388. if ( useMorphNormals ) cacheKey += 'morph-normals:';
  37389. var cachedMaterial = parser.cache.get( cacheKey );
  37390. if ( ! cachedMaterial ) {
  37391. cachedMaterial = material.isGLTFSpecularGlossinessMaterial
  37392. ? extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].cloneMaterial( material )
  37393. : material.clone();
  37394. if ( useSkinning ) cachedMaterial.skinning = true;
  37395. if ( useVertexColors ) cachedMaterial.vertexColors = THREE.VertexColors;
  37396. if ( useFlatShading ) cachedMaterial.flatShading = true;
  37397. if ( useMorphTargets ) cachedMaterial.morphTargets = true;
  37398. if ( useMorphNormals ) cachedMaterial.morphNormals = true;
  37399. parser.cache.add( cacheKey, cachedMaterial );
  37400. }
  37401. material = cachedMaterial;
  37402. }
  37403. materials[ j ] = material;
  37404. // workarounds for mesh and geometry
  37405. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  37406. console.log( 'THREE.GLTFLoader: Duplicating UVs to support aoMap.' );
  37407. geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  37408. }
  37409. if ( material.isGLTFSpecularGlossinessMaterial ) {
  37410. // for GLTFSpecularGlossinessMaterial(ShaderMaterial) uniforms runtime update
  37411. mesh.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms;
  37412. }
  37413. }
  37414. mesh.material = isMultiMaterial ? materials : materials[ 0 ];
  37415. }
  37416. if ( meshes.length === 1 ) {
  37417. return meshes[ 0 ];
  37418. }
  37419. var group = new THREE.Group();
  37420. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  37421. group.add( meshes[ i ] );
  37422. }
  37423. return group;
  37424. } );
  37425. } );
  37426. };
  37427. /**
  37428. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  37429. * @param {number} cameraIndex
  37430. * @return {Promise<THREE.Camera>}
  37431. */
  37432. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  37433. var camera;
  37434. var cameraDef = this.json.cameras[ cameraIndex ];
  37435. var params = cameraDef[ cameraDef.type ];
  37436. if ( ! params ) {
  37437. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  37438. return;
  37439. }
  37440. if ( cameraDef.type === 'perspective' ) {
  37441. camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  37442. } else if ( cameraDef.type === 'orthographic' ) {
  37443. camera = new THREE.OrthographicCamera( params.xmag / - 2, params.xmag / 2, params.ymag / 2, params.ymag / - 2, params.znear, params.zfar );
  37444. }
  37445. if ( cameraDef.name !== undefined ) camera.name = cameraDef.name;
  37446. assignExtrasToUserData( camera, cameraDef );
  37447. return Promise.resolve( camera );
  37448. };
  37449. /**
  37450. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  37451. * @param {number} skinIndex
  37452. * @return {Promise<Object>}
  37453. */
  37454. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  37455. var skinDef = this.json.skins[ skinIndex ];
  37456. var skinEntry = { joints: skinDef.joints };
  37457. if ( skinDef.inverseBindMatrices === undefined ) {
  37458. return Promise.resolve( skinEntry );
  37459. }
  37460. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  37461. skinEntry.inverseBindMatrices = accessor;
  37462. return skinEntry;
  37463. } );
  37464. };
  37465. /**
  37466. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  37467. * @param {number} animationIndex
  37468. * @return {Promise<THREE.AnimationClip>}
  37469. */
  37470. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  37471. var json = this.json;
  37472. var animationDef = json.animations[ animationIndex ];
  37473. var pendingNodes = [];
  37474. var pendingInputAccessors = [];
  37475. var pendingOutputAccessors = [];
  37476. var pendingSamplers = [];
  37477. var pendingTargets = [];
  37478. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  37479. var channel = animationDef.channels[ i ];
  37480. var sampler = animationDef.samplers[ channel.sampler ];
  37481. var target = channel.target;
  37482. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  37483. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  37484. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  37485. pendingNodes.push( this.getDependency( 'node', name ) );
  37486. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  37487. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  37488. pendingSamplers.push( sampler );
  37489. pendingTargets.push( target );
  37490. }
  37491. return Promise.all( [
  37492. Promise.all( pendingNodes ),
  37493. Promise.all( pendingInputAccessors ),
  37494. Promise.all( pendingOutputAccessors ),
  37495. Promise.all( pendingSamplers ),
  37496. Promise.all( pendingTargets )
  37497. ] ).then( function ( dependencies ) {
  37498. var nodes = dependencies[ 0 ];
  37499. var inputAccessors = dependencies[ 1 ];
  37500. var outputAccessors = dependencies[ 2 ];
  37501. var samplers = dependencies[ 3 ];
  37502. var targets = dependencies[ 4 ];
  37503. var tracks = [];
  37504. for ( var i = 0, il = nodes.length; i < il; i ++ ) {
  37505. var node = nodes[ i ];
  37506. var inputAccessor = inputAccessors[ i ];
  37507. var outputAccessor = outputAccessors[ i ];
  37508. var sampler = samplers[ i ];
  37509. var target = targets[ i ];
  37510. if ( node === undefined ) continue;
  37511. node.updateMatrix();
  37512. node.matrixAutoUpdate = true;
  37513. var TypedKeyframeTrack;
  37514. switch ( PATH_PROPERTIES[ target.path ] ) {
  37515. case PATH_PROPERTIES.weights:
  37516. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  37517. break;
  37518. case PATH_PROPERTIES.rotation:
  37519. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  37520. break;
  37521. case PATH_PROPERTIES.position:
  37522. case PATH_PROPERTIES.scale:
  37523. default:
  37524. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  37525. break;
  37526. }
  37527. var targetName = node.name ? node.name : node.uuid;
  37528. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  37529. var targetNames = [];
  37530. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  37531. // node can be THREE.Group here but
  37532. // PATH_PROPERTIES.weights(morphTargetInfluences) should be
  37533. // the property of a mesh object under group.
  37534. node.traverse( function ( object ) {
  37535. if ( object.isMesh === true && object.morphTargetInfluences ) {
  37536. targetNames.push( object.name ? object.name : object.uuid );
  37537. }
  37538. } );
  37539. } else {
  37540. targetNames.push( targetName );
  37541. }
  37542. // KeyframeTrack.optimize() will modify given 'times' and 'values'
  37543. // buffers before creating a truncated copy to keep. Because buffers may
  37544. // be reused by other tracks, make copies here.
  37545. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  37546. var track = new TypedKeyframeTrack(
  37547. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  37548. THREE.AnimationUtils.arraySlice( inputAccessor.array, 0 ),
  37549. THREE.AnimationUtils.arraySlice( outputAccessor.array, 0 ),
  37550. interpolation
  37551. );
  37552. // Here is the trick to enable custom interpolation.
  37553. // Overrides .createInterpolant in a factory method which creates custom interpolation.
  37554. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  37555. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  37556. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  37557. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  37558. // must be divided by three to get the interpolant's sampleSize argument.
  37559. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  37560. };
  37561. // Workaround, provide an alternate way to know if the interpolant type is cubis spline to track.
  37562. // track.getInterpolation() doesn't return valid value for custom interpolant.
  37563. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  37564. }
  37565. tracks.push( track );
  37566. }
  37567. }
  37568. var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
  37569. return new THREE.AnimationClip( name, undefined, tracks );
  37570. } );
  37571. };
  37572. /**
  37573. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  37574. * @param {number} nodeIndex
  37575. * @return {Promise<THREE.Object3D>}
  37576. */
  37577. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  37578. var json = this.json;
  37579. var extensions = this.extensions;
  37580. var parser = this;
  37581. var meshReferences = json.meshReferences;
  37582. var meshUses = json.meshUses;
  37583. var nodeDef = json.nodes[ nodeIndex ];
  37584. return new Promise( function ( resolve ) {
  37585. // .isBone isn't in glTF spec. See .markDefs
  37586. if ( nodeDef.isBone === true ) {
  37587. resolve( new THREE.Bone() );
  37588. } else if ( nodeDef.mesh !== undefined ) {
  37589. parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  37590. var node;
  37591. if ( meshReferences[ nodeDef.mesh ] > 1 ) {
  37592. var instanceNum = meshUses[ nodeDef.mesh ] ++;
  37593. node = mesh.clone();
  37594. node.name += '_instance_' + instanceNum;
  37595. // onBeforeRender copy for Specular-Glossiness
  37596. node.onBeforeRender = mesh.onBeforeRender;
  37597. for ( var i = 0, il = node.children.length; i < il; i ++ ) {
  37598. node.children[ i ].name += '_instance_' + instanceNum;
  37599. node.children[ i ].onBeforeRender = mesh.children[ i ].onBeforeRender;
  37600. }
  37601. } else {
  37602. node = mesh;
  37603. }
  37604. resolve( node );
  37605. } );
  37606. } else if ( nodeDef.camera !== undefined ) {
  37607. parser.getDependency( 'camera', nodeDef.camera ).then( resolve );
  37608. } else if ( nodeDef.extensions
  37609. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ]
  37610. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light !== undefined ) {
  37611. parser.getDependency( 'light', nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light ).then( resolve );
  37612. } else {
  37613. resolve( new THREE.Object3D() );
  37614. }
  37615. } ).then( function ( node ) {
  37616. if ( nodeDef.name !== undefined ) {
  37617. node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name );
  37618. }
  37619. assignExtrasToUserData( node, nodeDef );
  37620. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  37621. if ( nodeDef.matrix !== undefined ) {
  37622. var matrix = new THREE.Matrix4();
  37623. matrix.fromArray( nodeDef.matrix );
  37624. node.applyMatrix( matrix );
  37625. } else {
  37626. if ( nodeDef.translation !== undefined ) {
  37627. node.position.fromArray( nodeDef.translation );
  37628. }
  37629. if ( nodeDef.rotation !== undefined ) {
  37630. node.quaternion.fromArray( nodeDef.rotation );
  37631. }
  37632. if ( nodeDef.scale !== undefined ) {
  37633. node.scale.fromArray( nodeDef.scale );
  37634. }
  37635. }
  37636. return node;
  37637. } );
  37638. };
  37639. /**
  37640. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  37641. * @param {number} sceneIndex
  37642. * @return {Promise<THREE.Scene>}
  37643. */
  37644. GLTFParser.prototype.loadScene = function () {
  37645. // scene node hierachy builder
  37646. function buildNodeHierachy( nodeId, parentObject, json, parser ) {
  37647. var nodeDef = json.nodes[ nodeId ];
  37648. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  37649. if ( nodeDef.skin === undefined ) return node;
  37650. // build skeleton here as well
  37651. var skinEntry;
  37652. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  37653. skinEntry = skin;
  37654. var pendingJoints = [];
  37655. for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  37656. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  37657. }
  37658. return Promise.all( pendingJoints );
  37659. } ).then( function ( jointNodes ) {
  37660. var meshes = node.isGroup === true ? node.children : [ node ];
  37661. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  37662. var mesh = meshes[ i ];
  37663. var bones = [];
  37664. var boneInverses = [];
  37665. for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  37666. var jointNode = jointNodes[ j ];
  37667. if ( jointNode ) {
  37668. bones.push( jointNode );
  37669. var mat = new THREE.Matrix4();
  37670. if ( skinEntry.inverseBindMatrices !== undefined ) {
  37671. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  37672. }
  37673. boneInverses.push( mat );
  37674. } else {
  37675. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  37676. }
  37677. }
  37678. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  37679. };
  37680. return node;
  37681. } );
  37682. } ).then( function ( node ) {
  37683. // build node hierachy
  37684. parentObject.add( node );
  37685. var pending = [];
  37686. if ( nodeDef.children ) {
  37687. var children = nodeDef.children;
  37688. for ( var i = 0, il = children.length; i < il; i ++ ) {
  37689. var child = children[ i ];
  37690. pending.push( buildNodeHierachy( child, node, json, parser ) );
  37691. }
  37692. }
  37693. return Promise.all( pending );
  37694. } );
  37695. }
  37696. return function loadScene( sceneIndex ) {
  37697. var json = this.json;
  37698. var extensions = this.extensions;
  37699. var sceneDef = this.json.scenes[ sceneIndex ];
  37700. var parser = this;
  37701. var scene = new THREE.Scene();
  37702. if ( sceneDef.name !== undefined ) scene.name = sceneDef.name;
  37703. assignExtrasToUserData( scene, sceneDef );
  37704. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  37705. var nodeIds = sceneDef.nodes || [];
  37706. var pending = [];
  37707. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  37708. pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) );
  37709. }
  37710. return Promise.all( pending ).then( function () {
  37711. return scene;
  37712. } );
  37713. };
  37714. }();
  37715. return GLTFLoader;
  37716. } )();
  37717. },{}],43:[function(_dereq_,module,exports){
  37718. /**
  37719. * Loads a Wavefront .mtl file specifying materials
  37720. *
  37721. * @author angelxuanchang
  37722. */
  37723. THREE.MTLLoader = function ( manager ) {
  37724. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  37725. };
  37726. THREE.MTLLoader.prototype = {
  37727. constructor: THREE.MTLLoader,
  37728. /**
  37729. * Loads and parses a MTL asset from a URL.
  37730. *
  37731. * @param {String} url - URL to the MTL file.
  37732. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  37733. * @param {Function} [onProgress] - Callback for download progress.
  37734. * @param {Function} [onError] - Callback for download errors.
  37735. *
  37736. * @see setPath setResourcePath
  37737. *
  37738. * @note In order for relative texture references to resolve correctly
  37739. * you must call setResourcePath() explicitly prior to load.
  37740. */
  37741. load: function ( url, onLoad, onProgress, onError ) {
  37742. var scope = this;
  37743. var path = ( this.path === undefined ) ? THREE.LoaderUtils.extractUrlBase( url ) : this.path;
  37744. var loader = new THREE.FileLoader( this.manager );
  37745. loader.setPath( this.path );
  37746. loader.load( url, function ( text ) {
  37747. onLoad( scope.parse( text, path ) );
  37748. }, onProgress, onError );
  37749. },
  37750. /**
  37751. * Set base path for resolving references.
  37752. * If set this path will be prepended to each loaded and found reference.
  37753. *
  37754. * @see setResourcePath
  37755. * @param {String} path
  37756. * @return {THREE.MTLLoader}
  37757. *
  37758. * @example
  37759. * mtlLoader.setPath( 'assets/obj/' );
  37760. * mtlLoader.load( 'my.mtl', ... );
  37761. */
  37762. setPath: function ( path ) {
  37763. this.path = path;
  37764. return this;
  37765. },
  37766. /**
  37767. * Set base path for additional resources like textures.
  37768. *
  37769. * @see setPath
  37770. * @param {String} path
  37771. * @return {THREE.MTLLoader}
  37772. *
  37773. * @example
  37774. * mtlLoader.setPath( 'assets/obj/' );
  37775. * mtlLoader.setResourcePath( 'assets/textures/' );
  37776. * mtlLoader.load( 'my.mtl', ... );
  37777. */
  37778. setResourcePath: function ( path ) {
  37779. this.resourcePath = path;
  37780. return this;
  37781. },
  37782. setTexturePath: function ( path ) {
  37783. console.warn( 'THREE.MTLLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  37784. return this.setResourcePath( path );
  37785. },
  37786. setCrossOrigin: function ( value ) {
  37787. this.crossOrigin = value;
  37788. return this;
  37789. },
  37790. setMaterialOptions: function ( value ) {
  37791. this.materialOptions = value;
  37792. return this;
  37793. },
  37794. /**
  37795. * Parses a MTL file.
  37796. *
  37797. * @param {String} text - Content of MTL file
  37798. * @return {THREE.MTLLoader.MaterialCreator}
  37799. *
  37800. * @see setPath setResourcePath
  37801. *
  37802. * @note In order for relative texture references to resolve correctly
  37803. * you must call setResourcePath() explicitly prior to parse.
  37804. */
  37805. parse: function ( text, path ) {
  37806. var lines = text.split( '\n' );
  37807. var info = {};
  37808. var delimiter_pattern = /\s+/;
  37809. var materialsInfo = {};
  37810. for ( var i = 0; i < lines.length; i ++ ) {
  37811. var line = lines[ i ];
  37812. line = line.trim();
  37813. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  37814. // Blank line or comment ignore
  37815. continue;
  37816. }
  37817. var pos = line.indexOf( ' ' );
  37818. var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  37819. key = key.toLowerCase();
  37820. var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
  37821. value = value.trim();
  37822. if ( key === 'newmtl' ) {
  37823. // New material
  37824. info = { name: value };
  37825. materialsInfo[ value ] = info;
  37826. } else {
  37827. if ( key === 'ka' || key === 'kd' || key === 'ks' ) {
  37828. var ss = value.split( delimiter_pattern, 3 );
  37829. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  37830. } else {
  37831. info[ key ] = value;
  37832. }
  37833. }
  37834. }
  37835. var materialCreator = new THREE.MTLLoader.MaterialCreator( this.resourcePath || path, this.materialOptions );
  37836. materialCreator.setCrossOrigin( this.crossOrigin );
  37837. materialCreator.setManager( this.manager );
  37838. materialCreator.setMaterials( materialsInfo );
  37839. return materialCreator;
  37840. }
  37841. };
  37842. /**
  37843. * Create a new THREE-MTLLoader.MaterialCreator
  37844. * @param baseUrl - Url relative to which textures are loaded
  37845. * @param options - Set of options on how to construct the materials
  37846. * side: Which side to apply the material
  37847. * THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
  37848. * wrap: What type of wrapping to apply for textures
  37849. * THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  37850. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  37851. * Default: false, assumed to be already normalized
  37852. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  37853. * Default: false
  37854. * @constructor
  37855. */
  37856. THREE.MTLLoader.MaterialCreator = function ( baseUrl, options ) {
  37857. this.baseUrl = baseUrl || '';
  37858. this.options = options;
  37859. this.materialsInfo = {};
  37860. this.materials = {};
  37861. this.materialsArray = [];
  37862. this.nameLookup = {};
  37863. this.side = ( this.options && this.options.side ) ? this.options.side : THREE.FrontSide;
  37864. this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : THREE.RepeatWrapping;
  37865. };
  37866. THREE.MTLLoader.MaterialCreator.prototype = {
  37867. constructor: THREE.MTLLoader.MaterialCreator,
  37868. crossOrigin: 'anonymous',
  37869. setCrossOrigin: function ( value ) {
  37870. this.crossOrigin = value;
  37871. return this;
  37872. },
  37873. setManager: function ( value ) {
  37874. this.manager = value;
  37875. },
  37876. setMaterials: function ( materialsInfo ) {
  37877. this.materialsInfo = this.convert( materialsInfo );
  37878. this.materials = {};
  37879. this.materialsArray = [];
  37880. this.nameLookup = {};
  37881. },
  37882. convert: function ( materialsInfo ) {
  37883. if ( ! this.options ) return materialsInfo;
  37884. var converted = {};
  37885. for ( var mn in materialsInfo ) {
  37886. // Convert materials info into normalized form based on options
  37887. var mat = materialsInfo[ mn ];
  37888. var covmat = {};
  37889. converted[ mn ] = covmat;
  37890. for ( var prop in mat ) {
  37891. var save = true;
  37892. var value = mat[ prop ];
  37893. var lprop = prop.toLowerCase();
  37894. switch ( lprop ) {
  37895. case 'kd':
  37896. case 'ka':
  37897. case 'ks':
  37898. // Diffuse color (color under white light) using RGB values
  37899. if ( this.options && this.options.normalizeRGB ) {
  37900. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  37901. }
  37902. if ( this.options && this.options.ignoreZeroRGBs ) {
  37903. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  37904. // ignore
  37905. save = false;
  37906. }
  37907. }
  37908. break;
  37909. default:
  37910. break;
  37911. }
  37912. if ( save ) {
  37913. covmat[ lprop ] = value;
  37914. }
  37915. }
  37916. }
  37917. return converted;
  37918. },
  37919. preload: function () {
  37920. for ( var mn in this.materialsInfo ) {
  37921. this.create( mn );
  37922. }
  37923. },
  37924. getIndex: function ( materialName ) {
  37925. return this.nameLookup[ materialName ];
  37926. },
  37927. getAsArray: function () {
  37928. var index = 0;
  37929. for ( var mn in this.materialsInfo ) {
  37930. this.materialsArray[ index ] = this.create( mn );
  37931. this.nameLookup[ mn ] = index;
  37932. index ++;
  37933. }
  37934. return this.materialsArray;
  37935. },
  37936. create: function ( materialName ) {
  37937. if ( this.materials[ materialName ] === undefined ) {
  37938. this.createMaterial_( materialName );
  37939. }
  37940. return this.materials[ materialName ];
  37941. },
  37942. createMaterial_: function ( materialName ) {
  37943. // Create material
  37944. var scope = this;
  37945. var mat = this.materialsInfo[ materialName ];
  37946. var params = {
  37947. name: materialName,
  37948. side: this.side
  37949. };
  37950. function resolveURL( baseUrl, url ) {
  37951. if ( typeof url !== 'string' || url === '' )
  37952. return '';
  37953. // Absolute URL
  37954. if ( /^https?:\/\//i.test( url ) ) return url;
  37955. return baseUrl + url;
  37956. }
  37957. function setMapForType( mapType, value ) {
  37958. if ( params[ mapType ] ) return; // Keep the first encountered texture
  37959. var texParams = scope.getTextureParams( value, params );
  37960. var map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  37961. map.repeat.copy( texParams.scale );
  37962. map.offset.copy( texParams.offset );
  37963. map.wrapS = scope.wrap;
  37964. map.wrapT = scope.wrap;
  37965. params[ mapType ] = map;
  37966. }
  37967. for ( var prop in mat ) {
  37968. var value = mat[ prop ];
  37969. var n;
  37970. if ( value === '' ) continue;
  37971. switch ( prop.toLowerCase() ) {
  37972. // Ns is material specular exponent
  37973. case 'kd':
  37974. // Diffuse color (color under white light) using RGB values
  37975. params.color = new THREE.Color().fromArray( value );
  37976. break;
  37977. case 'ks':
  37978. // Specular color (color when light is reflected from shiny surface) using RGB values
  37979. params.specular = new THREE.Color().fromArray( value );
  37980. break;
  37981. case 'map_kd':
  37982. // Diffuse texture map
  37983. setMapForType( "map", value );
  37984. break;
  37985. case 'map_ks':
  37986. // Specular map
  37987. setMapForType( "specularMap", value );
  37988. break;
  37989. case 'norm':
  37990. setMapForType( "normalMap", value );
  37991. break;
  37992. case 'map_bump':
  37993. case 'bump':
  37994. // Bump texture map
  37995. setMapForType( "bumpMap", value );
  37996. break;
  37997. case 'map_d':
  37998. // Alpha map
  37999. setMapForType( "alphaMap", value );
  38000. params.transparent = true;
  38001. break;
  38002. case 'ns':
  38003. // The specular exponent (defines the focus of the specular highlight)
  38004. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  38005. params.shininess = parseFloat( value );
  38006. break;
  38007. case 'd':
  38008. n = parseFloat( value );
  38009. if ( n < 1 ) {
  38010. params.opacity = n;
  38011. params.transparent = true;
  38012. }
  38013. break;
  38014. case 'tr':
  38015. n = parseFloat( value );
  38016. if ( this.options && this.options.invertTrProperty ) n = 1 - n;
  38017. if ( n > 0 ) {
  38018. params.opacity = 1 - n;
  38019. params.transparent = true;
  38020. }
  38021. break;
  38022. default:
  38023. break;
  38024. }
  38025. }
  38026. this.materials[ materialName ] = new THREE.MeshPhongMaterial( params );
  38027. return this.materials[ materialName ];
  38028. },
  38029. getTextureParams: function ( value, matParams ) {
  38030. var texParams = {
  38031. scale: new THREE.Vector2( 1, 1 ),
  38032. offset: new THREE.Vector2( 0, 0 )
  38033. };
  38034. var items = value.split( /\s+/ );
  38035. var pos;
  38036. pos = items.indexOf( '-bm' );
  38037. if ( pos >= 0 ) {
  38038. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  38039. items.splice( pos, 2 );
  38040. }
  38041. pos = items.indexOf( '-s' );
  38042. if ( pos >= 0 ) {
  38043. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  38044. items.splice( pos, 4 ); // we expect 3 parameters here!
  38045. }
  38046. pos = items.indexOf( '-o' );
  38047. if ( pos >= 0 ) {
  38048. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  38049. items.splice( pos, 4 ); // we expect 3 parameters here!
  38050. }
  38051. texParams.url = items.join( ' ' ).trim();
  38052. return texParams;
  38053. },
  38054. loadTexture: function ( url, mapping, onLoad, onProgress, onError ) {
  38055. var texture;
  38056. var loader = THREE.Loader.Handlers.get( url );
  38057. var manager = ( this.manager !== undefined ) ? this.manager : THREE.DefaultLoadingManager;
  38058. if ( loader === null ) {
  38059. loader = new THREE.TextureLoader( manager );
  38060. }
  38061. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  38062. texture = loader.load( url, onLoad, onProgress, onError );
  38063. if ( mapping !== undefined ) texture.mapping = mapping;
  38064. return texture;
  38065. }
  38066. };
  38067. },{}],44:[function(_dereq_,module,exports){
  38068. /**
  38069. * @author mrdoob / http://mrdoob.com/
  38070. */
  38071. THREE.OBJLoader = ( function () {
  38072. // o object_name | g group_name
  38073. var object_pattern = /^[og]\s*(.+)?/;
  38074. // mtllib file_reference
  38075. var material_library_pattern = /^mtllib /;
  38076. // usemtl material_name
  38077. var material_use_pattern = /^usemtl /;
  38078. function ParserState() {
  38079. var state = {
  38080. objects: [],
  38081. object: {},
  38082. vertices: [],
  38083. normals: [],
  38084. colors: [],
  38085. uvs: [],
  38086. materialLibraries: [],
  38087. startObject: function ( name, fromDeclaration ) {
  38088. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  38089. // file. We need to use it for the first parsed g/o to keep things in sync.
  38090. if ( this.object && this.object.fromDeclaration === false ) {
  38091. this.object.name = name;
  38092. this.object.fromDeclaration = ( fromDeclaration !== false );
  38093. return;
  38094. }
  38095. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  38096. if ( this.object && typeof this.object._finalize === 'function' ) {
  38097. this.object._finalize( true );
  38098. }
  38099. this.object = {
  38100. name: name || '',
  38101. fromDeclaration: ( fromDeclaration !== false ),
  38102. geometry: {
  38103. vertices: [],
  38104. normals: [],
  38105. colors: [],
  38106. uvs: []
  38107. },
  38108. materials: [],
  38109. smooth: true,
  38110. startMaterial: function ( name, libraries ) {
  38111. var previous = this._finalize( false );
  38112. // New usemtl declaration overwrites an inherited material, except if faces were declared
  38113. // after the material, then it must be preserved for proper MultiMaterial continuation.
  38114. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  38115. this.materials.splice( previous.index, 1 );
  38116. }
  38117. var material = {
  38118. index: this.materials.length,
  38119. name: name || '',
  38120. mtllib: ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  38121. smooth: ( previous !== undefined ? previous.smooth : this.smooth ),
  38122. groupStart: ( previous !== undefined ? previous.groupEnd : 0 ),
  38123. groupEnd: - 1,
  38124. groupCount: - 1,
  38125. inherited: false,
  38126. clone: function ( index ) {
  38127. var cloned = {
  38128. index: ( typeof index === 'number' ? index : this.index ),
  38129. name: this.name,
  38130. mtllib: this.mtllib,
  38131. smooth: this.smooth,
  38132. groupStart: 0,
  38133. groupEnd: - 1,
  38134. groupCount: - 1,
  38135. inherited: false
  38136. };
  38137. cloned.clone = this.clone.bind( cloned );
  38138. return cloned;
  38139. }
  38140. };
  38141. this.materials.push( material );
  38142. return material;
  38143. },
  38144. currentMaterial: function () {
  38145. if ( this.materials.length > 0 ) {
  38146. return this.materials[ this.materials.length - 1 ];
  38147. }
  38148. return undefined;
  38149. },
  38150. _finalize: function ( end ) {
  38151. var lastMultiMaterial = this.currentMaterial();
  38152. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === - 1 ) {
  38153. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  38154. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  38155. lastMultiMaterial.inherited = false;
  38156. }
  38157. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  38158. if ( end && this.materials.length > 1 ) {
  38159. for ( var mi = this.materials.length - 1; mi >= 0; mi -- ) {
  38160. if ( this.materials[ mi ].groupCount <= 0 ) {
  38161. this.materials.splice( mi, 1 );
  38162. }
  38163. }
  38164. }
  38165. // Guarantee at least one empty material, this makes the creation later more straight forward.
  38166. if ( end && this.materials.length === 0 ) {
  38167. this.materials.push( {
  38168. name: '',
  38169. smooth: this.smooth
  38170. } );
  38171. }
  38172. return lastMultiMaterial;
  38173. }
  38174. };
  38175. // Inherit previous objects material.
  38176. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  38177. // If a usemtl declaration is encountered while this new object is being parsed, it will
  38178. // overwrite the inherited material. Exception being that there was already face declarations
  38179. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  38180. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function' ) {
  38181. var declared = previousMaterial.clone( 0 );
  38182. declared.inherited = true;
  38183. this.object.materials.push( declared );
  38184. }
  38185. this.objects.push( this.object );
  38186. },
  38187. finalize: function () {
  38188. if ( this.object && typeof this.object._finalize === 'function' ) {
  38189. this.object._finalize( true );
  38190. }
  38191. },
  38192. parseVertexIndex: function ( value, len ) {
  38193. var index = parseInt( value, 10 );
  38194. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  38195. },
  38196. parseNormalIndex: function ( value, len ) {
  38197. var index = parseInt( value, 10 );
  38198. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  38199. },
  38200. parseUVIndex: function ( value, len ) {
  38201. var index = parseInt( value, 10 );
  38202. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  38203. },
  38204. addVertex: function ( a, b, c ) {
  38205. var src = this.vertices;
  38206. var dst = this.object.geometry.vertices;
  38207. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  38208. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  38209. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  38210. },
  38211. addVertexPoint: function ( a ) {
  38212. var src = this.vertices;
  38213. var dst = this.object.geometry.vertices;
  38214. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  38215. },
  38216. addVertexLine: function ( a ) {
  38217. var src = this.vertices;
  38218. var dst = this.object.geometry.vertices;
  38219. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  38220. },
  38221. addNormal: function ( a, b, c ) {
  38222. var src = this.normals;
  38223. var dst = this.object.geometry.normals;
  38224. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  38225. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  38226. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  38227. },
  38228. addColor: function ( a, b, c ) {
  38229. var src = this.colors;
  38230. var dst = this.object.geometry.colors;
  38231. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  38232. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  38233. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  38234. },
  38235. addUV: function ( a, b, c ) {
  38236. var src = this.uvs;
  38237. var dst = this.object.geometry.uvs;
  38238. dst.push( src[ a + 0 ], src[ a + 1 ] );
  38239. dst.push( src[ b + 0 ], src[ b + 1 ] );
  38240. dst.push( src[ c + 0 ], src[ c + 1 ] );
  38241. },
  38242. addUVLine: function ( a ) {
  38243. var src = this.uvs;
  38244. var dst = this.object.geometry.uvs;
  38245. dst.push( src[ a + 0 ], src[ a + 1 ] );
  38246. },
  38247. addFace: function ( a, b, c, ua, ub, uc, na, nb, nc ) {
  38248. var vLen = this.vertices.length;
  38249. var ia = this.parseVertexIndex( a, vLen );
  38250. var ib = this.parseVertexIndex( b, vLen );
  38251. var ic = this.parseVertexIndex( c, vLen );
  38252. this.addVertex( ia, ib, ic );
  38253. if ( ua !== undefined && ua !== '' ) {
  38254. var uvLen = this.uvs.length;
  38255. ia = this.parseUVIndex( ua, uvLen );
  38256. ib = this.parseUVIndex( ub, uvLen );
  38257. ic = this.parseUVIndex( uc, uvLen );
  38258. this.addUV( ia, ib, ic );
  38259. }
  38260. if ( na !== undefined && na !== '' ) {
  38261. // Normals are many times the same. If so, skip function call and parseInt.
  38262. var nLen = this.normals.length;
  38263. ia = this.parseNormalIndex( na, nLen );
  38264. ib = na === nb ? ia : this.parseNormalIndex( nb, nLen );
  38265. ic = na === nc ? ia : this.parseNormalIndex( nc, nLen );
  38266. this.addNormal( ia, ib, ic );
  38267. }
  38268. if ( this.colors.length > 0 ) {
  38269. this.addColor( ia, ib, ic );
  38270. }
  38271. },
  38272. addPointGeometry: function ( vertices ) {
  38273. this.object.geometry.type = 'Points';
  38274. var vLen = this.vertices.length;
  38275. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  38276. this.addVertexPoint( this.parseVertexIndex( vertices[ vi ], vLen ) );
  38277. }
  38278. },
  38279. addLineGeometry: function ( vertices, uvs ) {
  38280. this.object.geometry.type = 'Line';
  38281. var vLen = this.vertices.length;
  38282. var uvLen = this.uvs.length;
  38283. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  38284. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  38285. }
  38286. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  38287. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  38288. }
  38289. }
  38290. };
  38291. state.startObject( '', false );
  38292. return state;
  38293. }
  38294. //
  38295. function OBJLoader( manager ) {
  38296. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  38297. this.materials = null;
  38298. }
  38299. OBJLoader.prototype = {
  38300. constructor: OBJLoader,
  38301. load: function ( url, onLoad, onProgress, onError ) {
  38302. var scope = this;
  38303. var loader = new THREE.FileLoader( scope.manager );
  38304. loader.setPath( this.path );
  38305. loader.load( url, function ( text ) {
  38306. onLoad( scope.parse( text ) );
  38307. }, onProgress, onError );
  38308. },
  38309. setPath: function ( value ) {
  38310. this.path = value;
  38311. return this;
  38312. },
  38313. setMaterials: function ( materials ) {
  38314. this.materials = materials;
  38315. return this;
  38316. },
  38317. parse: function ( text ) {
  38318. console.time( 'OBJLoader' );
  38319. var state = new ParserState();
  38320. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  38321. // This is faster than String.split with regex that splits on both
  38322. text = text.replace( /\r\n/g, '\n' );
  38323. }
  38324. if ( text.indexOf( '\\\n' ) !== - 1 ) {
  38325. // join lines separated by a line continuation character (\)
  38326. text = text.replace( /\\\n/g, '' );
  38327. }
  38328. var lines = text.split( '\n' );
  38329. var line = '', lineFirstChar = '';
  38330. var lineLength = 0;
  38331. var result = [];
  38332. // Faster to just trim left side of the line. Use if available.
  38333. var trimLeft = ( typeof ''.trimLeft === 'function' );
  38334. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  38335. line = lines[ i ];
  38336. line = trimLeft ? line.trimLeft() : line.trim();
  38337. lineLength = line.length;
  38338. if ( lineLength === 0 ) continue;
  38339. lineFirstChar = line.charAt( 0 );
  38340. // @todo invoke passed in handler if any
  38341. if ( lineFirstChar === '#' ) continue;
  38342. if ( lineFirstChar === 'v' ) {
  38343. var data = line.split( /\s+/ );
  38344. switch ( data[ 0 ] ) {
  38345. case 'v':
  38346. state.vertices.push(
  38347. parseFloat( data[ 1 ] ),
  38348. parseFloat( data[ 2 ] ),
  38349. parseFloat( data[ 3 ] )
  38350. );
  38351. if ( data.length === 8 ) {
  38352. state.colors.push(
  38353. parseFloat( data[ 4 ] ),
  38354. parseFloat( data[ 5 ] ),
  38355. parseFloat( data[ 6 ] )
  38356. );
  38357. }
  38358. break;
  38359. case 'vn':
  38360. state.normals.push(
  38361. parseFloat( data[ 1 ] ),
  38362. parseFloat( data[ 2 ] ),
  38363. parseFloat( data[ 3 ] )
  38364. );
  38365. break;
  38366. case 'vt':
  38367. state.uvs.push(
  38368. parseFloat( data[ 1 ] ),
  38369. parseFloat( data[ 2 ] )
  38370. );
  38371. break;
  38372. }
  38373. } else if ( lineFirstChar === 'f' ) {
  38374. var lineData = line.substr( 1 ).trim();
  38375. var vertexData = lineData.split( /\s+/ );
  38376. var faceVertices = [];
  38377. // Parse the face vertex data into an easy to work with format
  38378. for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) {
  38379. var vertex = vertexData[ j ];
  38380. if ( vertex.length > 0 ) {
  38381. var vertexParts = vertex.split( '/' );
  38382. faceVertices.push( vertexParts );
  38383. }
  38384. }
  38385. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  38386. var v1 = faceVertices[ 0 ];
  38387. for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
  38388. var v2 = faceVertices[ j ];
  38389. var v3 = faceVertices[ j + 1 ];
  38390. state.addFace(
  38391. v1[ 0 ], v2[ 0 ], v3[ 0 ],
  38392. v1[ 1 ], v2[ 1 ], v3[ 1 ],
  38393. v1[ 2 ], v2[ 2 ], v3[ 2 ]
  38394. );
  38395. }
  38396. } else if ( lineFirstChar === 'l' ) {
  38397. var lineParts = line.substring( 1 ).trim().split( " " );
  38398. var lineVertices = [], lineUVs = [];
  38399. if ( line.indexOf( "/" ) === - 1 ) {
  38400. lineVertices = lineParts;
  38401. } else {
  38402. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  38403. var parts = lineParts[ li ].split( "/" );
  38404. if ( parts[ 0 ] !== "" ) lineVertices.push( parts[ 0 ] );
  38405. if ( parts[ 1 ] !== "" ) lineUVs.push( parts[ 1 ] );
  38406. }
  38407. }
  38408. state.addLineGeometry( lineVertices, lineUVs );
  38409. } else if ( lineFirstChar === 'p' ) {
  38410. var lineData = line.substr( 1 ).trim();
  38411. var pointData = lineData.split( " " );
  38412. state.addPointGeometry( pointData );
  38413. } else if ( ( result = object_pattern.exec( line ) ) !== null ) {
  38414. // o object_name
  38415. // or
  38416. // g group_name
  38417. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  38418. // var name = result[ 0 ].substr( 1 ).trim();
  38419. var name = ( " " + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  38420. state.startObject( name );
  38421. } else if ( material_use_pattern.test( line ) ) {
  38422. // material
  38423. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  38424. } else if ( material_library_pattern.test( line ) ) {
  38425. // mtl file
  38426. state.materialLibraries.push( line.substring( 7 ).trim() );
  38427. } else if ( lineFirstChar === 's' ) {
  38428. result = line.split( ' ' );
  38429. // smooth shading
  38430. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  38431. // but does not define a usemtl for each face set.
  38432. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  38433. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  38434. // where explicit usemtl defines geometry groups.
  38435. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  38436. /*
  38437. * http://paulbourke.net/dataformats/obj/
  38438. * or
  38439. * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
  38440. *
  38441. * From chapter "Grouping" Syntax explanation "s group_number":
  38442. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  38443. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  38444. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  38445. * than 0."
  38446. */
  38447. if ( result.length > 1 ) {
  38448. var value = result[ 1 ].trim().toLowerCase();
  38449. state.object.smooth = ( value !== '0' && value !== 'off' );
  38450. } else {
  38451. // ZBrush can produce "s" lines #11707
  38452. state.object.smooth = true;
  38453. }
  38454. var material = state.object.currentMaterial();
  38455. if ( material ) material.smooth = state.object.smooth;
  38456. } else {
  38457. // Handle null terminated files without exception
  38458. if ( line === '\0' ) continue;
  38459. throw new Error( 'THREE.OBJLoader: Unexpected line: "' + line + '"' );
  38460. }
  38461. }
  38462. state.finalize();
  38463. var container = new THREE.Group();
  38464. container.materialLibraries = [].concat( state.materialLibraries );
  38465. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  38466. var object = state.objects[ i ];
  38467. var geometry = object.geometry;
  38468. var materials = object.materials;
  38469. var isLine = ( geometry.type === 'Line' );
  38470. var isPoints = ( geometry.type === 'Points' );
  38471. var hasVertexColors = false;
  38472. // Skip o/g line declarations that did not follow with any faces
  38473. if ( geometry.vertices.length === 0 ) continue;
  38474. var buffergeometry = new THREE.BufferGeometry();
  38475. buffergeometry.addAttribute( 'position', new THREE.Float32BufferAttribute( geometry.vertices, 3 ) );
  38476. if ( geometry.normals.length > 0 ) {
  38477. buffergeometry.addAttribute( 'normal', new THREE.Float32BufferAttribute( geometry.normals, 3 ) );
  38478. } else {
  38479. buffergeometry.computeVertexNormals();
  38480. }
  38481. if ( geometry.colors.length > 0 ) {
  38482. hasVertexColors = true;
  38483. buffergeometry.addAttribute( 'color', new THREE.Float32BufferAttribute( geometry.colors, 3 ) );
  38484. }
  38485. if ( geometry.uvs.length > 0 ) {
  38486. buffergeometry.addAttribute( 'uv', new THREE.Float32BufferAttribute( geometry.uvs, 2 ) );
  38487. }
  38488. // Create materials
  38489. var createdMaterials = [];
  38490. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  38491. var sourceMaterial = materials[ mi ];
  38492. var material = undefined;
  38493. if ( this.materials !== null ) {
  38494. material = this.materials.create( sourceMaterial.name );
  38495. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  38496. if ( isLine && material && ! ( material instanceof THREE.LineBasicMaterial ) ) {
  38497. var materialLine = new THREE.LineBasicMaterial();
  38498. materialLine.copy( material );
  38499. materialLine.lights = false; // TOFIX
  38500. material = materialLine;
  38501. } else if ( isPoints && material && ! ( material instanceof THREE.PointsMaterial ) ) {
  38502. var materialPoints = new THREE.PointsMaterial( { size: 10, sizeAttenuation: false } );
  38503. materialLine.copy( material );
  38504. material = materialPoints;
  38505. }
  38506. }
  38507. if ( ! material ) {
  38508. if ( isLine ) {
  38509. material = new THREE.LineBasicMaterial();
  38510. } else if ( isPoints ) {
  38511. material = new THREE.PointsMaterial( { size: 1, sizeAttenuation: false } );
  38512. } else {
  38513. material = new THREE.MeshPhongMaterial();
  38514. }
  38515. material.name = sourceMaterial.name;
  38516. }
  38517. material.flatShading = sourceMaterial.smooth ? false : true;
  38518. material.vertexColors = hasVertexColors ? THREE.VertexColors : THREE.NoColors;
  38519. createdMaterials.push( material );
  38520. }
  38521. // Create mesh
  38522. var mesh;
  38523. if ( createdMaterials.length > 1 ) {
  38524. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  38525. var sourceMaterial = materials[ mi ];
  38526. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  38527. }
  38528. if ( isLine ) {
  38529. mesh = new THREE.LineSegments( buffergeometry, createdMaterials );
  38530. } else if ( isPoints ) {
  38531. mesh = new THREE.Points( buffergeometry, createdMaterials );
  38532. } else {
  38533. mesh = new THREE.Mesh( buffergeometry, createdMaterials );
  38534. }
  38535. } else {
  38536. if ( isLine ) {
  38537. mesh = new THREE.LineSegments( buffergeometry, createdMaterials[ 0 ] );
  38538. } else if ( isPoints ) {
  38539. mesh = new THREE.Points( buffergeometry, createdMaterials[ 0 ] );
  38540. } else {
  38541. mesh = new THREE.Mesh( buffergeometry, createdMaterials[ 0 ] );
  38542. }
  38543. }
  38544. mesh.name = object.name;
  38545. container.add( mesh );
  38546. }
  38547. console.timeEnd( 'OBJLoader' );
  38548. return container;
  38549. }
  38550. };
  38551. return OBJLoader;
  38552. } )();
  38553. },{}],45:[function(_dereq_,module,exports){
  38554. exports = module.exports = trim;
  38555. function trim(str){
  38556. return str.replace(/^\s*|\s*$/g, '');
  38557. }
  38558. exports.left = function(str){
  38559. return str.replace(/^\s*/, '');
  38560. };
  38561. exports.right = function(str){
  38562. return str.replace(/\s*$/, '');
  38563. };
  38564. },{}],46:[function(_dereq_,module,exports){
  38565. (function (global){
  38566. /**
  38567. * @license
  38568. * webvr-polyfill
  38569. * Copyright (c) 2015-2017 Google
  38570. * Licensed under the Apache License, Version 2.0 (the "License");
  38571. * you may not use this file except in compliance with the License.
  38572. * You may obtain a copy of the License at
  38573. *
  38574. * http://www.apache.org/licenses/LICENSE-2.0
  38575. *
  38576. * Unless required by applicable law or agreed to in writing, software
  38577. * distributed under the License is distributed on an "AS IS" BASIS,
  38578. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  38579. * See the License for the specific language governing permissions and
  38580. * limitations under the License.
  38581. */
  38582. /**
  38583. * @license
  38584. * cardboard-vr-display
  38585. * Copyright (c) 2015-2017 Google
  38586. * Licensed under the Apache License, Version 2.0 (the "License");
  38587. * you may not use this file except in compliance with the License.
  38588. * You may obtain a copy of the License at
  38589. *
  38590. * http://www.apache.org/licenses/LICENSE-2.0
  38591. *
  38592. * Unless required by applicable law or agreed to in writing, software
  38593. * distributed under the License is distributed on an "AS IS" BASIS,
  38594. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  38595. * See the License for the specific language governing permissions and
  38596. * limitations under the License.
  38597. */
  38598. /**
  38599. * @license
  38600. * webvr-polyfill-dpdb
  38601. * Copyright (c) 2017 Google
  38602. * Licensed under the Apache License, Version 2.0 (the "License");
  38603. * you may not use this file except in compliance with the License.
  38604. * You may obtain a copy of the License at
  38605. *
  38606. * http://www.apache.org/licenses/LICENSE-2.0
  38607. *
  38608. * Unless required by applicable law or agreed to in writing, software
  38609. * distributed under the License is distributed on an "AS IS" BASIS,
  38610. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  38611. * See the License for the specific language governing permissions and
  38612. * limitations under the License.
  38613. */
  38614. /**
  38615. * @license
  38616. * wglu-preserve-state
  38617. * Copyright (c) 2016, Brandon Jones.
  38618. *
  38619. * Permission is hereby granted, free of charge, to any person obtaining a copy
  38620. * of this software and associated documentation files (the "Software"), to deal
  38621. * in the Software without restriction, including without limitation the rights
  38622. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  38623. * copies of the Software, and to permit persons to whom the Software is
  38624. * furnished to do so, subject to the following conditions:
  38625. *
  38626. * The above copyright notice and this permission notice shall be included in
  38627. * all copies or substantial portions of the Software.
  38628. *
  38629. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  38630. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  38631. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  38632. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  38633. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  38634. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  38635. * THE SOFTWARE.
  38636. */
  38637. /**
  38638. * @license
  38639. * nosleep.js
  38640. * Copyright (c) 2017, Rich Tibbett
  38641. *
  38642. * Permission is hereby granted, free of charge, to any person obtaining a copy
  38643. * of this software and associated documentation files (the "Software"), to deal
  38644. * in the Software without restriction, including without limitation the rights
  38645. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  38646. * copies of the Software, and to permit persons to whom the Software is
  38647. * furnished to do so, subject to the following conditions:
  38648. *
  38649. * The above copyright notice and this permission notice shall be included in
  38650. * all copies or substantial portions of the Software.
  38651. *
  38652. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  38653. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  38654. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  38655. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  38656. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  38657. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  38658. * THE SOFTWARE.
  38659. */
  38660. (function (global, factory) {
  38661. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  38662. typeof define === 'function' && define.amd ? define(factory) :
  38663. (global.WebVRPolyfill = factory());
  38664. }(this, (function () { 'use strict';
  38665. var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  38666. function unwrapExports (x) {
  38667. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  38668. }
  38669. function createCommonjsModule(fn, module) {
  38670. return module = { exports: {} }, fn(module, module.exports), module.exports;
  38671. }
  38672. var race = function race(promises) {
  38673. if (Promise.race) {
  38674. return Promise.race(promises);
  38675. }
  38676. return new Promise(function (resolve, reject) {
  38677. for (var i = 0; i < promises.length; i++) {
  38678. promises[i].then(resolve, reject);
  38679. }
  38680. });
  38681. };
  38682. var isMobile = function isMobile() {
  38683. return (/Android/i.test(navigator.userAgent) || /iPhone|iPad|iPod/i.test(navigator.userAgent)
  38684. );
  38685. };
  38686. var copyArray = function copyArray(source, dest) {
  38687. for (var i = 0, n = source.length; i < n; i++) {
  38688. dest[i] = source[i];
  38689. }
  38690. };
  38691. var extend = function extend(dest, src) {
  38692. for (var key in src) {
  38693. if (src.hasOwnProperty(key)) {
  38694. dest[key] = src[key];
  38695. }
  38696. }
  38697. return dest;
  38698. };
  38699. var cardboardVrDisplay = createCommonjsModule(function (module, exports) {
  38700. /**
  38701. * @license
  38702. * cardboard-vr-display
  38703. * Copyright (c) 2015-2017 Google
  38704. * Licensed under the Apache License, Version 2.0 (the "License");
  38705. * you may not use this file except in compliance with the License.
  38706. * You may obtain a copy of the License at
  38707. *
  38708. * http://www.apache.org/licenses/LICENSE-2.0
  38709. *
  38710. * Unless required by applicable law or agreed to in writing, software
  38711. * distributed under the License is distributed on an "AS IS" BASIS,
  38712. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  38713. * See the License for the specific language governing permissions and
  38714. * limitations under the License.
  38715. */
  38716. /**
  38717. * @license
  38718. * gl-preserve-state
  38719. * Copyright (c) 2016, Brandon Jones.
  38720. *
  38721. * Permission is hereby granted, free of charge, to any person obtaining a copy
  38722. * of this software and associated documentation files (the "Software"), to deal
  38723. * in the Software without restriction, including without limitation the rights
  38724. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  38725. * copies of the Software, and to permit persons to whom the Software is
  38726. * furnished to do so, subject to the following conditions:
  38727. *
  38728. * The above copyright notice and this permission notice shall be included in
  38729. * all copies or substantial portions of the Software.
  38730. *
  38731. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  38732. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  38733. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  38734. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  38735. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  38736. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  38737. * THE SOFTWARE.
  38738. */
  38739. /**
  38740. * @license
  38741. * webvr-polyfill-dpdb
  38742. * Copyright (c) 2015-2017 Google
  38743. * Licensed under the Apache License, Version 2.0 (the "License");
  38744. * you may not use this file except in compliance with the License.
  38745. * You may obtain a copy of the License at
  38746. *
  38747. * http://www.apache.org/licenses/LICENSE-2.0
  38748. *
  38749. * Unless required by applicable law or agreed to in writing, software
  38750. * distributed under the License is distributed on an "AS IS" BASIS,
  38751. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  38752. * See the License for the specific language governing permissions and
  38753. * limitations under the License.
  38754. */
  38755. /**
  38756. * @license
  38757. * nosleep.js
  38758. * Copyright (c) 2017, Rich Tibbett
  38759. *
  38760. * Permission is hereby granted, free of charge, to any person obtaining a copy
  38761. * of this software and associated documentation files (the "Software"), to deal
  38762. * in the Software without restriction, including without limitation the rights
  38763. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  38764. * copies of the Software, and to permit persons to whom the Software is
  38765. * furnished to do so, subject to the following conditions:
  38766. *
  38767. * The above copyright notice and this permission notice shall be included in
  38768. * all copies or substantial portions of the Software.
  38769. *
  38770. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  38771. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  38772. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  38773. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  38774. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  38775. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  38776. * THE SOFTWARE.
  38777. */
  38778. (function (global, factory) {
  38779. module.exports = factory();
  38780. }(commonjsGlobal, (function () { var classCallCheck = function (instance, Constructor) {
  38781. if (!(instance instanceof Constructor)) {
  38782. throw new TypeError("Cannot call a class as a function");
  38783. }
  38784. };
  38785. var createClass = function () {
  38786. function defineProperties(target, props) {
  38787. for (var i = 0; i < props.length; i++) {
  38788. var descriptor = props[i];
  38789. descriptor.enumerable = descriptor.enumerable || false;
  38790. descriptor.configurable = true;
  38791. if ("value" in descriptor) descriptor.writable = true;
  38792. Object.defineProperty(target, descriptor.key, descriptor);
  38793. }
  38794. }
  38795. return function (Constructor, protoProps, staticProps) {
  38796. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  38797. if (staticProps) defineProperties(Constructor, staticProps);
  38798. return Constructor;
  38799. };
  38800. }();
  38801. var slicedToArray = function () {
  38802. function sliceIterator(arr, i) {
  38803. var _arr = [];
  38804. var _n = true;
  38805. var _d = false;
  38806. var _e = undefined;
  38807. try {
  38808. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  38809. _arr.push(_s.value);
  38810. if (i && _arr.length === i) break;
  38811. }
  38812. } catch (err) {
  38813. _d = true;
  38814. _e = err;
  38815. } finally {
  38816. try {
  38817. if (!_n && _i["return"]) _i["return"]();
  38818. } finally {
  38819. if (_d) throw _e;
  38820. }
  38821. }
  38822. return _arr;
  38823. }
  38824. return function (arr, i) {
  38825. if (Array.isArray(arr)) {
  38826. return arr;
  38827. } else if (Symbol.iterator in Object(arr)) {
  38828. return sliceIterator(arr, i);
  38829. } else {
  38830. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  38831. }
  38832. };
  38833. }();
  38834. var MIN_TIMESTEP = 0.001;
  38835. var MAX_TIMESTEP = 1;
  38836. var base64 = function base64(mimeType, _base) {
  38837. return 'data:' + mimeType + ';base64,' + _base;
  38838. };
  38839. var lerp = function lerp(a, b, t) {
  38840. return a + (b - a) * t;
  38841. };
  38842. var isIOS = function () {
  38843. var isIOS = /iPad|iPhone|iPod/.test(navigator.platform);
  38844. return function () {
  38845. return isIOS;
  38846. };
  38847. }();
  38848. var isWebViewAndroid = function () {
  38849. var isWebViewAndroid = navigator.userAgent.indexOf('Version') !== -1 && navigator.userAgent.indexOf('Android') !== -1 && navigator.userAgent.indexOf('Chrome') !== -1;
  38850. return function () {
  38851. return isWebViewAndroid;
  38852. };
  38853. }();
  38854. var isSafari = function () {
  38855. var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  38856. return function () {
  38857. return isSafari;
  38858. };
  38859. }();
  38860. var isFirefoxAndroid = function () {
  38861. var isFirefoxAndroid = navigator.userAgent.indexOf('Firefox') !== -1 && navigator.userAgent.indexOf('Android') !== -1;
  38862. return function () {
  38863. return isFirefoxAndroid;
  38864. };
  38865. }();
  38866. var getChromeVersion = function () {
  38867. var match = navigator.userAgent.match(/.*Chrome\/([0-9]+)/);
  38868. var value = match ? parseInt(match[1], 10) : null;
  38869. return function () {
  38870. return value;
  38871. };
  38872. }();
  38873. var isChromeWithoutDeviceMotion = function () {
  38874. var value = false;
  38875. if (getChromeVersion() === 65) {
  38876. var match = navigator.userAgent.match(/.*Chrome\/([0-9\.]*)/);
  38877. if (match) {
  38878. var _match$1$split = match[1].split('.'),
  38879. _match$1$split2 = slicedToArray(_match$1$split, 4),
  38880. major = _match$1$split2[0],
  38881. minor = _match$1$split2[1],
  38882. branch = _match$1$split2[2],
  38883. build = _match$1$split2[3];
  38884. value = parseInt(branch, 10) === 3325 && parseInt(build, 10) < 148;
  38885. }
  38886. }
  38887. return function () {
  38888. return value;
  38889. };
  38890. }();
  38891. var isR7 = function () {
  38892. var isR7 = navigator.userAgent.indexOf('R7 Build') !== -1;
  38893. return function () {
  38894. return isR7;
  38895. };
  38896. }();
  38897. var isLandscapeMode = function isLandscapeMode() {
  38898. var rtn = window.orientation == 90 || window.orientation == -90;
  38899. return isR7() ? !rtn : rtn;
  38900. };
  38901. var isTimestampDeltaValid = function isTimestampDeltaValid(timestampDeltaS) {
  38902. if (isNaN(timestampDeltaS)) {
  38903. return false;
  38904. }
  38905. if (timestampDeltaS <= MIN_TIMESTEP) {
  38906. return false;
  38907. }
  38908. if (timestampDeltaS > MAX_TIMESTEP) {
  38909. return false;
  38910. }
  38911. return true;
  38912. };
  38913. var getScreenWidth = function getScreenWidth() {
  38914. return Math.max(window.screen.width, window.screen.height) * window.devicePixelRatio;
  38915. };
  38916. var getScreenHeight = function getScreenHeight() {
  38917. return Math.min(window.screen.width, window.screen.height) * window.devicePixelRatio;
  38918. };
  38919. var requestFullscreen = function requestFullscreen(element) {
  38920. if (isWebViewAndroid()) {
  38921. return false;
  38922. }
  38923. if (element.requestFullscreen) {
  38924. element.requestFullscreen();
  38925. } else if (element.webkitRequestFullscreen) {
  38926. element.webkitRequestFullscreen();
  38927. } else if (element.mozRequestFullScreen) {
  38928. element.mozRequestFullScreen();
  38929. } else if (element.msRequestFullscreen) {
  38930. element.msRequestFullscreen();
  38931. } else {
  38932. return false;
  38933. }
  38934. return true;
  38935. };
  38936. var exitFullscreen = function exitFullscreen() {
  38937. if (document.exitFullscreen) {
  38938. document.exitFullscreen();
  38939. } else if (document.webkitExitFullscreen) {
  38940. document.webkitExitFullscreen();
  38941. } else if (document.mozCancelFullScreen) {
  38942. document.mozCancelFullScreen();
  38943. } else if (document.msExitFullscreen) {
  38944. document.msExitFullscreen();
  38945. } else {
  38946. return false;
  38947. }
  38948. return true;
  38949. };
  38950. var getFullscreenElement = function getFullscreenElement() {
  38951. return document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  38952. };
  38953. var linkProgram = function linkProgram(gl, vertexSource, fragmentSource, attribLocationMap) {
  38954. var vertexShader = gl.createShader(gl.VERTEX_SHADER);
  38955. gl.shaderSource(vertexShader, vertexSource);
  38956. gl.compileShader(vertexShader);
  38957. var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  38958. gl.shaderSource(fragmentShader, fragmentSource);
  38959. gl.compileShader(fragmentShader);
  38960. var program = gl.createProgram();
  38961. gl.attachShader(program, vertexShader);
  38962. gl.attachShader(program, fragmentShader);
  38963. for (var attribName in attribLocationMap) {
  38964. gl.bindAttribLocation(program, attribLocationMap[attribName], attribName);
  38965. }gl.linkProgram(program);
  38966. gl.deleteShader(vertexShader);
  38967. gl.deleteShader(fragmentShader);
  38968. return program;
  38969. };
  38970. var getProgramUniforms = function getProgramUniforms(gl, program) {
  38971. var uniforms = {};
  38972. var uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  38973. var uniformName = '';
  38974. for (var i = 0; i < uniformCount; i++) {
  38975. var uniformInfo = gl.getActiveUniform(program, i);
  38976. uniformName = uniformInfo.name.replace('[0]', '');
  38977. uniforms[uniformName] = gl.getUniformLocation(program, uniformName);
  38978. }
  38979. return uniforms;
  38980. };
  38981. var orthoMatrix = function orthoMatrix(out, left, right, bottom, top, near, far) {
  38982. var lr = 1 / (left - right),
  38983. bt = 1 / (bottom - top),
  38984. nf = 1 / (near - far);
  38985. out[0] = -2 * lr;
  38986. out[1] = 0;
  38987. out[2] = 0;
  38988. out[3] = 0;
  38989. out[4] = 0;
  38990. out[5] = -2 * bt;
  38991. out[6] = 0;
  38992. out[7] = 0;
  38993. out[8] = 0;
  38994. out[9] = 0;
  38995. out[10] = 2 * nf;
  38996. out[11] = 0;
  38997. out[12] = (left + right) * lr;
  38998. out[13] = (top + bottom) * bt;
  38999. out[14] = (far + near) * nf;
  39000. out[15] = 1;
  39001. return out;
  39002. };
  39003. var isMobile = function isMobile() {
  39004. var check = false;
  39005. (function (a) {
  39006. 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;
  39007. })(navigator.userAgent || navigator.vendor || window.opera);
  39008. return check;
  39009. };
  39010. var extend = function extend(dest, src) {
  39011. for (var key in src) {
  39012. if (src.hasOwnProperty(key)) {
  39013. dest[key] = src[key];
  39014. }
  39015. }
  39016. return dest;
  39017. };
  39018. var safariCssSizeWorkaround = function safariCssSizeWorkaround(canvas) {
  39019. if (isIOS()) {
  39020. var width = canvas.style.width;
  39021. var height = canvas.style.height;
  39022. canvas.style.width = parseInt(width) + 1 + 'px';
  39023. canvas.style.height = parseInt(height) + 'px';
  39024. setTimeout(function () {
  39025. canvas.style.width = width;
  39026. canvas.style.height = height;
  39027. }, 100);
  39028. }
  39029. window.canvas = canvas;
  39030. };
  39031. var frameDataFromPose = function () {
  39032. var piOver180 = Math.PI / 180.0;
  39033. var rad45 = Math.PI * 0.25;
  39034. function mat4_perspectiveFromFieldOfView(out, fov, near, far) {
  39035. var upTan = Math.tan(fov ? fov.upDegrees * piOver180 : rad45),
  39036. downTan = Math.tan(fov ? fov.downDegrees * piOver180 : rad45),
  39037. leftTan = Math.tan(fov ? fov.leftDegrees * piOver180 : rad45),
  39038. rightTan = Math.tan(fov ? fov.rightDegrees * piOver180 : rad45),
  39039. xScale = 2.0 / (leftTan + rightTan),
  39040. yScale = 2.0 / (upTan + downTan);
  39041. out[0] = xScale;
  39042. out[1] = 0.0;
  39043. out[2] = 0.0;
  39044. out[3] = 0.0;
  39045. out[4] = 0.0;
  39046. out[5] = yScale;
  39047. out[6] = 0.0;
  39048. out[7] = 0.0;
  39049. out[8] = -((leftTan - rightTan) * xScale * 0.5);
  39050. out[9] = (upTan - downTan) * yScale * 0.5;
  39051. out[10] = far / (near - far);
  39052. out[11] = -1.0;
  39053. out[12] = 0.0;
  39054. out[13] = 0.0;
  39055. out[14] = far * near / (near - far);
  39056. out[15] = 0.0;
  39057. return out;
  39058. }
  39059. function mat4_fromRotationTranslation(out, q, v) {
  39060. var x = q[0],
  39061. y = q[1],
  39062. z = q[2],
  39063. w = q[3],
  39064. x2 = x + x,
  39065. y2 = y + y,
  39066. z2 = z + z,
  39067. xx = x * x2,
  39068. xy = x * y2,
  39069. xz = x * z2,
  39070. yy = y * y2,
  39071. yz = y * z2,
  39072. zz = z * z2,
  39073. wx = w * x2,
  39074. wy = w * y2,
  39075. wz = w * z2;
  39076. out[0] = 1 - (yy + zz);
  39077. out[1] = xy + wz;
  39078. out[2] = xz - wy;
  39079. out[3] = 0;
  39080. out[4] = xy - wz;
  39081. out[5] = 1 - (xx + zz);
  39082. out[6] = yz + wx;
  39083. out[7] = 0;
  39084. out[8] = xz + wy;
  39085. out[9] = yz - wx;
  39086. out[10] = 1 - (xx + yy);
  39087. out[11] = 0;
  39088. out[12] = v[0];
  39089. out[13] = v[1];
  39090. out[14] = v[2];
  39091. out[15] = 1;
  39092. return out;
  39093. }
  39094. function mat4_translate(out, a, v) {
  39095. var x = v[0],
  39096. y = v[1],
  39097. z = v[2],
  39098. a00,
  39099. a01,
  39100. a02,
  39101. a03,
  39102. a10,
  39103. a11,
  39104. a12,
  39105. a13,
  39106. a20,
  39107. a21,
  39108. a22,
  39109. a23;
  39110. if (a === out) {
  39111. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  39112. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  39113. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  39114. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  39115. } else {
  39116. a00 = a[0];a01 = a[1];a02 = a[2];a03 = a[3];
  39117. a10 = a[4];a11 = a[5];a12 = a[6];a13 = a[7];
  39118. a20 = a[8];a21 = a[9];a22 = a[10];a23 = a[11];
  39119. out[0] = a00;out[1] = a01;out[2] = a02;out[3] = a03;
  39120. out[4] = a10;out[5] = a11;out[6] = a12;out[7] = a13;
  39121. out[8] = a20;out[9] = a21;out[10] = a22;out[11] = a23;
  39122. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  39123. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  39124. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  39125. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  39126. }
  39127. return out;
  39128. }
  39129. function mat4_invert(out, a) {
  39130. var a00 = a[0],
  39131. a01 = a[1],
  39132. a02 = a[2],
  39133. a03 = a[3],
  39134. a10 = a[4],
  39135. a11 = a[5],
  39136. a12 = a[6],
  39137. a13 = a[7],
  39138. a20 = a[8],
  39139. a21 = a[9],
  39140. a22 = a[10],
  39141. a23 = a[11],
  39142. a30 = a[12],
  39143. a31 = a[13],
  39144. a32 = a[14],
  39145. a33 = a[15],
  39146. b00 = a00 * a11 - a01 * a10,
  39147. b01 = a00 * a12 - a02 * a10,
  39148. b02 = a00 * a13 - a03 * a10,
  39149. b03 = a01 * a12 - a02 * a11,
  39150. b04 = a01 * a13 - a03 * a11,
  39151. b05 = a02 * a13 - a03 * a12,
  39152. b06 = a20 * a31 - a21 * a30,
  39153. b07 = a20 * a32 - a22 * a30,
  39154. b08 = a20 * a33 - a23 * a30,
  39155. b09 = a21 * a32 - a22 * a31,
  39156. b10 = a21 * a33 - a23 * a31,
  39157. b11 = a22 * a33 - a23 * a32,
  39158. det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  39159. if (!det) {
  39160. return null;
  39161. }
  39162. det = 1.0 / det;
  39163. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  39164. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  39165. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  39166. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  39167. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  39168. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  39169. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  39170. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  39171. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  39172. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  39173. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  39174. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  39175. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  39176. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  39177. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  39178. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  39179. return out;
  39180. }
  39181. var defaultOrientation = new Float32Array([0, 0, 0, 1]);
  39182. var defaultPosition = new Float32Array([0, 0, 0]);
  39183. function updateEyeMatrices(projection, view, pose, fov, offset, vrDisplay) {
  39184. mat4_perspectiveFromFieldOfView(projection, fov || null, vrDisplay.depthNear, vrDisplay.depthFar);
  39185. var orientation = pose.orientation || defaultOrientation;
  39186. var position = pose.position || defaultPosition;
  39187. mat4_fromRotationTranslation(view, orientation, position);
  39188. if (offset) mat4_translate(view, view, offset);
  39189. mat4_invert(view, view);
  39190. }
  39191. return function (frameData, pose, vrDisplay) {
  39192. if (!frameData || !pose) return false;
  39193. frameData.pose = pose;
  39194. frameData.timestamp = pose.timestamp;
  39195. updateEyeMatrices(frameData.leftProjectionMatrix, frameData.leftViewMatrix, pose, vrDisplay._getFieldOfView("left"), vrDisplay._getEyeOffset("left"), vrDisplay);
  39196. updateEyeMatrices(frameData.rightProjectionMatrix, frameData.rightViewMatrix, pose, vrDisplay._getFieldOfView("right"), vrDisplay._getEyeOffset("right"), vrDisplay);
  39197. return true;
  39198. };
  39199. }();
  39200. var isInsideCrossOriginIFrame = function isInsideCrossOriginIFrame() {
  39201. var isFramed = window.self !== window.top;
  39202. var refOrigin = getOriginFromUrl(document.referrer);
  39203. var thisOrigin = getOriginFromUrl(window.location.href);
  39204. return isFramed && refOrigin !== thisOrigin;
  39205. };
  39206. var getOriginFromUrl = function getOriginFromUrl(url) {
  39207. var domainIdx;
  39208. var protoSepIdx = url.indexOf("://");
  39209. if (protoSepIdx !== -1) {
  39210. domainIdx = protoSepIdx + 3;
  39211. } else {
  39212. domainIdx = 0;
  39213. }
  39214. var domainEndIdx = url.indexOf('/', domainIdx);
  39215. if (domainEndIdx === -1) {
  39216. domainEndIdx = url.length;
  39217. }
  39218. return url.substring(0, domainEndIdx);
  39219. };
  39220. var getQuaternionAngle = function getQuaternionAngle(quat) {
  39221. if (quat.w > 1) {
  39222. console.warn('getQuaternionAngle: w > 1');
  39223. return 0;
  39224. }
  39225. var angle = 2 * Math.acos(quat.w);
  39226. return angle;
  39227. };
  39228. var warnOnce = function () {
  39229. var observedWarnings = {};
  39230. return function (key, message) {
  39231. if (observedWarnings[key] === undefined) {
  39232. console.warn('webvr-polyfill: ' + message);
  39233. observedWarnings[key] = true;
  39234. }
  39235. };
  39236. }();
  39237. var deprecateWarning = function deprecateWarning(deprecated, suggested) {
  39238. var alternative = suggested ? 'Please use ' + suggested + ' instead.' : '';
  39239. warnOnce(deprecated, deprecated + ' has been deprecated. ' + 'This may not work on native WebVR displays. ' + alternative);
  39240. };
  39241. function WGLUPreserveGLState(gl, bindings, callback) {
  39242. if (!bindings) {
  39243. callback(gl);
  39244. return;
  39245. }
  39246. var boundValues = [];
  39247. var activeTexture = null;
  39248. for (var i = 0; i < bindings.length; ++i) {
  39249. var binding = bindings[i];
  39250. switch (binding) {
  39251. case gl.TEXTURE_BINDING_2D:
  39252. case gl.TEXTURE_BINDING_CUBE_MAP:
  39253. var textureUnit = bindings[++i];
  39254. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31) {
  39255. console.error("TEXTURE_BINDING_2D or TEXTURE_BINDING_CUBE_MAP must be followed by a valid texture unit");
  39256. boundValues.push(null, null);
  39257. break;
  39258. }
  39259. if (!activeTexture) {
  39260. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  39261. }
  39262. gl.activeTexture(textureUnit);
  39263. boundValues.push(gl.getParameter(binding), null);
  39264. break;
  39265. case gl.ACTIVE_TEXTURE:
  39266. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  39267. boundValues.push(null);
  39268. break;
  39269. default:
  39270. boundValues.push(gl.getParameter(binding));
  39271. break;
  39272. }
  39273. }
  39274. callback(gl);
  39275. for (var i = 0; i < bindings.length; ++i) {
  39276. var binding = bindings[i];
  39277. var boundValue = boundValues[i];
  39278. switch (binding) {
  39279. case gl.ACTIVE_TEXTURE:
  39280. break;
  39281. case gl.ARRAY_BUFFER_BINDING:
  39282. gl.bindBuffer(gl.ARRAY_BUFFER, boundValue);
  39283. break;
  39284. case gl.COLOR_CLEAR_VALUE:
  39285. gl.clearColor(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  39286. break;
  39287. case gl.COLOR_WRITEMASK:
  39288. gl.colorMask(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  39289. break;
  39290. case gl.CURRENT_PROGRAM:
  39291. gl.useProgram(boundValue);
  39292. break;
  39293. case gl.ELEMENT_ARRAY_BUFFER_BINDING:
  39294. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, boundValue);
  39295. break;
  39296. case gl.FRAMEBUFFER_BINDING:
  39297. gl.bindFramebuffer(gl.FRAMEBUFFER, boundValue);
  39298. break;
  39299. case gl.RENDERBUFFER_BINDING:
  39300. gl.bindRenderbuffer(gl.RENDERBUFFER, boundValue);
  39301. break;
  39302. case gl.TEXTURE_BINDING_2D:
  39303. var textureUnit = bindings[++i];
  39304. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  39305. break;
  39306. gl.activeTexture(textureUnit);
  39307. gl.bindTexture(gl.TEXTURE_2D, boundValue);
  39308. break;
  39309. case gl.TEXTURE_BINDING_CUBE_MAP:
  39310. var textureUnit = bindings[++i];
  39311. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  39312. break;
  39313. gl.activeTexture(textureUnit);
  39314. gl.bindTexture(gl.TEXTURE_CUBE_MAP, boundValue);
  39315. break;
  39316. case gl.VIEWPORT:
  39317. gl.viewport(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  39318. break;
  39319. case gl.BLEND:
  39320. case gl.CULL_FACE:
  39321. case gl.DEPTH_TEST:
  39322. case gl.SCISSOR_TEST:
  39323. case gl.STENCIL_TEST:
  39324. if (boundValue) {
  39325. gl.enable(binding);
  39326. } else {
  39327. gl.disable(binding);
  39328. }
  39329. break;
  39330. default:
  39331. console.log("No GL restore behavior for 0x" + binding.toString(16));
  39332. break;
  39333. }
  39334. if (activeTexture) {
  39335. gl.activeTexture(activeTexture);
  39336. }
  39337. }
  39338. }
  39339. var glPreserveState = WGLUPreserveGLState;
  39340. var distortionVS = ['attribute vec2 position;', 'attribute vec3 texCoord;', 'varying vec2 vTexCoord;', 'uniform vec4 viewportOffsetScale[2];', 'void main() {', ' vec4 viewport = viewportOffsetScale[int(texCoord.z)];', ' vTexCoord = (texCoord.xy * viewport.zw) + viewport.xy;', ' gl_Position = vec4( position, 1.0, 1.0 );', '}'].join('\n');
  39341. var distortionFS = ['precision mediump float;', 'uniform sampler2D diffuse;', 'varying vec2 vTexCoord;', 'void main() {', ' gl_FragColor = texture2D(diffuse, vTexCoord);', '}'].join('\n');
  39342. function CardboardDistorter(gl, cardboardUI, bufferScale, dirtySubmitFrameBindings) {
  39343. this.gl = gl;
  39344. this.cardboardUI = cardboardUI;
  39345. this.bufferScale = bufferScale;
  39346. this.dirtySubmitFrameBindings = dirtySubmitFrameBindings;
  39347. this.ctxAttribs = gl.getContextAttributes();
  39348. this.meshWidth = 20;
  39349. this.meshHeight = 20;
  39350. this.bufferWidth = gl.drawingBufferWidth;
  39351. this.bufferHeight = gl.drawingBufferHeight;
  39352. this.realBindFramebuffer = gl.bindFramebuffer;
  39353. this.realEnable = gl.enable;
  39354. this.realDisable = gl.disable;
  39355. this.realColorMask = gl.colorMask;
  39356. this.realClearColor = gl.clearColor;
  39357. this.realViewport = gl.viewport;
  39358. if (!isIOS()) {
  39359. this.realCanvasWidth = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'width');
  39360. this.realCanvasHeight = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'height');
  39361. }
  39362. this.isPatched = false;
  39363. this.lastBoundFramebuffer = null;
  39364. this.cullFace = false;
  39365. this.depthTest = false;
  39366. this.blend = false;
  39367. this.scissorTest = false;
  39368. this.stencilTest = false;
  39369. this.viewport = [0, 0, 0, 0];
  39370. this.colorMask = [true, true, true, true];
  39371. this.clearColor = [0, 0, 0, 0];
  39372. this.attribs = {
  39373. position: 0,
  39374. texCoord: 1
  39375. };
  39376. this.program = linkProgram(gl, distortionVS, distortionFS, this.attribs);
  39377. this.uniforms = getProgramUniforms(gl, this.program);
  39378. this.viewportOffsetScale = new Float32Array(8);
  39379. this.setTextureBounds();
  39380. this.vertexBuffer = gl.createBuffer();
  39381. this.indexBuffer = gl.createBuffer();
  39382. this.indexCount = 0;
  39383. this.renderTarget = gl.createTexture();
  39384. this.framebuffer = gl.createFramebuffer();
  39385. this.depthStencilBuffer = null;
  39386. this.depthBuffer = null;
  39387. this.stencilBuffer = null;
  39388. if (this.ctxAttribs.depth && this.ctxAttribs.stencil) {
  39389. this.depthStencilBuffer = gl.createRenderbuffer();
  39390. } else if (this.ctxAttribs.depth) {
  39391. this.depthBuffer = gl.createRenderbuffer();
  39392. } else if (this.ctxAttribs.stencil) {
  39393. this.stencilBuffer = gl.createRenderbuffer();
  39394. }
  39395. this.patch();
  39396. this.onResize();
  39397. }
  39398. CardboardDistorter.prototype.destroy = function () {
  39399. var gl = this.gl;
  39400. this.unpatch();
  39401. gl.deleteProgram(this.program);
  39402. gl.deleteBuffer(this.vertexBuffer);
  39403. gl.deleteBuffer(this.indexBuffer);
  39404. gl.deleteTexture(this.renderTarget);
  39405. gl.deleteFramebuffer(this.framebuffer);
  39406. if (this.depthStencilBuffer) {
  39407. gl.deleteRenderbuffer(this.depthStencilBuffer);
  39408. }
  39409. if (this.depthBuffer) {
  39410. gl.deleteRenderbuffer(this.depthBuffer);
  39411. }
  39412. if (this.stencilBuffer) {
  39413. gl.deleteRenderbuffer(this.stencilBuffer);
  39414. }
  39415. if (this.cardboardUI) {
  39416. this.cardboardUI.destroy();
  39417. }
  39418. };
  39419. CardboardDistorter.prototype.onResize = function () {
  39420. var gl = this.gl;
  39421. var self = this;
  39422. var glState = [gl.RENDERBUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0];
  39423. glPreserveState(gl, glState, function (gl) {
  39424. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  39425. if (self.scissorTest) {
  39426. self.realDisable.call(gl, gl.SCISSOR_TEST);
  39427. }
  39428. self.realColorMask.call(gl, true, true, true, true);
  39429. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  39430. self.realClearColor.call(gl, 0, 0, 0, 1);
  39431. gl.clear(gl.COLOR_BUFFER_BIT);
  39432. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.framebuffer);
  39433. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  39434. gl.texImage2D(gl.TEXTURE_2D, 0, self.ctxAttribs.alpha ? gl.RGBA : gl.RGB, self.bufferWidth, self.bufferHeight, 0, self.ctxAttribs.alpha ? gl.RGBA : gl.RGB, gl.UNSIGNED_BYTE, null);
  39435. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  39436. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  39437. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  39438. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  39439. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, self.renderTarget, 0);
  39440. if (self.ctxAttribs.depth && self.ctxAttribs.stencil) {
  39441. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthStencilBuffer);
  39442. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, self.bufferWidth, self.bufferHeight);
  39443. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.depthStencilBuffer);
  39444. } else if (self.ctxAttribs.depth) {
  39445. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthBuffer);
  39446. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, self.bufferWidth, self.bufferHeight);
  39447. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, self.depthBuffer);
  39448. } else if (self.ctxAttribs.stencil) {
  39449. gl.bindRenderbuffer(gl.RENDERBUFFER, self.stencilBuffer);
  39450. gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8, self.bufferWidth, self.bufferHeight);
  39451. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.stencilBuffer);
  39452. }
  39453. if (!gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE) {
  39454. console.error('Framebuffer incomplete!');
  39455. }
  39456. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  39457. if (self.scissorTest) {
  39458. self.realEnable.call(gl, gl.SCISSOR_TEST);
  39459. }
  39460. self.realColorMask.apply(gl, self.colorMask);
  39461. self.realViewport.apply(gl, self.viewport);
  39462. self.realClearColor.apply(gl, self.clearColor);
  39463. });
  39464. if (this.cardboardUI) {
  39465. this.cardboardUI.onResize();
  39466. }
  39467. };
  39468. CardboardDistorter.prototype.patch = function () {
  39469. if (this.isPatched) {
  39470. return;
  39471. }
  39472. var self = this;
  39473. var canvas = this.gl.canvas;
  39474. var gl = this.gl;
  39475. if (!isIOS()) {
  39476. canvas.width = getScreenWidth() * this.bufferScale;
  39477. canvas.height = getScreenHeight() * this.bufferScale;
  39478. Object.defineProperty(canvas, 'width', {
  39479. configurable: true,
  39480. enumerable: true,
  39481. get: function get() {
  39482. return self.bufferWidth;
  39483. },
  39484. set: function set(value) {
  39485. self.bufferWidth = value;
  39486. self.realCanvasWidth.set.call(canvas, value);
  39487. self.onResize();
  39488. }
  39489. });
  39490. Object.defineProperty(canvas, 'height', {
  39491. configurable: true,
  39492. enumerable: true,
  39493. get: function get() {
  39494. return self.bufferHeight;
  39495. },
  39496. set: function set(value) {
  39497. self.bufferHeight = value;
  39498. self.realCanvasHeight.set.call(canvas, value);
  39499. self.onResize();
  39500. }
  39501. });
  39502. }
  39503. this.lastBoundFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  39504. if (this.lastBoundFramebuffer == null) {
  39505. this.lastBoundFramebuffer = this.framebuffer;
  39506. this.gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
  39507. }
  39508. this.gl.bindFramebuffer = function (target, framebuffer) {
  39509. self.lastBoundFramebuffer = framebuffer ? framebuffer : self.framebuffer;
  39510. self.realBindFramebuffer.call(gl, target, self.lastBoundFramebuffer);
  39511. };
  39512. this.cullFace = gl.getParameter(gl.CULL_FACE);
  39513. this.depthTest = gl.getParameter(gl.DEPTH_TEST);
  39514. this.blend = gl.getParameter(gl.BLEND);
  39515. this.scissorTest = gl.getParameter(gl.SCISSOR_TEST);
  39516. this.stencilTest = gl.getParameter(gl.STENCIL_TEST);
  39517. gl.enable = function (pname) {
  39518. switch (pname) {
  39519. case gl.CULL_FACE:
  39520. self.cullFace = true;break;
  39521. case gl.DEPTH_TEST:
  39522. self.depthTest = true;break;
  39523. case gl.BLEND:
  39524. self.blend = true;break;
  39525. case gl.SCISSOR_TEST:
  39526. self.scissorTest = true;break;
  39527. case gl.STENCIL_TEST:
  39528. self.stencilTest = true;break;
  39529. }
  39530. self.realEnable.call(gl, pname);
  39531. };
  39532. gl.disable = function (pname) {
  39533. switch (pname) {
  39534. case gl.CULL_FACE:
  39535. self.cullFace = false;break;
  39536. case gl.DEPTH_TEST:
  39537. self.depthTest = false;break;
  39538. case gl.BLEND:
  39539. self.blend = false;break;
  39540. case gl.SCISSOR_TEST:
  39541. self.scissorTest = false;break;
  39542. case gl.STENCIL_TEST:
  39543. self.stencilTest = false;break;
  39544. }
  39545. self.realDisable.call(gl, pname);
  39546. };
  39547. this.colorMask = gl.getParameter(gl.COLOR_WRITEMASK);
  39548. gl.colorMask = function (r, g, b, a) {
  39549. self.colorMask[0] = r;
  39550. self.colorMask[1] = g;
  39551. self.colorMask[2] = b;
  39552. self.colorMask[3] = a;
  39553. self.realColorMask.call(gl, r, g, b, a);
  39554. };
  39555. this.clearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
  39556. gl.clearColor = function (r, g, b, a) {
  39557. self.clearColor[0] = r;
  39558. self.clearColor[1] = g;
  39559. self.clearColor[2] = b;
  39560. self.clearColor[3] = a;
  39561. self.realClearColor.call(gl, r, g, b, a);
  39562. };
  39563. this.viewport = gl.getParameter(gl.VIEWPORT);
  39564. gl.viewport = function (x, y, w, h) {
  39565. self.viewport[0] = x;
  39566. self.viewport[1] = y;
  39567. self.viewport[2] = w;
  39568. self.viewport[3] = h;
  39569. self.realViewport.call(gl, x, y, w, h);
  39570. };
  39571. this.isPatched = true;
  39572. safariCssSizeWorkaround(canvas);
  39573. };
  39574. CardboardDistorter.prototype.unpatch = function () {
  39575. if (!this.isPatched) {
  39576. return;
  39577. }
  39578. var gl = this.gl;
  39579. var canvas = this.gl.canvas;
  39580. if (!isIOS()) {
  39581. Object.defineProperty(canvas, 'width', this.realCanvasWidth);
  39582. Object.defineProperty(canvas, 'height', this.realCanvasHeight);
  39583. }
  39584. canvas.width = this.bufferWidth;
  39585. canvas.height = this.bufferHeight;
  39586. gl.bindFramebuffer = this.realBindFramebuffer;
  39587. gl.enable = this.realEnable;
  39588. gl.disable = this.realDisable;
  39589. gl.colorMask = this.realColorMask;
  39590. gl.clearColor = this.realClearColor;
  39591. gl.viewport = this.realViewport;
  39592. if (this.lastBoundFramebuffer == this.framebuffer) {
  39593. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  39594. }
  39595. this.isPatched = false;
  39596. setTimeout(function () {
  39597. safariCssSizeWorkaround(canvas);
  39598. }, 1);
  39599. };
  39600. CardboardDistorter.prototype.setTextureBounds = function (leftBounds, rightBounds) {
  39601. if (!leftBounds) {
  39602. leftBounds = [0, 0, 0.5, 1];
  39603. }
  39604. if (!rightBounds) {
  39605. rightBounds = [0.5, 0, 0.5, 1];
  39606. }
  39607. this.viewportOffsetScale[0] = leftBounds[0];
  39608. this.viewportOffsetScale[1] = leftBounds[1];
  39609. this.viewportOffsetScale[2] = leftBounds[2];
  39610. this.viewportOffsetScale[3] = leftBounds[3];
  39611. this.viewportOffsetScale[4] = rightBounds[0];
  39612. this.viewportOffsetScale[5] = rightBounds[1];
  39613. this.viewportOffsetScale[6] = rightBounds[2];
  39614. this.viewportOffsetScale[7] = rightBounds[3];
  39615. };
  39616. CardboardDistorter.prototype.submitFrame = function () {
  39617. var gl = this.gl;
  39618. var self = this;
  39619. var glState = [];
  39620. if (!this.dirtySubmitFrameBindings) {
  39621. glState.push(gl.CURRENT_PROGRAM, gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0);
  39622. }
  39623. glPreserveState(gl, glState, function (gl) {
  39624. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  39625. if (self.cullFace) {
  39626. self.realDisable.call(gl, gl.CULL_FACE);
  39627. }
  39628. if (self.depthTest) {
  39629. self.realDisable.call(gl, gl.DEPTH_TEST);
  39630. }
  39631. if (self.blend) {
  39632. self.realDisable.call(gl, gl.BLEND);
  39633. }
  39634. if (self.scissorTest) {
  39635. self.realDisable.call(gl, gl.SCISSOR_TEST);
  39636. }
  39637. if (self.stencilTest) {
  39638. self.realDisable.call(gl, gl.STENCIL_TEST);
  39639. }
  39640. self.realColorMask.call(gl, true, true, true, true);
  39641. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  39642. if (self.ctxAttribs.alpha || isIOS()) {
  39643. self.realClearColor.call(gl, 0, 0, 0, 1);
  39644. gl.clear(gl.COLOR_BUFFER_BIT);
  39645. }
  39646. gl.useProgram(self.program);
  39647. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  39648. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  39649. gl.enableVertexAttribArray(self.attribs.position);
  39650. gl.enableVertexAttribArray(self.attribs.texCoord);
  39651. gl.vertexAttribPointer(self.attribs.position, 2, gl.FLOAT, false, 20, 0);
  39652. gl.vertexAttribPointer(self.attribs.texCoord, 3, gl.FLOAT, false, 20, 8);
  39653. gl.activeTexture(gl.TEXTURE0);
  39654. gl.uniform1i(self.uniforms.diffuse, 0);
  39655. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  39656. gl.uniform4fv(self.uniforms.viewportOffsetScale, self.viewportOffsetScale);
  39657. gl.drawElements(gl.TRIANGLES, self.indexCount, gl.UNSIGNED_SHORT, 0);
  39658. if (self.cardboardUI) {
  39659. self.cardboardUI.renderNoState();
  39660. }
  39661. self.realBindFramebuffer.call(self.gl, gl.FRAMEBUFFER, self.framebuffer);
  39662. if (!self.ctxAttribs.preserveDrawingBuffer) {
  39663. self.realClearColor.call(gl, 0, 0, 0, 0);
  39664. gl.clear(gl.COLOR_BUFFER_BIT);
  39665. }
  39666. if (!self.dirtySubmitFrameBindings) {
  39667. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  39668. }
  39669. if (self.cullFace) {
  39670. self.realEnable.call(gl, gl.CULL_FACE);
  39671. }
  39672. if (self.depthTest) {
  39673. self.realEnable.call(gl, gl.DEPTH_TEST);
  39674. }
  39675. if (self.blend) {
  39676. self.realEnable.call(gl, gl.BLEND);
  39677. }
  39678. if (self.scissorTest) {
  39679. self.realEnable.call(gl, gl.SCISSOR_TEST);
  39680. }
  39681. if (self.stencilTest) {
  39682. self.realEnable.call(gl, gl.STENCIL_TEST);
  39683. }
  39684. self.realColorMask.apply(gl, self.colorMask);
  39685. self.realViewport.apply(gl, self.viewport);
  39686. if (self.ctxAttribs.alpha || !self.ctxAttribs.preserveDrawingBuffer) {
  39687. self.realClearColor.apply(gl, self.clearColor);
  39688. }
  39689. });
  39690. if (isIOS()) {
  39691. var canvas = gl.canvas;
  39692. if (canvas.width != self.bufferWidth || canvas.height != self.bufferHeight) {
  39693. self.bufferWidth = canvas.width;
  39694. self.bufferHeight = canvas.height;
  39695. self.onResize();
  39696. }
  39697. }
  39698. };
  39699. CardboardDistorter.prototype.updateDeviceInfo = function (deviceInfo) {
  39700. var gl = this.gl;
  39701. var self = this;
  39702. var glState = [gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING];
  39703. glPreserveState(gl, glState, function (gl) {
  39704. var vertices = self.computeMeshVertices_(self.meshWidth, self.meshHeight, deviceInfo);
  39705. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  39706. gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  39707. if (!self.indexCount) {
  39708. var indices = self.computeMeshIndices_(self.meshWidth, self.meshHeight);
  39709. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  39710. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
  39711. self.indexCount = indices.length;
  39712. }
  39713. });
  39714. };
  39715. CardboardDistorter.prototype.computeMeshVertices_ = function (width, height, deviceInfo) {
  39716. var vertices = new Float32Array(2 * width * height * 5);
  39717. var lensFrustum = deviceInfo.getLeftEyeVisibleTanAngles();
  39718. var noLensFrustum = deviceInfo.getLeftEyeNoLensTanAngles();
  39719. var viewport = deviceInfo.getLeftEyeVisibleScreenRect(noLensFrustum);
  39720. var vidx = 0;
  39721. for (var e = 0; e < 2; e++) {
  39722. for (var j = 0; j < height; j++) {
  39723. for (var i = 0; i < width; i++, vidx++) {
  39724. var u = i / (width - 1);
  39725. var v = j / (height - 1);
  39726. var s = u;
  39727. var t = v;
  39728. var x = lerp(lensFrustum[0], lensFrustum[2], u);
  39729. var y = lerp(lensFrustum[3], lensFrustum[1], v);
  39730. var d = Math.sqrt(x * x + y * y);
  39731. var r = deviceInfo.distortion.distortInverse(d);
  39732. var p = x * r / d;
  39733. var q = y * r / d;
  39734. u = (p - noLensFrustum[0]) / (noLensFrustum[2] - noLensFrustum[0]);
  39735. v = (q - noLensFrustum[3]) / (noLensFrustum[1] - noLensFrustum[3]);
  39736. u = (viewport.x + u * viewport.width - 0.5) * 2.0;
  39737. v = (viewport.y + v * viewport.height - 0.5) * 2.0;
  39738. vertices[vidx * 5 + 0] = u;
  39739. vertices[vidx * 5 + 1] = v;
  39740. vertices[vidx * 5 + 2] = s;
  39741. vertices[vidx * 5 + 3] = t;
  39742. vertices[vidx * 5 + 4] = e;
  39743. }
  39744. }
  39745. var w = lensFrustum[2] - lensFrustum[0];
  39746. lensFrustum[0] = -(w + lensFrustum[0]);
  39747. lensFrustum[2] = w - lensFrustum[2];
  39748. w = noLensFrustum[2] - noLensFrustum[0];
  39749. noLensFrustum[0] = -(w + noLensFrustum[0]);
  39750. noLensFrustum[2] = w - noLensFrustum[2];
  39751. viewport.x = 1 - (viewport.x + viewport.width);
  39752. }
  39753. return vertices;
  39754. };
  39755. CardboardDistorter.prototype.computeMeshIndices_ = function (width, height) {
  39756. var indices = new Uint16Array(2 * (width - 1) * (height - 1) * 6);
  39757. var halfwidth = width / 2;
  39758. var halfheight = height / 2;
  39759. var vidx = 0;
  39760. var iidx = 0;
  39761. for (var e = 0; e < 2; e++) {
  39762. for (var j = 0; j < height; j++) {
  39763. for (var i = 0; i < width; i++, vidx++) {
  39764. if (i == 0 || j == 0) continue;
  39765. if (i <= halfwidth == j <= halfheight) {
  39766. indices[iidx++] = vidx;
  39767. indices[iidx++] = vidx - width - 1;
  39768. indices[iidx++] = vidx - width;
  39769. indices[iidx++] = vidx - width - 1;
  39770. indices[iidx++] = vidx;
  39771. indices[iidx++] = vidx - 1;
  39772. } else {
  39773. indices[iidx++] = vidx - 1;
  39774. indices[iidx++] = vidx - width;
  39775. indices[iidx++] = vidx;
  39776. indices[iidx++] = vidx - width;
  39777. indices[iidx++] = vidx - 1;
  39778. indices[iidx++] = vidx - width - 1;
  39779. }
  39780. }
  39781. }
  39782. }
  39783. return indices;
  39784. };
  39785. CardboardDistorter.prototype.getOwnPropertyDescriptor_ = function (proto, attrName) {
  39786. var descriptor = Object.getOwnPropertyDescriptor(proto, attrName);
  39787. if (descriptor.get === undefined || descriptor.set === undefined) {
  39788. descriptor.configurable = true;
  39789. descriptor.enumerable = true;
  39790. descriptor.get = function () {
  39791. return this.getAttribute(attrName);
  39792. };
  39793. descriptor.set = function (val) {
  39794. this.setAttribute(attrName, val);
  39795. };
  39796. }
  39797. return descriptor;
  39798. };
  39799. var uiVS = ['attribute vec2 position;', 'uniform mat4 projectionMat;', 'void main() {', ' gl_Position = projectionMat * vec4( position, -1.0, 1.0 );', '}'].join('\n');
  39800. var uiFS = ['precision mediump float;', 'uniform vec4 color;', 'void main() {', ' gl_FragColor = color;', '}'].join('\n');
  39801. var DEG2RAD = Math.PI / 180.0;
  39802. var kAnglePerGearSection = 60;
  39803. var kOuterRimEndAngle = 12;
  39804. var kInnerRimBeginAngle = 20;
  39805. var kOuterRadius = 1;
  39806. var kMiddleRadius = 0.75;
  39807. var kInnerRadius = 0.3125;
  39808. var kCenterLineThicknessDp = 4;
  39809. var kButtonWidthDp = 28;
  39810. var kTouchSlopFactor = 1.5;
  39811. function CardboardUI(gl) {
  39812. this.gl = gl;
  39813. this.attribs = {
  39814. position: 0
  39815. };
  39816. this.program = linkProgram(gl, uiVS, uiFS, this.attribs);
  39817. this.uniforms = getProgramUniforms(gl, this.program);
  39818. this.vertexBuffer = gl.createBuffer();
  39819. this.gearOffset = 0;
  39820. this.gearVertexCount = 0;
  39821. this.arrowOffset = 0;
  39822. this.arrowVertexCount = 0;
  39823. this.projMat = new Float32Array(16);
  39824. this.listener = null;
  39825. this.onResize();
  39826. }
  39827. CardboardUI.prototype.destroy = function () {
  39828. var gl = this.gl;
  39829. if (this.listener) {
  39830. gl.canvas.removeEventListener('click', this.listener, false);
  39831. }
  39832. gl.deleteProgram(this.program);
  39833. gl.deleteBuffer(this.vertexBuffer);
  39834. };
  39835. CardboardUI.prototype.listen = function (optionsCallback, backCallback) {
  39836. var canvas = this.gl.canvas;
  39837. this.listener = function (event) {
  39838. var midline = canvas.clientWidth / 2;
  39839. var buttonSize = kButtonWidthDp * kTouchSlopFactor;
  39840. if (event.clientX > midline - buttonSize && event.clientX < midline + buttonSize && event.clientY > canvas.clientHeight - buttonSize) {
  39841. optionsCallback(event);
  39842. }
  39843. else if (event.clientX < buttonSize && event.clientY < buttonSize) {
  39844. backCallback(event);
  39845. }
  39846. };
  39847. canvas.addEventListener('click', this.listener, false);
  39848. };
  39849. CardboardUI.prototype.onResize = function () {
  39850. var gl = this.gl;
  39851. var self = this;
  39852. var glState = [gl.ARRAY_BUFFER_BINDING];
  39853. glPreserveState(gl, glState, function (gl) {
  39854. var vertices = [];
  39855. var midline = gl.drawingBufferWidth / 2;
  39856. var physicalPixels = Math.max(screen.width, screen.height) * window.devicePixelRatio;
  39857. var scalingRatio = gl.drawingBufferWidth / physicalPixels;
  39858. var dps = scalingRatio * window.devicePixelRatio;
  39859. var lineWidth = kCenterLineThicknessDp * dps / 2;
  39860. var buttonSize = kButtonWidthDp * kTouchSlopFactor * dps;
  39861. var buttonScale = kButtonWidthDp * dps / 2;
  39862. var buttonBorder = (kButtonWidthDp * kTouchSlopFactor - kButtonWidthDp) * dps;
  39863. vertices.push(midline - lineWidth, buttonSize);
  39864. vertices.push(midline - lineWidth, gl.drawingBufferHeight);
  39865. vertices.push(midline + lineWidth, buttonSize);
  39866. vertices.push(midline + lineWidth, gl.drawingBufferHeight);
  39867. self.gearOffset = vertices.length / 2;
  39868. function addGearSegment(theta, r) {
  39869. var angle = (90 - theta) * DEG2RAD;
  39870. var x = Math.cos(angle);
  39871. var y = Math.sin(angle);
  39872. vertices.push(kInnerRadius * x * buttonScale + midline, kInnerRadius * y * buttonScale + buttonScale);
  39873. vertices.push(r * x * buttonScale + midline, r * y * buttonScale + buttonScale);
  39874. }
  39875. for (var i = 0; i <= 6; i++) {
  39876. var segmentTheta = i * kAnglePerGearSection;
  39877. addGearSegment(segmentTheta, kOuterRadius);
  39878. addGearSegment(segmentTheta + kOuterRimEndAngle, kOuterRadius);
  39879. addGearSegment(segmentTheta + kInnerRimBeginAngle, kMiddleRadius);
  39880. addGearSegment(segmentTheta + (kAnglePerGearSection - kInnerRimBeginAngle), kMiddleRadius);
  39881. addGearSegment(segmentTheta + (kAnglePerGearSection - kOuterRimEndAngle), kOuterRadius);
  39882. }
  39883. self.gearVertexCount = vertices.length / 2 - self.gearOffset;
  39884. self.arrowOffset = vertices.length / 2;
  39885. function addArrowVertex(x, y) {
  39886. vertices.push(buttonBorder + x, gl.drawingBufferHeight - buttonBorder - y);
  39887. }
  39888. var angledLineWidth = lineWidth / Math.sin(45 * DEG2RAD);
  39889. addArrowVertex(0, buttonScale);
  39890. addArrowVertex(buttonScale, 0);
  39891. addArrowVertex(buttonScale + angledLineWidth, angledLineWidth);
  39892. addArrowVertex(angledLineWidth, buttonScale + angledLineWidth);
  39893. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  39894. addArrowVertex(0, buttonScale);
  39895. addArrowVertex(buttonScale, buttonScale * 2);
  39896. addArrowVertex(buttonScale + angledLineWidth, buttonScale * 2 - angledLineWidth);
  39897. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  39898. addArrowVertex(0, buttonScale);
  39899. addArrowVertex(angledLineWidth, buttonScale - lineWidth);
  39900. addArrowVertex(kButtonWidthDp * dps, buttonScale - lineWidth);
  39901. addArrowVertex(angledLineWidth, buttonScale + lineWidth);
  39902. addArrowVertex(kButtonWidthDp * dps, buttonScale + lineWidth);
  39903. self.arrowVertexCount = vertices.length / 2 - self.arrowOffset;
  39904. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  39905. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  39906. });
  39907. };
  39908. CardboardUI.prototype.render = function () {
  39909. var gl = this.gl;
  39910. var self = this;
  39911. var glState = [gl.CULL_FACE, gl.DEPTH_TEST, gl.BLEND, gl.SCISSOR_TEST, gl.STENCIL_TEST, gl.COLOR_WRITEMASK, gl.VIEWPORT, gl.CURRENT_PROGRAM, gl.ARRAY_BUFFER_BINDING];
  39912. glPreserveState(gl, glState, function (gl) {
  39913. gl.disable(gl.CULL_FACE);
  39914. gl.disable(gl.DEPTH_TEST);
  39915. gl.disable(gl.BLEND);
  39916. gl.disable(gl.SCISSOR_TEST);
  39917. gl.disable(gl.STENCIL_TEST);
  39918. gl.colorMask(true, true, true, true);
  39919. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  39920. self.renderNoState();
  39921. });
  39922. };
  39923. CardboardUI.prototype.renderNoState = function () {
  39924. var gl = this.gl;
  39925. gl.useProgram(this.program);
  39926. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  39927. gl.enableVertexAttribArray(this.attribs.position);
  39928. gl.vertexAttribPointer(this.attribs.position, 2, gl.FLOAT, false, 8, 0);
  39929. gl.uniform4f(this.uniforms.color, 1.0, 1.0, 1.0, 1.0);
  39930. orthoMatrix(this.projMat, 0, gl.drawingBufferWidth, 0, gl.drawingBufferHeight, 0.1, 1024.0);
  39931. gl.uniformMatrix4fv(this.uniforms.projectionMat, false, this.projMat);
  39932. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  39933. gl.drawArrays(gl.TRIANGLE_STRIP, this.gearOffset, this.gearVertexCount);
  39934. gl.drawArrays(gl.TRIANGLE_STRIP, this.arrowOffset, this.arrowVertexCount);
  39935. };
  39936. function Distortion(coefficients) {
  39937. this.coefficients = coefficients;
  39938. }
  39939. Distortion.prototype.distortInverse = function (radius) {
  39940. var r0 = 0;
  39941. var r1 = 1;
  39942. var dr0 = radius - this.distort(r0);
  39943. while (Math.abs(r1 - r0) > 0.0001 ) {
  39944. var dr1 = radius - this.distort(r1);
  39945. var r2 = r1 - dr1 * ((r1 - r0) / (dr1 - dr0));
  39946. r0 = r1;
  39947. r1 = r2;
  39948. dr0 = dr1;
  39949. }
  39950. return r1;
  39951. };
  39952. Distortion.prototype.distort = function (radius) {
  39953. var r2 = radius * radius;
  39954. var ret = 0;
  39955. for (var i = 0; i < this.coefficients.length; i++) {
  39956. ret = r2 * (ret + this.coefficients[i]);
  39957. }
  39958. return (ret + 1) * radius;
  39959. };
  39960. var degToRad = Math.PI / 180;
  39961. var radToDeg = 180 / Math.PI;
  39962. var Vector3 = function Vector3(x, y, z) {
  39963. this.x = x || 0;
  39964. this.y = y || 0;
  39965. this.z = z || 0;
  39966. };
  39967. Vector3.prototype = {
  39968. constructor: Vector3,
  39969. set: function set(x, y, z) {
  39970. this.x = x;
  39971. this.y = y;
  39972. this.z = z;
  39973. return this;
  39974. },
  39975. copy: function copy(v) {
  39976. this.x = v.x;
  39977. this.y = v.y;
  39978. this.z = v.z;
  39979. return this;
  39980. },
  39981. length: function length() {
  39982. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  39983. },
  39984. normalize: function normalize() {
  39985. var scalar = this.length();
  39986. if (scalar !== 0) {
  39987. var invScalar = 1 / scalar;
  39988. this.multiplyScalar(invScalar);
  39989. } else {
  39990. this.x = 0;
  39991. this.y = 0;
  39992. this.z = 0;
  39993. }
  39994. return this;
  39995. },
  39996. multiplyScalar: function multiplyScalar(scalar) {
  39997. this.x *= scalar;
  39998. this.y *= scalar;
  39999. this.z *= scalar;
  40000. },
  40001. applyQuaternion: function applyQuaternion(q) {
  40002. var x = this.x;
  40003. var y = this.y;
  40004. var z = this.z;
  40005. var qx = q.x;
  40006. var qy = q.y;
  40007. var qz = q.z;
  40008. var qw = q.w;
  40009. var ix = qw * x + qy * z - qz * y;
  40010. var iy = qw * y + qz * x - qx * z;
  40011. var iz = qw * z + qx * y - qy * x;
  40012. var iw = -qx * x - qy * y - qz * z;
  40013. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  40014. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  40015. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  40016. return this;
  40017. },
  40018. dot: function dot(v) {
  40019. return this.x * v.x + this.y * v.y + this.z * v.z;
  40020. },
  40021. crossVectors: function crossVectors(a, b) {
  40022. var ax = a.x,
  40023. ay = a.y,
  40024. az = a.z;
  40025. var bx = b.x,
  40026. by = b.y,
  40027. bz = b.z;
  40028. this.x = ay * bz - az * by;
  40029. this.y = az * bx - ax * bz;
  40030. this.z = ax * by - ay * bx;
  40031. return this;
  40032. }
  40033. };
  40034. var Quaternion = function Quaternion(x, y, z, w) {
  40035. this.x = x || 0;
  40036. this.y = y || 0;
  40037. this.z = z || 0;
  40038. this.w = w !== undefined ? w : 1;
  40039. };
  40040. Quaternion.prototype = {
  40041. constructor: Quaternion,
  40042. set: function set(x, y, z, w) {
  40043. this.x = x;
  40044. this.y = y;
  40045. this.z = z;
  40046. this.w = w;
  40047. return this;
  40048. },
  40049. copy: function copy(quaternion) {
  40050. this.x = quaternion.x;
  40051. this.y = quaternion.y;
  40052. this.z = quaternion.z;
  40053. this.w = quaternion.w;
  40054. return this;
  40055. },
  40056. setFromEulerXYZ: function setFromEulerXYZ(x, y, z) {
  40057. var c1 = Math.cos(x / 2);
  40058. var c2 = Math.cos(y / 2);
  40059. var c3 = Math.cos(z / 2);
  40060. var s1 = Math.sin(x / 2);
  40061. var s2 = Math.sin(y / 2);
  40062. var s3 = Math.sin(z / 2);
  40063. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  40064. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  40065. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  40066. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  40067. return this;
  40068. },
  40069. setFromEulerYXZ: function setFromEulerYXZ(x, y, z) {
  40070. var c1 = Math.cos(x / 2);
  40071. var c2 = Math.cos(y / 2);
  40072. var c3 = Math.cos(z / 2);
  40073. var s1 = Math.sin(x / 2);
  40074. var s2 = Math.sin(y / 2);
  40075. var s3 = Math.sin(z / 2);
  40076. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  40077. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  40078. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  40079. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  40080. return this;
  40081. },
  40082. setFromAxisAngle: function setFromAxisAngle(axis, angle) {
  40083. var halfAngle = angle / 2,
  40084. s = Math.sin(halfAngle);
  40085. this.x = axis.x * s;
  40086. this.y = axis.y * s;
  40087. this.z = axis.z * s;
  40088. this.w = Math.cos(halfAngle);
  40089. return this;
  40090. },
  40091. multiply: function multiply(q) {
  40092. return this.multiplyQuaternions(this, q);
  40093. },
  40094. multiplyQuaternions: function multiplyQuaternions(a, b) {
  40095. var qax = a.x,
  40096. qay = a.y,
  40097. qaz = a.z,
  40098. qaw = a.w;
  40099. var qbx = b.x,
  40100. qby = b.y,
  40101. qbz = b.z,
  40102. qbw = b.w;
  40103. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  40104. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  40105. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  40106. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  40107. return this;
  40108. },
  40109. inverse: function inverse() {
  40110. this.x *= -1;
  40111. this.y *= -1;
  40112. this.z *= -1;
  40113. this.normalize();
  40114. return this;
  40115. },
  40116. normalize: function normalize() {
  40117. var l = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  40118. if (l === 0) {
  40119. this.x = 0;
  40120. this.y = 0;
  40121. this.z = 0;
  40122. this.w = 1;
  40123. } else {
  40124. l = 1 / l;
  40125. this.x = this.x * l;
  40126. this.y = this.y * l;
  40127. this.z = this.z * l;
  40128. this.w = this.w * l;
  40129. }
  40130. return this;
  40131. },
  40132. slerp: function slerp(qb, t) {
  40133. if (t === 0) return this;
  40134. if (t === 1) return this.copy(qb);
  40135. var x = this.x,
  40136. y = this.y,
  40137. z = this.z,
  40138. w = this.w;
  40139. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  40140. if (cosHalfTheta < 0) {
  40141. this.w = -qb.w;
  40142. this.x = -qb.x;
  40143. this.y = -qb.y;
  40144. this.z = -qb.z;
  40145. cosHalfTheta = -cosHalfTheta;
  40146. } else {
  40147. this.copy(qb);
  40148. }
  40149. if (cosHalfTheta >= 1.0) {
  40150. this.w = w;
  40151. this.x = x;
  40152. this.y = y;
  40153. this.z = z;
  40154. return this;
  40155. }
  40156. var halfTheta = Math.acos(cosHalfTheta);
  40157. var sinHalfTheta = Math.sqrt(1.0 - cosHalfTheta * cosHalfTheta);
  40158. if (Math.abs(sinHalfTheta) < 0.001) {
  40159. this.w = 0.5 * (w + this.w);
  40160. this.x = 0.5 * (x + this.x);
  40161. this.y = 0.5 * (y + this.y);
  40162. this.z = 0.5 * (z + this.z);
  40163. return this;
  40164. }
  40165. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  40166. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  40167. this.w = w * ratioA + this.w * ratioB;
  40168. this.x = x * ratioA + this.x * ratioB;
  40169. this.y = y * ratioA + this.y * ratioB;
  40170. this.z = z * ratioA + this.z * ratioB;
  40171. return this;
  40172. },
  40173. setFromUnitVectors: function () {
  40174. var v1, r;
  40175. var EPS = 0.000001;
  40176. return function (vFrom, vTo) {
  40177. if (v1 === undefined) v1 = new Vector3();
  40178. r = vFrom.dot(vTo) + 1;
  40179. if (r < EPS) {
  40180. r = 0;
  40181. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  40182. v1.set(-vFrom.y, vFrom.x, 0);
  40183. } else {
  40184. v1.set(0, -vFrom.z, vFrom.y);
  40185. }
  40186. } else {
  40187. v1.crossVectors(vFrom, vTo);
  40188. }
  40189. this.x = v1.x;
  40190. this.y = v1.y;
  40191. this.z = v1.z;
  40192. this.w = r;
  40193. this.normalize();
  40194. return this;
  40195. };
  40196. }()
  40197. };
  40198. function Device(params) {
  40199. this.width = params.width || getScreenWidth();
  40200. this.height = params.height || getScreenHeight();
  40201. this.widthMeters = params.widthMeters;
  40202. this.heightMeters = params.heightMeters;
  40203. this.bevelMeters = params.bevelMeters;
  40204. }
  40205. var DEFAULT_ANDROID = new Device({
  40206. widthMeters: 0.110,
  40207. heightMeters: 0.062,
  40208. bevelMeters: 0.004
  40209. });
  40210. var DEFAULT_IOS = new Device({
  40211. widthMeters: 0.1038,
  40212. heightMeters: 0.0584,
  40213. bevelMeters: 0.004
  40214. });
  40215. var Viewers = {
  40216. CardboardV1: new CardboardViewer({
  40217. id: 'CardboardV1',
  40218. label: 'Cardboard I/O 2014',
  40219. fov: 40,
  40220. interLensDistance: 0.060,
  40221. baselineLensDistance: 0.035,
  40222. screenLensDistance: 0.042,
  40223. distortionCoefficients: [0.441, 0.156],
  40224. inverseCoefficients: [-0.4410035, 0.42756155, -0.4804439, 0.5460139, -0.58821183, 0.5733938, -0.48303202, 0.33299083, -0.17573841, 0.0651772, -0.01488963, 0.001559834]
  40225. }),
  40226. CardboardV2: new CardboardViewer({
  40227. id: 'CardboardV2',
  40228. label: 'Cardboard I/O 2015',
  40229. fov: 60,
  40230. interLensDistance: 0.064,
  40231. baselineLensDistance: 0.035,
  40232. screenLensDistance: 0.039,
  40233. distortionCoefficients: [0.34, 0.55],
  40234. inverseCoefficients: [-0.33836704, -0.18162185, 0.862655, -1.2462051, 1.0560602, -0.58208317, 0.21609078, -0.05444823, 0.009177956, -9.904169E-4, 6.183535E-5, -1.6981803E-6]
  40235. })
  40236. };
  40237. function DeviceInfo(deviceParams, additionalViewers) {
  40238. this.viewer = Viewers.CardboardV2;
  40239. this.updateDeviceParams(deviceParams);
  40240. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  40241. for (var i = 0; i < additionalViewers.length; i++) {
  40242. var viewer = additionalViewers[i];
  40243. Viewers[viewer.id] = new CardboardViewer(viewer);
  40244. }
  40245. }
  40246. DeviceInfo.prototype.updateDeviceParams = function (deviceParams) {
  40247. this.device = this.determineDevice_(deviceParams) || this.device;
  40248. };
  40249. DeviceInfo.prototype.getDevice = function () {
  40250. return this.device;
  40251. };
  40252. DeviceInfo.prototype.setViewer = function (viewer) {
  40253. this.viewer = viewer;
  40254. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  40255. };
  40256. DeviceInfo.prototype.determineDevice_ = function (deviceParams) {
  40257. if (!deviceParams) {
  40258. if (isIOS()) {
  40259. console.warn('Using fallback iOS device measurements.');
  40260. return DEFAULT_IOS;
  40261. } else {
  40262. console.warn('Using fallback Android device measurements.');
  40263. return DEFAULT_ANDROID;
  40264. }
  40265. }
  40266. var METERS_PER_INCH = 0.0254;
  40267. var metersPerPixelX = METERS_PER_INCH / deviceParams.xdpi;
  40268. var metersPerPixelY = METERS_PER_INCH / deviceParams.ydpi;
  40269. var width = getScreenWidth();
  40270. var height = getScreenHeight();
  40271. return new Device({
  40272. widthMeters: metersPerPixelX * width,
  40273. heightMeters: metersPerPixelY * height,
  40274. bevelMeters: deviceParams.bevelMm * 0.001
  40275. });
  40276. };
  40277. DeviceInfo.prototype.getDistortedFieldOfViewLeftEye = function () {
  40278. var viewer = this.viewer;
  40279. var device = this.device;
  40280. var distortion = this.distortion;
  40281. var eyeToScreenDistance = viewer.screenLensDistance;
  40282. var outerDist = (device.widthMeters - viewer.interLensDistance) / 2;
  40283. var innerDist = viewer.interLensDistance / 2;
  40284. var bottomDist = viewer.baselineLensDistance - device.bevelMeters;
  40285. var topDist = device.heightMeters - bottomDist;
  40286. var outerAngle = radToDeg * Math.atan(distortion.distort(outerDist / eyeToScreenDistance));
  40287. var innerAngle = radToDeg * Math.atan(distortion.distort(innerDist / eyeToScreenDistance));
  40288. var bottomAngle = radToDeg * Math.atan(distortion.distort(bottomDist / eyeToScreenDistance));
  40289. var topAngle = radToDeg * Math.atan(distortion.distort(topDist / eyeToScreenDistance));
  40290. return {
  40291. leftDegrees: Math.min(outerAngle, viewer.fov),
  40292. rightDegrees: Math.min(innerAngle, viewer.fov),
  40293. downDegrees: Math.min(bottomAngle, viewer.fov),
  40294. upDegrees: Math.min(topAngle, viewer.fov)
  40295. };
  40296. };
  40297. DeviceInfo.prototype.getLeftEyeVisibleTanAngles = function () {
  40298. var viewer = this.viewer;
  40299. var device = this.device;
  40300. var distortion = this.distortion;
  40301. var fovLeft = Math.tan(-degToRad * viewer.fov);
  40302. var fovTop = Math.tan(degToRad * viewer.fov);
  40303. var fovRight = Math.tan(degToRad * viewer.fov);
  40304. var fovBottom = Math.tan(-degToRad * viewer.fov);
  40305. var halfWidth = device.widthMeters / 4;
  40306. var halfHeight = device.heightMeters / 2;
  40307. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  40308. var centerX = viewer.interLensDistance / 2 - halfWidth;
  40309. var centerY = -verticalLensOffset;
  40310. var centerZ = viewer.screenLensDistance;
  40311. var screenLeft = distortion.distort((centerX - halfWidth) / centerZ);
  40312. var screenTop = distortion.distort((centerY + halfHeight) / centerZ);
  40313. var screenRight = distortion.distort((centerX + halfWidth) / centerZ);
  40314. var screenBottom = distortion.distort((centerY - halfHeight) / centerZ);
  40315. var result = new Float32Array(4);
  40316. result[0] = Math.max(fovLeft, screenLeft);
  40317. result[1] = Math.min(fovTop, screenTop);
  40318. result[2] = Math.min(fovRight, screenRight);
  40319. result[3] = Math.max(fovBottom, screenBottom);
  40320. return result;
  40321. };
  40322. DeviceInfo.prototype.getLeftEyeNoLensTanAngles = function () {
  40323. var viewer = this.viewer;
  40324. var device = this.device;
  40325. var distortion = this.distortion;
  40326. var result = new Float32Array(4);
  40327. var fovLeft = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  40328. var fovTop = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  40329. var fovRight = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  40330. var fovBottom = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  40331. var halfWidth = device.widthMeters / 4;
  40332. var halfHeight = device.heightMeters / 2;
  40333. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  40334. var centerX = viewer.interLensDistance / 2 - halfWidth;
  40335. var centerY = -verticalLensOffset;
  40336. var centerZ = viewer.screenLensDistance;
  40337. var screenLeft = (centerX - halfWidth) / centerZ;
  40338. var screenTop = (centerY + halfHeight) / centerZ;
  40339. var screenRight = (centerX + halfWidth) / centerZ;
  40340. var screenBottom = (centerY - halfHeight) / centerZ;
  40341. result[0] = Math.max(fovLeft, screenLeft);
  40342. result[1] = Math.min(fovTop, screenTop);
  40343. result[2] = Math.min(fovRight, screenRight);
  40344. result[3] = Math.max(fovBottom, screenBottom);
  40345. return result;
  40346. };
  40347. DeviceInfo.prototype.getLeftEyeVisibleScreenRect = function (undistortedFrustum) {
  40348. var viewer = this.viewer;
  40349. var device = this.device;
  40350. var dist = viewer.screenLensDistance;
  40351. var eyeX = (device.widthMeters - viewer.interLensDistance) / 2;
  40352. var eyeY = viewer.baselineLensDistance - device.bevelMeters;
  40353. var left = (undistortedFrustum[0] * dist + eyeX) / device.widthMeters;
  40354. var top = (undistortedFrustum[1] * dist + eyeY) / device.heightMeters;
  40355. var right = (undistortedFrustum[2] * dist + eyeX) / device.widthMeters;
  40356. var bottom = (undistortedFrustum[3] * dist + eyeY) / device.heightMeters;
  40357. return {
  40358. x: left,
  40359. y: bottom,
  40360. width: right - left,
  40361. height: top - bottom
  40362. };
  40363. };
  40364. DeviceInfo.prototype.getFieldOfViewLeftEye = function (opt_isUndistorted) {
  40365. return opt_isUndistorted ? this.getUndistortedFieldOfViewLeftEye() : this.getDistortedFieldOfViewLeftEye();
  40366. };
  40367. DeviceInfo.prototype.getFieldOfViewRightEye = function (opt_isUndistorted) {
  40368. var fov = this.getFieldOfViewLeftEye(opt_isUndistorted);
  40369. return {
  40370. leftDegrees: fov.rightDegrees,
  40371. rightDegrees: fov.leftDegrees,
  40372. upDegrees: fov.upDegrees,
  40373. downDegrees: fov.downDegrees
  40374. };
  40375. };
  40376. DeviceInfo.prototype.getUndistortedFieldOfViewLeftEye = function () {
  40377. var p = this.getUndistortedParams_();
  40378. return {
  40379. leftDegrees: radToDeg * Math.atan(p.outerDist),
  40380. rightDegrees: radToDeg * Math.atan(p.innerDist),
  40381. downDegrees: radToDeg * Math.atan(p.bottomDist),
  40382. upDegrees: radToDeg * Math.atan(p.topDist)
  40383. };
  40384. };
  40385. DeviceInfo.prototype.getUndistortedViewportLeftEye = function () {
  40386. var p = this.getUndistortedParams_();
  40387. var viewer = this.viewer;
  40388. var device = this.device;
  40389. var eyeToScreenDistance = viewer.screenLensDistance;
  40390. var screenWidth = device.widthMeters / eyeToScreenDistance;
  40391. var screenHeight = device.heightMeters / eyeToScreenDistance;
  40392. var xPxPerTanAngle = device.width / screenWidth;
  40393. var yPxPerTanAngle = device.height / screenHeight;
  40394. var x = Math.round((p.eyePosX - p.outerDist) * xPxPerTanAngle);
  40395. var y = Math.round((p.eyePosY - p.bottomDist) * yPxPerTanAngle);
  40396. return {
  40397. x: x,
  40398. y: y,
  40399. width: Math.round((p.eyePosX + p.innerDist) * xPxPerTanAngle) - x,
  40400. height: Math.round((p.eyePosY + p.topDist) * yPxPerTanAngle) - y
  40401. };
  40402. };
  40403. DeviceInfo.prototype.getUndistortedParams_ = function () {
  40404. var viewer = this.viewer;
  40405. var device = this.device;
  40406. var distortion = this.distortion;
  40407. var eyeToScreenDistance = viewer.screenLensDistance;
  40408. var halfLensDistance = viewer.interLensDistance / 2 / eyeToScreenDistance;
  40409. var screenWidth = device.widthMeters / eyeToScreenDistance;
  40410. var screenHeight = device.heightMeters / eyeToScreenDistance;
  40411. var eyePosX = screenWidth / 2 - halfLensDistance;
  40412. var eyePosY = (viewer.baselineLensDistance - device.bevelMeters) / eyeToScreenDistance;
  40413. var maxFov = viewer.fov;
  40414. var viewerMax = distortion.distortInverse(Math.tan(degToRad * maxFov));
  40415. var outerDist = Math.min(eyePosX, viewerMax);
  40416. var innerDist = Math.min(halfLensDistance, viewerMax);
  40417. var bottomDist = Math.min(eyePosY, viewerMax);
  40418. var topDist = Math.min(screenHeight - eyePosY, viewerMax);
  40419. return {
  40420. outerDist: outerDist,
  40421. innerDist: innerDist,
  40422. topDist: topDist,
  40423. bottomDist: bottomDist,
  40424. eyePosX: eyePosX,
  40425. eyePosY: eyePosY
  40426. };
  40427. };
  40428. function CardboardViewer(params) {
  40429. this.id = params.id;
  40430. this.label = params.label;
  40431. this.fov = params.fov;
  40432. this.interLensDistance = params.interLensDistance;
  40433. this.baselineLensDistance = params.baselineLensDistance;
  40434. this.screenLensDistance = params.screenLensDistance;
  40435. this.distortionCoefficients = params.distortionCoefficients;
  40436. this.inverseCoefficients = params.inverseCoefficients;
  40437. }
  40438. DeviceInfo.Viewers = Viewers;
  40439. var format = 1;
  40440. var last_updated = "2018-10-17T15:31:16Z";
  40441. var devices = [{"type":"android","rules":[{"mdmh":"asus/*/Nexus 7/*"},{"ua":"Nexus 7"}],"dpi":[320.8,323],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"asus/*/ASUS_Z00AD/*"},{"ua":"ASUS_Z00AD"}],"dpi":[403,404.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Google/*/Pixel XL/*"},{"ua":"Pixel XL"}],"dpi":[537.9,533],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Google/*/Pixel/*"},{"ua":"Pixel"}],"dpi":[432.6,436.7],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"HTC/*/HTC6435LVW/*"},{"ua":"HTC6435LVW"}],"dpi":[449.7,443.3],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"HTC/*/HTC One XL/*"},{"ua":"HTC One XL"}],"dpi":[315.3,314.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"htc/*/Nexus 9/*"},{"ua":"Nexus 9"}],"dpi":289,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"HTC/*/HTC One M9/*"},{"ua":"HTC One M9"}],"dpi":[442.5,443.3],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"HTC/*/HTC One_M8/*"},{"ua":"HTC One_M8"}],"dpi":[449.7,447.4],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"HTC/*/HTC One/*"},{"ua":"HTC One"}],"dpi":472.8,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Huawei/*/Nexus 6P/*"},{"ua":"Nexus 6P"}],"dpi":[515.1,518],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Huawei/*/BLN-L24/*"},{"ua":"HONORBLN-L24"}],"dpi":480,"bw":4,"ac":500},{"type":"android","rules":[{"mdmh":"Huawei/*/BKL-L09/*"},{"ua":"BKL-L09"}],"dpi":403,"bw":3.47,"ac":500},{"type":"android","rules":[{"mdmh":"LENOVO/*/Lenovo PB2-690Y/*"},{"ua":"Lenovo PB2-690Y"}],"dpi":[457.2,454.713],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"LGE/*/Nexus 5X/*"},{"ua":"Nexus 5X"}],"dpi":[422,419.9],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"LGE/*/LGMS345/*"},{"ua":"LGMS345"}],"dpi":[221.7,219.1],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"LGE/*/LG-D800/*"},{"ua":"LG-D800"}],"dpi":[422,424.1],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"LGE/*/LG-D850/*"},{"ua":"LG-D850"}],"dpi":[537.9,541.9],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"LGE/*/VS985 4G/*"},{"ua":"VS985 4G"}],"dpi":[537.9,535.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"LGE/*/Nexus 5/*"},{"ua":"Nexus 5 B"}],"dpi":[442.4,444.8],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"LGE/*/Nexus 4/*"},{"ua":"Nexus 4"}],"dpi":[319.8,318.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"LGE/*/LG-P769/*"},{"ua":"LG-P769"}],"dpi":[240.6,247.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"LGE/*/LGMS323/*"},{"ua":"LGMS323"}],"dpi":[206.6,204.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"LGE/*/LGLS996/*"},{"ua":"LGLS996"}],"dpi":[403.4,401.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Micromax/*/4560MMX/*"},{"ua":"4560MMX"}],"dpi":[240,219.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Micromax/*/A250/*"},{"ua":"Micromax A250"}],"dpi":[480,446.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Micromax/*/Micromax AQ4501/*"},{"ua":"Micromax AQ4501"}],"dpi":240,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"motorola/*/G5/*"},{"ua":"Moto G (5) Plus"}],"dpi":[403.4,403],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/DROID RAZR/*"},{"ua":"DROID RAZR"}],"dpi":[368.1,256.7],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/XT830C/*"},{"ua":"XT830C"}],"dpi":[254,255.9],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/XT1021/*"},{"ua":"XT1021"}],"dpi":[254,256.7],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"motorola/*/XT1023/*"},{"ua":"XT1023"}],"dpi":[254,256.7],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"motorola/*/XT1028/*"},{"ua":"XT1028"}],"dpi":[326.6,327.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/XT1034/*"},{"ua":"XT1034"}],"dpi":[326.6,328.4],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"motorola/*/XT1053/*"},{"ua":"XT1053"}],"dpi":[315.3,316.1],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/XT1562/*"},{"ua":"XT1562"}],"dpi":[403.4,402.7],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/Nexus 6/*"},{"ua":"Nexus 6 B"}],"dpi":[494.3,489.7],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/XT1063/*"},{"ua":"XT1063"}],"dpi":[295,296.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/XT1064/*"},{"ua":"XT1064"}],"dpi":[295,295.6],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"motorola/*/XT1092/*"},{"ua":"XT1092"}],"dpi":[422,424.1],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"motorola/*/XT1095/*"},{"ua":"XT1095"}],"dpi":[422,423.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/G4/*"},{"ua":"Moto G (4)"}],"dpi":401,"bw":4,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/A0001/*"},{"ua":"A0001"}],"dpi":[403.4,401],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONE E1005/*"},{"ua":"ONE E1005"}],"dpi":[442.4,441.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONE A2005/*"},{"ua":"ONE A2005"}],"dpi":[391.9,405.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONEPLUS A5000/*"},{"ua":"ONEPLUS A5000 "}],"dpi":[403.411,399.737],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONE A5010/*"},{"ua":"ONEPLUS A5010"}],"dpi":[403,400],"bw":2,"ac":1000},{"type":"android","rules":[{"mdmh":"OPPO/*/X909/*"},{"ua":"X909"}],"dpi":[442.4,444.1],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/GT-I9082/*"},{"ua":"GT-I9082"}],"dpi":[184.7,185.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G360P/*"},{"ua":"SM-G360P"}],"dpi":[196.7,205.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/Nexus S/*"},{"ua":"Nexus S"}],"dpi":[234.5,229.8],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/GT-I9300/*"},{"ua":"GT-I9300"}],"dpi":[304.8,303.9],"bw":5,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-T230NU/*"},{"ua":"SM-T230NU"}],"dpi":216,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SGH-T399/*"},{"ua":"SGH-T399"}],"dpi":[217.7,231.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SGH-M919/*"},{"ua":"SGH-M919"}],"dpi":[440.8,437.7],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-N9005/*"},{"ua":"SM-N9005"}],"dpi":[386.4,387],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SAMSUNG-SM-N900A/*"},{"ua":"SAMSUNG-SM-N900A"}],"dpi":[386.4,387.7],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/GT-I9500/*"},{"ua":"GT-I9500"}],"dpi":[442.5,443.3],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/GT-I9505/*"},{"ua":"GT-I9505"}],"dpi":439.4,"bw":4,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G900F/*"},{"ua":"SM-G900F"}],"dpi":[415.6,431.6],"bw":5,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G900M/*"},{"ua":"SM-G900M"}],"dpi":[415.6,431.6],"bw":5,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G800F/*"},{"ua":"SM-G800F"}],"dpi":326.8,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G906S/*"},{"ua":"SM-G906S"}],"dpi":[562.7,572.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/GT-I9300/*"},{"ua":"GT-I9300"}],"dpi":[306.7,304.8],"bw":5,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-T535/*"},{"ua":"SM-T535"}],"dpi":[142.6,136.4],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-N920C/*"},{"ua":"SM-N920C"}],"dpi":[515.1,518.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-N920P/*"},{"ua":"SM-N920P"}],"dpi":[386.3655,390.144],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-N920W8/*"},{"ua":"SM-N920W8"}],"dpi":[515.1,518.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/GT-I9300I/*"},{"ua":"GT-I9300I"}],"dpi":[304.8,305.8],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/GT-I9195/*"},{"ua":"GT-I9195"}],"dpi":[249.4,256.7],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SPH-L520/*"},{"ua":"SPH-L520"}],"dpi":[249.4,255.9],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SAMSUNG-SGH-I717/*"},{"ua":"SAMSUNG-SGH-I717"}],"dpi":285.8,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SPH-D710/*"},{"ua":"SPH-D710"}],"dpi":[217.7,204.2],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/GT-N7100/*"},{"ua":"GT-N7100"}],"dpi":265.1,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SCH-I605/*"},{"ua":"SCH-I605"}],"dpi":265.1,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/Galaxy Nexus/*"},{"ua":"Galaxy Nexus"}],"dpi":[315.3,314.2],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-N910H/*"},{"ua":"SM-N910H"}],"dpi":[515.1,518],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-N910C/*"},{"ua":"SM-N910C"}],"dpi":[515.2,520.2],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G130M/*"},{"ua":"SM-G130M"}],"dpi":[165.9,164.8],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G928I/*"},{"ua":"SM-G928I"}],"dpi":[515.1,518.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G920F/*"},{"ua":"SM-G920F"}],"dpi":580.6,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G920P/*"},{"ua":"SM-G920P"}],"dpi":[522.5,577],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G925F/*"},{"ua":"SM-G925F"}],"dpi":580.6,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G925V/*"},{"ua":"SM-G925V"}],"dpi":[522.5,576.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G930F/*"},{"ua":"SM-G930F"}],"dpi":576.6,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G935F/*"},{"ua":"SM-G935F"}],"dpi":533,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G950F/*"},{"ua":"SM-G950F"}],"dpi":[562.707,565.293],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G955U/*"},{"ua":"SM-G955U"}],"dpi":[522.514,525.762],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G955F/*"},{"ua":"SM-G955F"}],"dpi":[522.514,525.762],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"Sony/*/C6903/*"},{"ua":"C6903"}],"dpi":[442.5,443.3],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"Sony/*/D6653/*"},{"ua":"D6653"}],"dpi":[428.6,427.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Sony/*/E6653/*"},{"ua":"E6653"}],"dpi":[428.6,425.7],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Sony/*/E6853/*"},{"ua":"E6853"}],"dpi":[403.4,401.9],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Sony/*/SGP321/*"},{"ua":"SGP321"}],"dpi":[224.7,224.1],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"TCT/*/ALCATEL ONE TOUCH Fierce/*"},{"ua":"ALCATEL ONE TOUCH Fierce"}],"dpi":[240,247.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"THL/*/thl 5000/*"},{"ua":"thl 5000"}],"dpi":[480,443.3],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Fly/*/IQ4412/*"},{"ua":"IQ4412"}],"dpi":307.9,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"ZTE/*/ZTE Blade L2/*"},{"ua":"ZTE Blade L2"}],"dpi":240,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"BENEVE/*/VR518/*"},{"ua":"VR518"}],"dpi":480,"bw":3,"ac":500},{"type":"ios","rules":[{"res":[640,960]}],"dpi":[325.1,328.4],"bw":4,"ac":1000},{"type":"ios","rules":[{"res":[640,1136]}],"dpi":[317.1,320.2],"bw":3,"ac":1000},{"type":"ios","rules":[{"res":[750,1334]}],"dpi":326.4,"bw":4,"ac":1000},{"type":"ios","rules":[{"res":[1242,2208]}],"dpi":[453.6,458.4],"bw":4,"ac":1000},{"type":"ios","rules":[{"res":[1125,2001]}],"dpi":[410.9,415.4],"bw":4,"ac":1000},{"type":"ios","rules":[{"res":[1125,2436]}],"dpi":458,"bw":4,"ac":1000}];
  40442. var DPDB_CACHE = {
  40443. format: format,
  40444. last_updated: last_updated,
  40445. devices: devices
  40446. };
  40447. function Dpdb(url, onDeviceParamsUpdated) {
  40448. this.dpdb = DPDB_CACHE;
  40449. this.recalculateDeviceParams_();
  40450. if (url) {
  40451. this.onDeviceParamsUpdated = onDeviceParamsUpdated;
  40452. var xhr = new XMLHttpRequest();
  40453. var obj = this;
  40454. xhr.open('GET', url, true);
  40455. xhr.addEventListener('load', function () {
  40456. obj.loading = false;
  40457. if (xhr.status >= 200 && xhr.status <= 299) {
  40458. obj.dpdb = JSON.parse(xhr.response);
  40459. obj.recalculateDeviceParams_();
  40460. } else {
  40461. console.error('Error loading online DPDB!');
  40462. }
  40463. });
  40464. xhr.send();
  40465. }
  40466. }
  40467. Dpdb.prototype.getDeviceParams = function () {
  40468. return this.deviceParams;
  40469. };
  40470. Dpdb.prototype.recalculateDeviceParams_ = function () {
  40471. var newDeviceParams = this.calcDeviceParams_();
  40472. if (newDeviceParams) {
  40473. this.deviceParams = newDeviceParams;
  40474. if (this.onDeviceParamsUpdated) {
  40475. this.onDeviceParamsUpdated(this.deviceParams);
  40476. }
  40477. } else {
  40478. console.error('Failed to recalculate device parameters.');
  40479. }
  40480. };
  40481. Dpdb.prototype.calcDeviceParams_ = function () {
  40482. var db = this.dpdb;
  40483. if (!db) {
  40484. console.error('DPDB not available.');
  40485. return null;
  40486. }
  40487. if (db.format != 1) {
  40488. console.error('DPDB has unexpected format version.');
  40489. return null;
  40490. }
  40491. if (!db.devices || !db.devices.length) {
  40492. console.error('DPDB does not have a devices section.');
  40493. return null;
  40494. }
  40495. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  40496. var width = getScreenWidth();
  40497. var height = getScreenHeight();
  40498. if (!db.devices) {
  40499. console.error('DPDB has no devices section.');
  40500. return null;
  40501. }
  40502. for (var i = 0; i < db.devices.length; i++) {
  40503. var device = db.devices[i];
  40504. if (!device.rules) {
  40505. console.warn('Device[' + i + '] has no rules section.');
  40506. continue;
  40507. }
  40508. if (device.type != 'ios' && device.type != 'android') {
  40509. console.warn('Device[' + i + '] has invalid type.');
  40510. continue;
  40511. }
  40512. if (isIOS() != (device.type == 'ios')) continue;
  40513. var matched = false;
  40514. for (var j = 0; j < device.rules.length; j++) {
  40515. var rule = device.rules[j];
  40516. if (this.matchRule_(rule, userAgent, width, height)) {
  40517. matched = true;
  40518. break;
  40519. }
  40520. }
  40521. if (!matched) continue;
  40522. var xdpi = device.dpi[0] || device.dpi;
  40523. var ydpi = device.dpi[1] || device.dpi;
  40524. return new DeviceParams({ xdpi: xdpi, ydpi: ydpi, bevelMm: device.bw });
  40525. }
  40526. console.warn('No DPDB device match.');
  40527. return null;
  40528. };
  40529. Dpdb.prototype.matchRule_ = function (rule, ua, screenWidth, screenHeight) {
  40530. if (!rule.ua && !rule.res) return false;
  40531. if (rule.ua && rule.ua.substring(0, 2) === 'SM') rule.ua = rule.ua.substring(0, 7);
  40532. if (rule.ua && ua.indexOf(rule.ua) < 0) return false;
  40533. if (rule.res) {
  40534. if (!rule.res[0] || !rule.res[1]) return false;
  40535. var resX = rule.res[0];
  40536. var resY = rule.res[1];
  40537. if (Math.min(screenWidth, screenHeight) != Math.min(resX, resY) || Math.max(screenWidth, screenHeight) != Math.max(resX, resY)) {
  40538. return false;
  40539. }
  40540. }
  40541. return true;
  40542. };
  40543. function DeviceParams(params) {
  40544. this.xdpi = params.xdpi;
  40545. this.ydpi = params.ydpi;
  40546. this.bevelMm = params.bevelMm;
  40547. }
  40548. function SensorSample(sample, timestampS) {
  40549. this.set(sample, timestampS);
  40550. }
  40551. SensorSample.prototype.set = function (sample, timestampS) {
  40552. this.sample = sample;
  40553. this.timestampS = timestampS;
  40554. };
  40555. SensorSample.prototype.copy = function (sensorSample) {
  40556. this.set(sensorSample.sample, sensorSample.timestampS);
  40557. };
  40558. function ComplementaryFilter(kFilter, isDebug) {
  40559. this.kFilter = kFilter;
  40560. this.isDebug = isDebug;
  40561. this.currentAccelMeasurement = new SensorSample();
  40562. this.currentGyroMeasurement = new SensorSample();
  40563. this.previousGyroMeasurement = new SensorSample();
  40564. if (isIOS()) {
  40565. this.filterQ = new Quaternion(-1, 0, 0, 1);
  40566. } else {
  40567. this.filterQ = new Quaternion(1, 0, 0, 1);
  40568. }
  40569. this.previousFilterQ = new Quaternion();
  40570. this.previousFilterQ.copy(this.filterQ);
  40571. this.accelQ = new Quaternion();
  40572. this.isOrientationInitialized = false;
  40573. this.estimatedGravity = new Vector3();
  40574. this.measuredGravity = new Vector3();
  40575. this.gyroIntegralQ = new Quaternion();
  40576. }
  40577. ComplementaryFilter.prototype.addAccelMeasurement = function (vector, timestampS) {
  40578. this.currentAccelMeasurement.set(vector, timestampS);
  40579. };
  40580. ComplementaryFilter.prototype.addGyroMeasurement = function (vector, timestampS) {
  40581. this.currentGyroMeasurement.set(vector, timestampS);
  40582. var deltaT = timestampS - this.previousGyroMeasurement.timestampS;
  40583. if (isTimestampDeltaValid(deltaT)) {
  40584. this.run_();
  40585. }
  40586. this.previousGyroMeasurement.copy(this.currentGyroMeasurement);
  40587. };
  40588. ComplementaryFilter.prototype.run_ = function () {
  40589. if (!this.isOrientationInitialized) {
  40590. this.accelQ = this.accelToQuaternion_(this.currentAccelMeasurement.sample);
  40591. this.previousFilterQ.copy(this.accelQ);
  40592. this.isOrientationInitialized = true;
  40593. return;
  40594. }
  40595. var deltaT = this.currentGyroMeasurement.timestampS - this.previousGyroMeasurement.timestampS;
  40596. var gyroDeltaQ = this.gyroToQuaternionDelta_(this.currentGyroMeasurement.sample, deltaT);
  40597. this.gyroIntegralQ.multiply(gyroDeltaQ);
  40598. this.filterQ.copy(this.previousFilterQ);
  40599. this.filterQ.multiply(gyroDeltaQ);
  40600. var invFilterQ = new Quaternion();
  40601. invFilterQ.copy(this.filterQ);
  40602. invFilterQ.inverse();
  40603. this.estimatedGravity.set(0, 0, -1);
  40604. this.estimatedGravity.applyQuaternion(invFilterQ);
  40605. this.estimatedGravity.normalize();
  40606. this.measuredGravity.copy(this.currentAccelMeasurement.sample);
  40607. this.measuredGravity.normalize();
  40608. var deltaQ = new Quaternion();
  40609. deltaQ.setFromUnitVectors(this.estimatedGravity, this.measuredGravity);
  40610. deltaQ.inverse();
  40611. if (this.isDebug) {
  40612. console.log('Delta: %d deg, G_est: (%s, %s, %s), G_meas: (%s, %s, %s)', radToDeg * getQuaternionAngle(deltaQ), this.estimatedGravity.x.toFixed(1), this.estimatedGravity.y.toFixed(1), this.estimatedGravity.z.toFixed(1), this.measuredGravity.x.toFixed(1), this.measuredGravity.y.toFixed(1), this.measuredGravity.z.toFixed(1));
  40613. }
  40614. var targetQ = new Quaternion();
  40615. targetQ.copy(this.filterQ);
  40616. targetQ.multiply(deltaQ);
  40617. this.filterQ.slerp(targetQ, 1 - this.kFilter);
  40618. this.previousFilterQ.copy(this.filterQ);
  40619. };
  40620. ComplementaryFilter.prototype.getOrientation = function () {
  40621. return this.filterQ;
  40622. };
  40623. ComplementaryFilter.prototype.accelToQuaternion_ = function (accel) {
  40624. var normAccel = new Vector3();
  40625. normAccel.copy(accel);
  40626. normAccel.normalize();
  40627. var quat = new Quaternion();
  40628. quat.setFromUnitVectors(new Vector3(0, 0, -1), normAccel);
  40629. quat.inverse();
  40630. return quat;
  40631. };
  40632. ComplementaryFilter.prototype.gyroToQuaternionDelta_ = function (gyro, dt) {
  40633. var quat = new Quaternion();
  40634. var axis = new Vector3();
  40635. axis.copy(gyro);
  40636. axis.normalize();
  40637. quat.setFromAxisAngle(axis, gyro.length() * dt);
  40638. return quat;
  40639. };
  40640. function PosePredictor(predictionTimeS, isDebug) {
  40641. this.predictionTimeS = predictionTimeS;
  40642. this.isDebug = isDebug;
  40643. this.previousQ = new Quaternion();
  40644. this.previousTimestampS = null;
  40645. this.deltaQ = new Quaternion();
  40646. this.outQ = new Quaternion();
  40647. }
  40648. PosePredictor.prototype.getPrediction = function (currentQ, gyro, timestampS) {
  40649. if (!this.previousTimestampS) {
  40650. this.previousQ.copy(currentQ);
  40651. this.previousTimestampS = timestampS;
  40652. return currentQ;
  40653. }
  40654. var axis = new Vector3();
  40655. axis.copy(gyro);
  40656. axis.normalize();
  40657. var angularSpeed = gyro.length();
  40658. if (angularSpeed < degToRad * 20) {
  40659. if (this.isDebug) {
  40660. console.log('Moving slowly, at %s deg/s: no prediction', (radToDeg * angularSpeed).toFixed(1));
  40661. }
  40662. this.outQ.copy(currentQ);
  40663. this.previousQ.copy(currentQ);
  40664. return this.outQ;
  40665. }
  40666. var predictAngle = angularSpeed * this.predictionTimeS;
  40667. this.deltaQ.setFromAxisAngle(axis, predictAngle);
  40668. this.outQ.copy(this.previousQ);
  40669. this.outQ.multiply(this.deltaQ);
  40670. this.previousQ.copy(currentQ);
  40671. this.previousTimestampS = timestampS;
  40672. return this.outQ;
  40673. };
  40674. function FusionPoseSensor(kFilter, predictionTime, yawOnly, isDebug) {
  40675. this.yawOnly = yawOnly;
  40676. this.accelerometer = new Vector3();
  40677. this.gyroscope = new Vector3();
  40678. this.filter = new ComplementaryFilter(kFilter, isDebug);
  40679. this.posePredictor = new PosePredictor(predictionTime, isDebug);
  40680. this.isFirefoxAndroid = isFirefoxAndroid();
  40681. this.isIOS = isIOS();
  40682. var chromeVersion = getChromeVersion();
  40683. this.isDeviceMotionInRadians = !this.isIOS && chromeVersion && chromeVersion < 66;
  40684. this.isWithoutDeviceMotion = isChromeWithoutDeviceMotion();
  40685. this.filterToWorldQ = new Quaternion();
  40686. if (isIOS()) {
  40687. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), Math.PI / 2);
  40688. } else {
  40689. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  40690. }
  40691. this.inverseWorldToScreenQ = new Quaternion();
  40692. this.worldToScreenQ = new Quaternion();
  40693. this.originalPoseAdjustQ = new Quaternion();
  40694. this.originalPoseAdjustQ.setFromAxisAngle(new Vector3(0, 0, 1), -window.orientation * Math.PI / 180);
  40695. this.setScreenTransform_();
  40696. if (isLandscapeMode()) {
  40697. this.filterToWorldQ.multiply(this.inverseWorldToScreenQ);
  40698. }
  40699. this.resetQ = new Quaternion();
  40700. this.orientationOut_ = new Float32Array(4);
  40701. this.start();
  40702. }
  40703. FusionPoseSensor.prototype.getPosition = function () {
  40704. return null;
  40705. };
  40706. FusionPoseSensor.prototype.getOrientation = function () {
  40707. var orientation = void 0;
  40708. if (this.isWithoutDeviceMotion && this._deviceOrientationQ) {
  40709. this.deviceOrientationFixQ = this.deviceOrientationFixQ || function () {
  40710. var z = new Quaternion().setFromAxisAngle(new Vector3(0, 0, -1), 0);
  40711. var y = new Quaternion();
  40712. if (window.orientation === -90) {
  40713. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / -2);
  40714. } else {
  40715. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / 2);
  40716. }
  40717. return z.multiply(y);
  40718. }();
  40719. this.deviceOrientationFilterToWorldQ = this.deviceOrientationFilterToWorldQ || function () {
  40720. var q = new Quaternion();
  40721. q.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  40722. return q;
  40723. }();
  40724. orientation = this._deviceOrientationQ;
  40725. var out = new Quaternion();
  40726. out.copy(orientation);
  40727. out.multiply(this.deviceOrientationFilterToWorldQ);
  40728. out.multiply(this.resetQ);
  40729. out.multiply(this.worldToScreenQ);
  40730. out.multiplyQuaternions(this.deviceOrientationFixQ, out);
  40731. if (this.yawOnly) {
  40732. out.x = 0;
  40733. out.z = 0;
  40734. out.normalize();
  40735. }
  40736. this.orientationOut_[0] = out.x;
  40737. this.orientationOut_[1] = out.y;
  40738. this.orientationOut_[2] = out.z;
  40739. this.orientationOut_[3] = out.w;
  40740. return this.orientationOut_;
  40741. } else {
  40742. var filterOrientation = this.filter.getOrientation();
  40743. orientation = this.posePredictor.getPrediction(filterOrientation, this.gyroscope, this.previousTimestampS);
  40744. }
  40745. var out = new Quaternion();
  40746. out.copy(this.filterToWorldQ);
  40747. out.multiply(this.resetQ);
  40748. out.multiply(orientation);
  40749. out.multiply(this.worldToScreenQ);
  40750. if (this.yawOnly) {
  40751. out.x = 0;
  40752. out.z = 0;
  40753. out.normalize();
  40754. }
  40755. this.orientationOut_[0] = out.x;
  40756. this.orientationOut_[1] = out.y;
  40757. this.orientationOut_[2] = out.z;
  40758. this.orientationOut_[3] = out.w;
  40759. return this.orientationOut_;
  40760. };
  40761. FusionPoseSensor.prototype.resetPose = function () {
  40762. this.resetQ.copy(this.filter.getOrientation());
  40763. this.resetQ.x = 0;
  40764. this.resetQ.y = 0;
  40765. this.resetQ.z *= -1;
  40766. this.resetQ.normalize();
  40767. if (isLandscapeMode()) {
  40768. this.resetQ.multiply(this.inverseWorldToScreenQ);
  40769. }
  40770. this.resetQ.multiply(this.originalPoseAdjustQ);
  40771. };
  40772. FusionPoseSensor.prototype.onDeviceOrientation_ = function (e) {
  40773. this._deviceOrientationQ = this._deviceOrientationQ || new Quaternion();
  40774. var alpha = e.alpha,
  40775. beta = e.beta,
  40776. gamma = e.gamma;
  40777. alpha = (alpha || 0) * Math.PI / 180;
  40778. beta = (beta || 0) * Math.PI / 180;
  40779. gamma = (gamma || 0) * Math.PI / 180;
  40780. this._deviceOrientationQ.setFromEulerYXZ(beta, alpha, -gamma);
  40781. };
  40782. FusionPoseSensor.prototype.onDeviceMotion_ = function (deviceMotion) {
  40783. this.updateDeviceMotion_(deviceMotion);
  40784. };
  40785. FusionPoseSensor.prototype.updateDeviceMotion_ = function (deviceMotion) {
  40786. var accGravity = deviceMotion.accelerationIncludingGravity;
  40787. var rotRate = deviceMotion.rotationRate;
  40788. var timestampS = deviceMotion.timeStamp / 1000;
  40789. var deltaS = timestampS - this.previousTimestampS;
  40790. if (deltaS < 0) {
  40791. warnOnce('fusion-pose-sensor:invalid:non-monotonic', 'Invalid timestamps detected: non-monotonic timestamp from devicemotion');
  40792. this.previousTimestampS = timestampS;
  40793. return;
  40794. } else if (deltaS <= MIN_TIMESTEP || deltaS > MAX_TIMESTEP) {
  40795. warnOnce('fusion-pose-sensor:invalid:outside-threshold', 'Invalid timestamps detected: Timestamp from devicemotion outside expected range.');
  40796. this.previousTimestampS = timestampS;
  40797. return;
  40798. }
  40799. this.accelerometer.set(-accGravity.x, -accGravity.y, -accGravity.z);
  40800. if (isR7()) {
  40801. this.gyroscope.set(-rotRate.beta, rotRate.alpha, rotRate.gamma);
  40802. } else {
  40803. this.gyroscope.set(rotRate.alpha, rotRate.beta, rotRate.gamma);
  40804. }
  40805. if (!this.isDeviceMotionInRadians) {
  40806. this.gyroscope.multiplyScalar(Math.PI / 180);
  40807. }
  40808. this.filter.addAccelMeasurement(this.accelerometer, timestampS);
  40809. this.filter.addGyroMeasurement(this.gyroscope, timestampS);
  40810. this.previousTimestampS = timestampS;
  40811. };
  40812. FusionPoseSensor.prototype.onOrientationChange_ = function (screenOrientation) {
  40813. this.setScreenTransform_();
  40814. };
  40815. FusionPoseSensor.prototype.onMessage_ = function (event) {
  40816. var message = event.data;
  40817. if (!message || !message.type) {
  40818. return;
  40819. }
  40820. var type = message.type.toLowerCase();
  40821. if (type !== 'devicemotion') {
  40822. return;
  40823. }
  40824. this.updateDeviceMotion_(message.deviceMotionEvent);
  40825. };
  40826. FusionPoseSensor.prototype.setScreenTransform_ = function () {
  40827. this.worldToScreenQ.set(0, 0, 0, 1);
  40828. switch (window.orientation) {
  40829. case 0:
  40830. break;
  40831. case 90:
  40832. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), -Math.PI / 2);
  40833. break;
  40834. case -90:
  40835. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), Math.PI / 2);
  40836. break;
  40837. case 180:
  40838. break;
  40839. }
  40840. this.inverseWorldToScreenQ.copy(this.worldToScreenQ);
  40841. this.inverseWorldToScreenQ.inverse();
  40842. };
  40843. FusionPoseSensor.prototype.start = function () {
  40844. this.onDeviceMotionCallback_ = this.onDeviceMotion_.bind(this);
  40845. this.onOrientationChangeCallback_ = this.onOrientationChange_.bind(this);
  40846. this.onMessageCallback_ = this.onMessage_.bind(this);
  40847. this.onDeviceOrientationCallback_ = this.onDeviceOrientation_.bind(this);
  40848. if (isIOS() && isInsideCrossOriginIFrame()) {
  40849. window.addEventListener('message', this.onMessageCallback_);
  40850. }
  40851. window.addEventListener('orientationchange', this.onOrientationChangeCallback_);
  40852. if (this.isWithoutDeviceMotion) {
  40853. window.addEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  40854. } else {
  40855. window.addEventListener('devicemotion', this.onDeviceMotionCallback_);
  40856. }
  40857. };
  40858. FusionPoseSensor.prototype.stop = function () {
  40859. window.removeEventListener('devicemotion', this.onDeviceMotionCallback_);
  40860. window.removeEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  40861. window.removeEventListener('orientationchange', this.onOrientationChangeCallback_);
  40862. window.removeEventListener('message', this.onMessageCallback_);
  40863. };
  40864. var SENSOR_FREQUENCY = 60;
  40865. var X_AXIS = new Vector3(1, 0, 0);
  40866. var Z_AXIS = new Vector3(0, 0, 1);
  40867. var SENSOR_TO_VR = new Quaternion();
  40868. SENSOR_TO_VR.setFromAxisAngle(X_AXIS, -Math.PI / 2);
  40869. SENSOR_TO_VR.multiply(new Quaternion().setFromAxisAngle(Z_AXIS, Math.PI / 2));
  40870. var PoseSensor = function () {
  40871. function PoseSensor(config) {
  40872. classCallCheck(this, PoseSensor);
  40873. this.config = config;
  40874. this.sensor = null;
  40875. this.fusionSensor = null;
  40876. this._out = new Float32Array(4);
  40877. this.api = null;
  40878. this.errors = [];
  40879. this._sensorQ = new Quaternion();
  40880. this._outQ = new Quaternion();
  40881. this._onSensorRead = this._onSensorRead.bind(this);
  40882. this._onSensorError = this._onSensorError.bind(this);
  40883. this.init();
  40884. }
  40885. createClass(PoseSensor, [{
  40886. key: 'init',
  40887. value: function init() {
  40888. var sensor = null;
  40889. try {
  40890. sensor = new RelativeOrientationSensor({
  40891. frequency: SENSOR_FREQUENCY,
  40892. referenceFrame: 'screen'
  40893. });
  40894. sensor.addEventListener('error', this._onSensorError);
  40895. } catch (error) {
  40896. this.errors.push(error);
  40897. if (error.name === 'SecurityError') {
  40898. console.error('Cannot construct sensors due to the Feature Policy');
  40899. console.warn('Attempting to fall back using "devicemotion"; however this will ' + 'fail in the future without correct permissions.');
  40900. this.useDeviceMotion();
  40901. } else if (error.name === 'ReferenceError') {
  40902. this.useDeviceMotion();
  40903. } else {
  40904. console.error(error);
  40905. }
  40906. }
  40907. if (sensor) {
  40908. this.api = 'sensor';
  40909. this.sensor = sensor;
  40910. this.sensor.addEventListener('reading', this._onSensorRead);
  40911. this.sensor.start();
  40912. }
  40913. }
  40914. }, {
  40915. key: 'useDeviceMotion',
  40916. value: function useDeviceMotion() {
  40917. this.api = 'devicemotion';
  40918. this.fusionSensor = new FusionPoseSensor(this.config.K_FILTER, this.config.PREDICTION_TIME_S, this.config.YAW_ONLY, this.config.DEBUG);
  40919. if (this.sensor) {
  40920. this.sensor.removeEventListener('reading', this._onSensorRead);
  40921. this.sensor.removeEventListener('error', this._onSensorError);
  40922. this.sensor = null;
  40923. }
  40924. }
  40925. }, {
  40926. key: 'getOrientation',
  40927. value: function getOrientation() {
  40928. if (this.fusionSensor) {
  40929. return this.fusionSensor.getOrientation();
  40930. }
  40931. if (!this.sensor || !this.sensor.quaternion) {
  40932. this._out[0] = this._out[1] = this._out[2] = 0;
  40933. this._out[3] = 1;
  40934. return this._out;
  40935. }
  40936. var q = this.sensor.quaternion;
  40937. this._sensorQ.set(q[0], q[1], q[2], q[3]);
  40938. var out = this._outQ;
  40939. out.copy(SENSOR_TO_VR);
  40940. out.multiply(this._sensorQ);
  40941. if (this.config.YAW_ONLY) {
  40942. out.x = out.z = 0;
  40943. out.normalize();
  40944. }
  40945. this._out[0] = out.x;
  40946. this._out[1] = out.y;
  40947. this._out[2] = out.z;
  40948. this._out[3] = out.w;
  40949. return this._out;
  40950. }
  40951. }, {
  40952. key: '_onSensorError',
  40953. value: function _onSensorError(event) {
  40954. this.errors.push(event.error);
  40955. if (event.error.name === 'NotAllowedError') {
  40956. console.error('Permission to access sensor was denied');
  40957. } else if (event.error.name === 'NotReadableError') {
  40958. console.error('Sensor could not be read');
  40959. } else {
  40960. console.error(event.error);
  40961. }
  40962. this.useDeviceMotion();
  40963. }
  40964. }, {
  40965. key: '_onSensorRead',
  40966. value: function _onSensorRead() {}
  40967. }]);
  40968. return PoseSensor;
  40969. }();
  40970. var rotateInstructionsAsset = 'PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjE5OHB4IiBoZWlnaHQ9IjI0MHB4IiB2aWV3Qm94PSIwIDAgMTk4IDI0MCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4bWxuczpza2V0Y2g9Imh0dHA6Ly93d3cuYm9oZW1pYW5jb2RpbmcuY29tL3NrZXRjaC9ucyI+CiAgICA8IS0tIEdlbmVyYXRvcjogU2tldGNoIDMuMy4zICgxMjA4MSkgLSBodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2ggLS0+CiAgICA8dGl0bGU+dHJhbnNpdGlvbjwvdGl0bGU+CiAgICA8ZGVzYz5DcmVhdGVkIHdpdGggU2tldGNoLjwvZGVzYz4KICAgIDxkZWZzPjwvZGVmcz4KICAgIDxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIHNrZXRjaDp0eXBlPSJNU1BhZ2UiPgogICAgICAgIDxnIGlkPSJ0cmFuc2l0aW9uIiBza2V0Y2g6dHlwZT0iTVNBcnRib2FyZEdyb3VwIj4KICAgICAgICAgICAgPGcgaWQ9IkltcG9ydGVkLUxheWVycy1Db3B5LTQtKy1JbXBvcnRlZC1MYXllcnMtQ29weS0rLUltcG9ydGVkLUxheWVycy1Db3B5LTItQ29weSIgc2tldGNoOnR5cGU9Ik1TTGF5ZXJHcm91cCI+CiAgICAgICAgICAgICAgICA8ZyBpZD0iSW1wb3J0ZWQtTGF5ZXJzLUNvcHktNCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMC4wMDAwMDAsIDEwNy4wMDAwMDApIiBza2V0Y2g6dHlwZT0iTVNTaGFwZUdyb3VwIj4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTQ5LjYyNSwyLjUyNyBDMTQ5LjYyNSwyLjUyNyAxNTUuODA1LDYuMDk2IDE1Ni4zNjIsNi40MTggTDE1Ni4zNjIsNy4zMDQgQzE1Ni4zNjIsNy40ODEgMTU2LjM3NSw3LjY2NCAxNTYuNCw3Ljg1MyBDMTU2LjQxLDcuOTM0IDE1Ni40Miw4LjAxNSAxNTYuNDI3LDguMDk1IEMxNTYuNTY3LDkuNTEgMTU3LjQwMSwxMS4wOTMgMTU4LjUzMiwxMi4wOTQgTDE2NC4yNTIsMTcuMTU2IEwxNjQuMzMzLDE3LjA2NiBDMTY0LjMzMywxNy4wNjYgMTY4LjcxNSwxNC41MzYgMTY5LjU2OCwxNC4wNDIgQzE3MS4wMjUsMTQuODgzIDE5NS41MzgsMjkuMDM1IDE5NS41MzgsMjkuMDM1IEwxOTUuNTM4LDgzLjAzNiBDMTk1LjUzOCw4My44MDcgMTk1LjE1Miw4NC4yNTMgMTk0LjU5LDg0LjI1MyBDMTk0LjM1Nyw4NC4yNTMgMTk0LjA5NSw4NC4xNzcgMTkzLjgxOCw4NC4wMTcgTDE2OS44NTEsNzAuMTc5IEwxNjkuODM3LDcwLjIwMyBMMTQyLjUxNSw4NS45NzggTDE0MS42NjUsODQuNjU1IEMxMzYuOTM0LDgzLjEyNiAxMzEuOTE3LDgxLjkxNSAxMjYuNzE0LDgxLjA0NSBDMTI2LjcwOSw4MS4wNiAxMjYuNzA3LDgxLjA2OSAxMjYuNzA3LDgxLjA2OSBMMTIxLjY0LDk4LjAzIEwxMTMuNzQ5LDEwMi41ODYgTDExMy43MTIsMTAyLjUyMyBMMTEzLjcxMiwxMzAuMTEzIEMxMTMuNzEyLDEzMC44ODUgMTEzLjMyNiwxMzEuMzMgMTEyLjc2NCwxMzEuMzMgQzExMi41MzIsMTMxLjMzIDExMi4yNjksMTMxLjI1NCAxMTEuOTkyLDEzMS4wOTQgTDY5LjUxOSwxMDYuNTcyIEM2OC41NjksMTA2LjAyMyA2Ny43OTksMTA0LjY5NSA2Ny43OTksMTAzLjYwNSBMNjcuNzk5LDEwMi41NyBMNjcuNzc4LDEwMi42MTcgQzY3LjI3LDEwMi4zOTMgNjYuNjQ4LDEwMi4yNDkgNjUuOTYyLDEwMi4yMTggQzY1Ljg3NSwxMDIuMjE0IDY1Ljc4OCwxMDIuMjEyIDY1LjcwMSwxMDIuMjEyIEM2NS42MDYsMTAyLjIxMiA2NS41MTEsMTAyLjIxNSA2NS40MTYsMTAyLjIxOSBDNjUuMTk1LDEwMi4yMjkgNjQuOTc0LDEwMi4yMzUgNjQuNzU0LDEwMi4yMzUgQzY0LjMzMSwxMDIuMjM1IDYzLjkxMSwxMDIuMjE2IDYzLjQ5OCwxMDIuMTc4IEM2MS44NDMsMTAyLjAyNSA2MC4yOTgsMTAxLjU3OCA1OS4wOTQsMTAwLjg4MiBMMTIuNTE4LDczLjk5MiBMMTIuNTIzLDc0LjAwNCBMMi4yNDUsNTUuMjU0IEMxLjI0NCw1My40MjcgMi4wMDQsNTEuMDM4IDMuOTQzLDQ5LjkxOCBMNTkuOTU0LDE3LjU3MyBDNjAuNjI2LDE3LjE4NSA2MS4zNSwxNy4wMDEgNjIuMDUzLDE3LjAwMSBDNjMuMzc5LDE3LjAwMSA2NC42MjUsMTcuNjYgNjUuMjgsMTguODU0IEw2NS4yODUsMTguODUxIEw2NS41MTIsMTkuMjY0IEw2NS41MDYsMTkuMjY4IEM2NS45MDksMjAuMDAzIDY2LjQwNSwyMC42OCA2Ni45ODMsMjEuMjg2IEw2Ny4yNiwyMS41NTYgQzY5LjE3NCwyMy40MDYgNzEuNzI4LDI0LjM1NyA3NC4zNzMsMjQuMzU3IEM3Ni4zMjIsMjQuMzU3IDc4LjMyMSwyMy44NCA4MC4xNDgsMjIuNzg1IEM4MC4xNjEsMjIuNzg1IDg3LjQ2NywxOC41NjYgODcuNDY3LDE4LjU2NiBDODguMTM5LDE4LjE3OCA4OC44NjMsMTcuOTk0IDg5LjU2NiwxNy45OTQgQzkwLjg5MiwxNy45OTQgOTIuMTM4LDE4LjY1MiA5Mi43OTIsMTkuODQ3IEw5Ni4wNDIsMjUuNzc1IEw5Ni4wNjQsMjUuNzU3IEwxMDIuODQ5LDI5LjY3NCBMMTAyLjc0NCwyOS40OTIgTDE0OS42MjUsMi41MjcgTTE0OS42MjUsMC44OTIgQzE0OS4zNDMsMC44OTIgMTQ5LjA2MiwwLjk2NSAxNDguODEsMS4xMSBMMTAyLjY0MSwyNy42NjYgTDk3LjIzMSwyNC41NDIgTDk0LjIyNiwxOS4wNjEgQzkzLjMxMywxNy4zOTQgOTEuNTI3LDE2LjM1OSA4OS41NjYsMTYuMzU4IEM4OC41NTUsMTYuMzU4IDg3LjU0NiwxNi42MzIgODYuNjQ5LDE3LjE1IEM4My44NzgsMTguNzUgNzkuNjg3LDIxLjE2OSA3OS4zNzQsMjEuMzQ1IEM3OS4zNTksMjEuMzUzIDc5LjM0NSwyMS4zNjEgNzkuMzMsMjEuMzY5IEM3Ny43OTgsMjIuMjU0IDc2LjA4NCwyMi43MjIgNzQuMzczLDIyLjcyMiBDNzIuMDgxLDIyLjcyMiA2OS45NTksMjEuODkgNjguMzk3LDIwLjM4IEw2OC4xNDUsMjAuMTM1IEM2Ny43MDYsMTkuNjcyIDY3LjMyMywxOS4xNTYgNjcuMDA2LDE4LjYwMSBDNjYuOTg4LDE4LjU1OSA2Ni45NjgsMTguNTE5IDY2Ljk0NiwxOC40NzkgTDY2LjcxOSwxOC4wNjUgQzY2LjY5LDE4LjAxMiA2Ni42NTgsMTcuOTYgNjYuNjI0LDE3LjkxMSBDNjUuNjg2LDE2LjMzNyA2My45NTEsMTUuMzY2IDYyLjA1MywxNS4zNjYgQzYxLjA0MiwxNS4zNjYgNjAuMDMzLDE1LjY0IDU5LjEzNiwxNi4xNTggTDMuMTI1LDQ4LjUwMiBDMC40MjYsNTAuMDYxIC0wLjYxMyw1My40NDIgMC44MTEsNTYuMDQgTDExLjA4OSw3NC43OSBDMTEuMjY2LDc1LjExMyAxMS41MzcsNzUuMzUzIDExLjg1LDc1LjQ5NCBMNTguMjc2LDEwMi4yOTggQzU5LjY3OSwxMDMuMTA4IDYxLjQzMywxMDMuNjMgNjMuMzQ4LDEwMy44MDYgQzYzLjgxMiwxMDMuODQ4IDY0LjI4NSwxMDMuODcgNjQuNzU0LDEwMy44NyBDNjUsMTAzLjg3IDY1LjI0OSwxMDMuODY0IDY1LjQ5NCwxMDMuODUyIEM2NS41NjMsMTAzLjg0OSA2NS42MzIsMTAzLjg0NyA2NS43MDEsMTAzLjg0NyBDNjUuNzY0LDEwMy44NDcgNjUuODI4LDEwMy44NDkgNjUuODksMTAzLjg1MiBDNjUuOTg2LDEwMy44NTYgNjYuMDgsMTAzLjg2MyA2Ni4xNzMsMTAzLjg3NCBDNjYuMjgyLDEwNS40NjcgNjcuMzMyLDEwNy4xOTcgNjguNzAyLDEwNy45ODggTDExMS4xNzQsMTMyLjUxIEMxMTEuNjk4LDEzMi44MTIgMTEyLjIzMiwxMzIuOTY1IDExMi43NjQsMTMyLjk2NSBDMTE0LjI2MSwxMzIuOTY1IDExNS4zNDcsMTMxLjc2NSAxMTUuMzQ3LDEzMC4xMTMgTDExNS4zNDcsMTAzLjU1MSBMMTIyLjQ1OCw5OS40NDYgQzEyMi44MTksOTkuMjM3IDEyMy4wODcsOTguODk4IDEyMy4yMDcsOTguNDk4IEwxMjcuODY1LDgyLjkwNSBDMTMyLjI3OSw4My43MDIgMTM2LjU1Nyw4NC43NTMgMTQwLjYwNyw4Ni4wMzMgTDE0MS4xNCw4Ni44NjIgQzE0MS40NTEsODcuMzQ2IDE0MS45NzcsODcuNjEzIDE0Mi41MTYsODcuNjEzIEMxNDIuNzk0LDg3LjYxMyAxNDMuMDc2LDg3LjU0MiAxNDMuMzMzLDg3LjM5MyBMMTY5Ljg2NSw3Mi4wNzYgTDE5Myw4NS40MzMgQzE5My41MjMsODUuNzM1IDE5NC4wNTgsODUuODg4IDE5NC41OSw4NS44ODggQzE5Ni4wODcsODUuODg4IDE5Ny4xNzMsODQuNjg5IDE5Ny4xNzMsODMuMDM2IEwxOTcuMTczLDI5LjAzNSBDMTk3LjE3MywyOC40NTEgMTk2Ljg2MSwyNy45MTEgMTk2LjM1NSwyNy42MTkgQzE5Ni4zNTUsMjcuNjE5IDE3MS44NDMsMTMuNDY3IDE3MC4zODUsMTIuNjI2IEMxNzAuMTMyLDEyLjQ4IDE2OS44NSwxMi40MDcgMTY5LjU2OCwxMi40MDcgQzE2OS4yODUsMTIuNDA3IDE2OS4wMDIsMTIuNDgxIDE2OC43NDksMTIuNjI3IEMxNjguMTQzLDEyLjk3OCAxNjUuNzU2LDE0LjM1NyAxNjQuNDI0LDE1LjEyNSBMMTU5LjYxNSwxMC44NyBDMTU4Ljc5NiwxMC4xNDUgMTU4LjE1NCw4LjkzNyAxNTguMDU0LDcuOTM0IEMxNTguMDQ1LDcuODM3IDE1OC4wMzQsNy43MzkgMTU4LjAyMSw3LjY0IEMxNTguMDA1LDcuNTIzIDE1Ny45OTgsNy40MSAxNTcuOTk4LDcuMzA0IEwxNTcuOTk4LDYuNDE4IEMxNTcuOTk4LDUuODM0IDE1Ny42ODYsNS4yOTUgMTU3LjE4MSw1LjAwMiBDMTU2LjYyNCw0LjY4IDE1MC40NDIsMS4xMTEgMTUwLjQ0MiwxLjExMSBDMTUwLjE4OSwwLjk2NSAxNDkuOTA3LDAuODkyIDE0OS42MjUsMC44OTIiIGlkPSJGaWxsLTEiIGZpbGw9IiM0NTVBNjQiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNOTYuMDI3LDI1LjYzNiBMMTQyLjYwMyw1Mi41MjcgQzE0My44MDcsNTMuMjIyIDE0NC41ODIsNTQuMTE0IDE0NC44NDUsNTUuMDY4IEwxNDQuODM1LDU1LjA3NSBMNjMuNDYxLDEwMi4wNTcgTDYzLjQ2LDEwMi4wNTcgQzYxLjgwNiwxMDEuOTA1IDYwLjI2MSwxMDEuNDU3IDU5LjA1NywxMDAuNzYyIEwxMi40ODEsNzMuODcxIEw5Ni4wMjcsMjUuNjM2IiBpZD0iRmlsbC0yIiBmaWxsPSIjRkFGQUZBIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTYzLjQ2MSwxMDIuMTc0IEM2My40NTMsMTAyLjE3NCA2My40NDYsMTAyLjE3NCA2My40MzksMTAyLjE3MiBDNjEuNzQ2LDEwMi4wMTYgNjAuMjExLDEwMS41NjMgNTguOTk4LDEwMC44NjMgTDEyLjQyMiw3My45NzMgQzEyLjM4Niw3My45NTIgMTIuMzY0LDczLjkxNCAxMi4zNjQsNzMuODcxIEMxMi4zNjQsNzMuODMgMTIuMzg2LDczLjc5MSAxMi40MjIsNzMuNzcgTDk1Ljk2OCwyNS41MzUgQzk2LjAwNCwyNS41MTQgOTYuMDQ5LDI1LjUxNCA5Ni4wODUsMjUuNTM1IEwxNDIuNjYxLDUyLjQyNiBDMTQzLjg4OCw1My4xMzQgMTQ0LjY4Miw1NC4wMzggMTQ0Ljk1Nyw1NS4wMzcgQzE0NC45Nyw1NS4wODMgMTQ0Ljk1Myw1NS4xMzMgMTQ0LjkxNSw1NS4xNjEgQzE0NC45MTEsNTUuMTY1IDE0NC44OTgsNTUuMTc0IDE0NC44OTQsNTUuMTc3IEw2My41MTksMTAyLjE1OCBDNjMuNTAxLDEwMi4xNjkgNjMuNDgxLDEwMi4xNzQgNjMuNDYxLDEwMi4xNzQgTDYzLjQ2MSwxMDIuMTc0IFogTTEyLjcxNCw3My44NzEgTDU5LjExNSwxMDAuNjYxIEM2MC4yOTMsMTAxLjM0MSA2MS43ODYsMTAxLjc4MiA2My40MzUsMTAxLjkzNyBMMTQ0LjcwNyw1NS4wMTUgQzE0NC40MjgsNTQuMTA4IDE0My42ODIsNTMuMjg1IDE0Mi41NDQsNTIuNjI4IEw5Ni4wMjcsMjUuNzcxIEwxMi43MTQsNzMuODcxIEwxMi43MTQsNzMuODcxIFoiIGlkPSJGaWxsLTMiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTQ4LjMyNyw1OC40NzEgQzE0OC4xNDUsNTguNDggMTQ3Ljk2Miw1OC40OCAxNDcuNzgxLDU4LjQ3MiBDMTQ1Ljg4Nyw1OC4zODkgMTQ0LjQ3OSw1Ny40MzQgMTQ0LjYzNiw1Ni4zNCBDMTQ0LjY4OSw1NS45NjcgMTQ0LjY2NCw1NS41OTcgMTQ0LjU2NCw1NS4yMzUgTDYzLjQ2MSwxMDIuMDU3IEM2NC4wODksMTAyLjExNSA2NC43MzMsMTAyLjEzIDY1LjM3OSwxMDIuMDk5IEM2NS41NjEsMTAyLjA5IDY1Ljc0MywxMDIuMDkgNjUuOTI1LDEwMi4wOTggQzY3LjgxOSwxMDIuMTgxIDY5LjIyNywxMDMuMTM2IDY5LjA3LDEwNC4yMyBMMTQ4LjMyNyw1OC40NzEiIGlkPSJGaWxsLTQiIGZpbGw9IiNGRkZGRkYiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNNjkuMDcsMTA0LjM0NyBDNjkuMDQ4LDEwNC4zNDcgNjkuMDI1LDEwNC4zNCA2OS4wMDUsMTA0LjMyNyBDNjguOTY4LDEwNC4zMDEgNjguOTQ4LDEwNC4yNTcgNjguOTU1LDEwNC4yMTMgQzY5LDEwMy44OTYgNjguODk4LDEwMy41NzYgNjguNjU4LDEwMy4yODggQzY4LjE1MywxMDIuNjc4IDY3LjEwMywxMDIuMjY2IDY1LjkyLDEwMi4yMTQgQzY1Ljc0MiwxMDIuMjA2IDY1LjU2MywxMDIuMjA3IDY1LjM4NSwxMDIuMjE1IEM2NC43NDIsMTAyLjI0NiA2NC4wODcsMTAyLjIzMiA2My40NSwxMDIuMTc0IEM2My4zOTksMTAyLjE2OSA2My4zNTgsMTAyLjEzMiA2My4zNDcsMTAyLjA4MiBDNjMuMzM2LDEwMi4wMzMgNjMuMzU4LDEwMS45ODEgNjMuNDAyLDEwMS45NTYgTDE0NC41MDYsNTUuMTM0IEMxNDQuNTM3LDU1LjExNiAxNDQuNTc1LDU1LjExMyAxNDQuNjA5LDU1LjEyNyBDMTQ0LjY0Miw1NS4xNDEgMTQ0LjY2OCw1NS4xNyAxNDQuNjc3LDU1LjIwNCBDMTQ0Ljc4MSw1NS41ODUgMTQ0LjgwNiw1NS45NzIgMTQ0Ljc1MSw1Ni4zNTcgQzE0NC43MDYsNTYuNjczIDE0NC44MDgsNTYuOTk0IDE0NS4wNDcsNTcuMjgyIEMxNDUuNTUzLDU3Ljg5MiAxNDYuNjAyLDU4LjMwMyAxNDcuNzg2LDU4LjM1NSBDMTQ3Ljk2NCw1OC4zNjMgMTQ4LjE0Myw1OC4zNjMgMTQ4LjMyMSw1OC4zNTQgQzE0OC4zNzcsNTguMzUyIDE0OC40MjQsNTguMzg3IDE0OC40MzksNTguNDM4IEMxNDguNDU0LDU4LjQ5IDE0OC40MzIsNTguNTQ1IDE0OC4zODUsNTguNTcyIEw2OS4xMjksMTA0LjMzMSBDNjkuMTExLDEwNC4zNDIgNjkuMDksMTA0LjM0NyA2OS4wNywxMDQuMzQ3IEw2OS4wNywxMDQuMzQ3IFogTTY1LjY2NSwxMDEuOTc1IEM2NS43NTQsMTAxLjk3NSA2NS44NDIsMTAxLjk3NyA2NS45MywxMDEuOTgxIEM2Ny4xOTYsMTAyLjAzNyA2OC4yODMsMTAyLjQ2OSA2OC44MzgsMTAzLjEzOSBDNjkuMDY1LDEwMy40MTMgNjkuMTg4LDEwMy43MTQgNjkuMTk4LDEwNC4wMjEgTDE0Ny44ODMsNTguNTkyIEMxNDcuODQ3LDU4LjU5MiAxNDcuODExLDU4LjU5MSAxNDcuNzc2LDU4LjU4OSBDMTQ2LjUwOSw1OC41MzMgMTQ1LjQyMiw1OC4xIDE0NC44NjcsNTcuNDMxIEMxNDQuNTg1LDU3LjA5MSAxNDQuNDY1LDU2LjcwNyAxNDQuNTIsNTYuMzI0IEMxNDQuNTYzLDU2LjAyMSAxNDQuNTUyLDU1LjcxNiAxNDQuNDg4LDU1LjQxNCBMNjMuODQ2LDEwMS45NyBDNjQuMzUzLDEwMi4wMDIgNjQuODY3LDEwMi4wMDYgNjUuMzc0LDEwMS45ODIgQzY1LjQ3MSwxMDEuOTc3IDY1LjU2OCwxMDEuOTc1IDY1LjY2NSwxMDEuOTc1IEw2NS42NjUsMTAxLjk3NSBaIiBpZD0iRmlsbC01IiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTIuMjA4LDU1LjEzNCBDMS4yMDcsNTMuMzA3IDEuOTY3LDUwLjkxNyAzLjkwNiw0OS43OTcgTDU5LjkxNywxNy40NTMgQzYxLjg1NiwxNi4zMzMgNjQuMjQxLDE2LjkwNyA2NS4yNDMsMTguNzM0IEw2NS40NzUsMTkuMTQ0IEM2NS44NzIsMTkuODgyIDY2LjM2OCwyMC41NiA2Ni45NDUsMjEuMTY1IEw2Ny4yMjMsMjEuNDM1IEM3MC41NDgsMjQuNjQ5IDc1LjgwNiwyNS4xNTEgODAuMTExLDIyLjY2NSBMODcuNDMsMTguNDQ1IEM4OS4zNywxNy4zMjYgOTEuNzU0LDE3Ljg5OSA5Mi43NTUsMTkuNzI3IEw5Ni4wMDUsMjUuNjU1IEwxMi40ODYsNzMuODg0IEwyLjIwOCw1NS4xMzQgWiIgaWQ9IkZpbGwtNiIgZmlsbD0iI0ZBRkFGQSI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xMi40ODYsNzQuMDAxIEMxMi40NzYsNzQuMDAxIDEyLjQ2NSw3My45OTkgMTIuNDU1LDczLjk5NiBDMTIuNDI0LDczLjk4OCAxMi4zOTksNzMuOTY3IDEyLjM4NCw3My45NCBMMi4xMDYsNTUuMTkgQzEuMDc1LDUzLjMxIDEuODU3LDUwLjg0NSAzLjg0OCw0OS42OTYgTDU5Ljg1OCwxNy4zNTIgQzYwLjUyNSwxNi45NjcgNjEuMjcxLDE2Ljc2NCA2Mi4wMTYsMTYuNzY0IEM2My40MzEsMTYuNzY0IDY0LjY2NiwxNy40NjYgNjUuMzI3LDE4LjY0NiBDNjUuMzM3LDE4LjY1NCA2NS4zNDUsMTguNjYzIDY1LjM1MSwxOC42NzQgTDY1LjU3OCwxOS4wODggQzY1LjU4NCwxOS4xIDY1LjU4OSwxOS4xMTIgNjUuNTkxLDE5LjEyNiBDNjUuOTg1LDE5LjgzOCA2Ni40NjksMjAuNDk3IDY3LjAzLDIxLjA4NSBMNjcuMzA1LDIxLjM1MSBDNjkuMTUxLDIzLjEzNyA3MS42NDksMjQuMTIgNzQuMzM2LDI0LjEyIEM3Ni4zMTMsMjQuMTIgNzguMjksMjMuNTgyIDgwLjA1MywyMi41NjMgQzgwLjA2NCwyMi41NTcgODAuMDc2LDIyLjU1MyA4MC4wODgsMjIuNTUgTDg3LjM3MiwxOC4zNDQgQzg4LjAzOCwxNy45NTkgODguNzg0LDE3Ljc1NiA4OS41MjksMTcuNzU2IEM5MC45NTYsMTcuNzU2IDkyLjIwMSwxOC40NzIgOTIuODU4LDE5LjY3IEw5Ni4xMDcsMjUuNTk5IEM5Ni4xMzgsMjUuNjU0IDk2LjExOCwyNS43MjQgOTYuMDYzLDI1Ljc1NiBMMTIuNTQ1LDczLjk4NSBDMTIuNTI2LDczLjk5NiAxMi41MDYsNzQuMDAxIDEyLjQ4Niw3NC4wMDEgTDEyLjQ4Niw3NC4wMDEgWiBNNjIuMDE2LDE2Ljk5NyBDNjEuMzEyLDE2Ljk5NyA2MC42MDYsMTcuMTkgNTkuOTc1LDE3LjU1NCBMMy45NjUsNDkuODk5IEMyLjA4Myw1MC45ODUgMS4zNDEsNTMuMzA4IDIuMzEsNTUuMDc4IEwxMi41MzEsNzMuNzIzIEw5NS44NDgsMjUuNjExIEw5Mi42NTMsMTkuNzgyIEM5Mi4wMzgsMTguNjYgOTAuODcsMTcuOTkgODkuNTI5LDE3Ljk5IEM4OC44MjUsMTcuOTkgODguMTE5LDE4LjE4MiA4Ny40ODksMTguNTQ3IEw4MC4xNzIsMjIuNzcyIEM4MC4xNjEsMjIuNzc4IDgwLjE0OSwyMi43ODIgODAuMTM3LDIyLjc4NSBDNzguMzQ2LDIzLjgxMSA3Ni4zNDEsMjQuMzU0IDc0LjMzNiwyNC4zNTQgQzcxLjU4OCwyNC4zNTQgNjkuMDMzLDIzLjM0NyA2Ny4xNDIsMjEuNTE5IEw2Ni44NjQsMjEuMjQ5IEM2Ni4yNzcsMjAuNjM0IDY1Ljc3NCwxOS45NDcgNjUuMzY3LDE5LjIwMyBDNjUuMzYsMTkuMTkyIDY1LjM1NiwxOS4xNzkgNjUuMzU0LDE5LjE2NiBMNjUuMTYzLDE4LjgxOSBDNjUuMTU0LDE4LjgxMSA2NS4xNDYsMTguODAxIDY1LjE0LDE4Ljc5IEM2NC41MjUsMTcuNjY3IDYzLjM1NywxNi45OTcgNjIuMDE2LDE2Ljk5NyBMNjIuMDE2LDE2Ljk5NyBaIiBpZD0iRmlsbC03IiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTQyLjQzNCw0OC44MDggTDQyLjQzNCw0OC44MDggQzM5LjkyNCw0OC44MDcgMzcuNzM3LDQ3LjU1IDM2LjU4Miw0NS40NDMgQzM0Ljc3MSw0Mi4xMzkgMzYuMTQ0LDM3LjgwOSAzOS42NDEsMzUuNzg5IEw1MS45MzIsMjguNjkxIEM1My4xMDMsMjguMDE1IDU0LjQxMywyNy42NTggNTUuNzIxLDI3LjY1OCBDNTguMjMxLDI3LjY1OCA2MC40MTgsMjguOTE2IDYxLjU3MywzMS4wMjMgQzYzLjM4NCwzNC4zMjcgNjIuMDEyLDM4LjY1NyA1OC41MTQsNDAuNjc3IEw0Ni4yMjMsNDcuNzc1IEM0NS4wNTMsNDguNDUgNDMuNzQyLDQ4LjgwOCA0Mi40MzQsNDguODA4IEw0Mi40MzQsNDguODA4IFogTTU1LjcyMSwyOC4xMjUgQzU0LjQ5NSwyOC4xMjUgNTMuMjY1LDI4LjQ2MSA1Mi4xNjYsMjkuMDk2IEwzOS44NzUsMzYuMTk0IEMzNi41OTYsMzguMDg3IDM1LjMwMiw0Mi4xMzYgMzYuOTkyLDQ1LjIxOCBDMzguMDYzLDQ3LjE3MyA0MC4wOTgsNDguMzQgNDIuNDM0LDQ4LjM0IEM0My42NjEsNDguMzQgNDQuODksNDguMDA1IDQ1Ljk5LDQ3LjM3IEw1OC4yODEsNDAuMjcyIEM2MS41NiwzOC4zNzkgNjIuODUzLDM0LjMzIDYxLjE2NCwzMS4yNDggQzYwLjA5MiwyOS4yOTMgNTguMDU4LDI4LjEyNSA1NS43MjEsMjguMTI1IEw1NS43MjEsMjguMTI1IFoiIGlkPSJGaWxsLTgiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTQ5LjU4OCwyLjQwNyBDMTQ5LjU4OCwyLjQwNyAxNTUuNzY4LDUuOTc1IDE1Ni4zMjUsNi4yOTcgTDE1Ni4zMjUsNy4xODQgQzE1Ni4zMjUsNy4zNiAxNTYuMzM4LDcuNTQ0IDE1Ni4zNjIsNy43MzMgQzE1Ni4zNzMsNy44MTQgMTU2LjM4Miw3Ljg5NCAxNTYuMzksNy45NzUgQzE1Ni41Myw5LjM5IDE1Ny4zNjMsMTAuOTczIDE1OC40OTUsMTEuOTc0IEwxNjUuODkxLDE4LjUxOSBDMTY2LjA2OCwxOC42NzUgMTY2LjI0OSwxOC44MTQgMTY2LjQzMiwxOC45MzQgQzE2OC4wMTEsMTkuOTc0IDE2OS4zODIsMTkuNCAxNjkuNDk0LDE3LjY1MiBDMTY5LjU0MywxNi44NjggMTY5LjU1MSwxNi4wNTcgMTY5LjUxNywxNS4yMjMgTDE2OS41MTQsMTUuMDYzIEwxNjkuNTE0LDEzLjkxMiBDMTcwLjc4LDE0LjY0MiAxOTUuNTAxLDI4LjkxNSAxOTUuNTAxLDI4LjkxNSBMMTk1LjUwMSw4Mi45MTUgQzE5NS41MDEsODQuMDA1IDE5NC43MzEsODQuNDQ1IDE5My43ODEsODMuODk3IEwxNTEuMzA4LDU5LjM3NCBDMTUwLjM1OCw1OC44MjYgMTQ5LjU4OCw1Ny40OTcgMTQ5LjU4OCw1Ni40MDggTDE0OS41ODgsMjIuMzc1IiBpZD0iRmlsbC05IiBmaWxsPSIjRkFGQUZBIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTE5NC41NTMsODQuMjUgQzE5NC4yOTYsODQuMjUgMTk0LjAxMyw4NC4xNjUgMTkzLjcyMiw4My45OTcgTDE1MS4yNSw1OS40NzYgQzE1MC4yNjksNTguOTA5IDE0OS40NzEsNTcuNTMzIDE0OS40NzEsNTYuNDA4IEwxNDkuNDcxLDIyLjM3NSBMMTQ5LjcwNSwyMi4zNzUgTDE0OS43MDUsNTYuNDA4IEMxNDkuNzA1LDU3LjQ1OSAxNTAuNDUsNTguNzQ0IDE1MS4zNjYsNTkuMjc0IEwxOTMuODM5LDgzLjc5NSBDMTk0LjI2Myw4NC4wNCAxOTQuNjU1LDg0LjA4MyAxOTQuOTQyLDgzLjkxNyBDMTk1LjIyNyw4My43NTMgMTk1LjM4NCw4My4zOTcgMTk1LjM4NCw4Mi45MTUgTDE5NS4zODQsMjguOTgyIEMxOTQuMTAyLDI4LjI0MiAxNzIuMTA0LDE1LjU0MiAxNjkuNjMxLDE0LjExNCBMMTY5LjYzNCwxNS4yMiBDMTY5LjY2OCwxNi4wNTIgMTY5LjY2LDE2Ljg3NCAxNjkuNjEsMTcuNjU5IEMxNjkuNTU2LDE4LjUwMyAxNjkuMjE0LDE5LjEyMyAxNjguNjQ3LDE5LjQwNSBDMTY4LjAyOCwxOS43MTQgMTY3LjE5NywxOS41NzggMTY2LjM2NywxOS4wMzIgQzE2Ni4xODEsMTguOTA5IDE2NS45OTUsMTguNzY2IDE2NS44MTQsMTguNjA2IEwxNTguNDE3LDEyLjA2MiBDMTU3LjI1OSwxMS4wMzYgMTU2LjQxOCw5LjQzNyAxNTYuMjc0LDcuOTg2IEMxNTYuMjY2LDcuOTA3IDE1Ni4yNTcsNy44MjcgMTU2LjI0Nyw3Ljc0OCBDMTU2LjIyMSw3LjU1NSAxNTYuMjA5LDcuMzY1IDE1Ni4yMDksNy4xODQgTDE1Ni4yMDksNi4zNjQgQzE1NS4zNzUsNS44ODMgMTQ5LjUyOSwyLjUwOCAxNDkuNTI5LDIuNTA4IEwxNDkuNjQ2LDIuMzA2IEMxNDkuNjQ2LDIuMzA2IDE1NS44MjcsNS44NzQgMTU2LjM4NCw2LjE5NiBMMTU2LjQ0Miw2LjIzIEwxNTYuNDQyLDcuMTg0IEMxNTYuNDQyLDcuMzU1IDE1Ni40NTQsNy41MzUgMTU2LjQ3OCw3LjcxNyBDMTU2LjQ4OSw3LjggMTU2LjQ5OSw3Ljg4MiAxNTYuNTA3LDcuOTYzIEMxNTYuNjQ1LDkuMzU4IDE1Ny40NTUsMTAuODk4IDE1OC41NzIsMTEuODg2IEwxNjUuOTY5LDE4LjQzMSBDMTY2LjE0MiwxOC41ODQgMTY2LjMxOSwxOC43MiAxNjYuNDk2LDE4LjgzNyBDMTY3LjI1NCwxOS4zMzYgMTY4LDE5LjQ2NyAxNjguNTQzLDE5LjE5NiBDMTY5LjAzMywxOC45NTMgMTY5LjMyOSwxOC40MDEgMTY5LjM3NywxNy42NDUgQzE2OS40MjcsMTYuODY3IDE2OS40MzQsMTYuMDU0IDE2OS40MDEsMTUuMjI4IEwxNjkuMzk3LDE1LjA2NSBMMTY5LjM5NywxMy43MSBMMTY5LjU3MiwxMy44MSBDMTcwLjgzOSwxNC41NDEgMTk1LjU1OSwyOC44MTQgMTk1LjU1OSwyOC44MTQgTDE5NS42MTgsMjguODQ3IEwxOTUuNjE4LDgyLjkxNSBDMTk1LjYxOCw4My40ODQgMTk1LjQyLDgzLjkxMSAxOTUuMDU5LDg0LjExOSBDMTk0LjkwOCw4NC4yMDYgMTk0LjczNyw4NC4yNSAxOTQuNTUzLDg0LjI1IiBpZD0iRmlsbC0xMCIgZmlsbD0iIzYwN0Q4QiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xNDUuNjg1LDU2LjE2MSBMMTY5LjgsNzAuMDgzIEwxNDMuODIyLDg1LjA4MSBMMTQyLjM2LDg0Ljc3NCBDMTM1LjgyNiw4Mi42MDQgMTI4LjczMiw4MS4wNDYgMTIxLjM0MSw4MC4xNTggQzExNi45NzYsNzkuNjM0IDExMi42NzgsODEuMjU0IDExMS43NDMsODMuNzc4IEMxMTEuNTA2LDg0LjQxNCAxMTEuNTAzLDg1LjA3MSAxMTEuNzMyLDg1LjcwNiBDMTEzLjI3LDg5Ljk3MyAxMTUuOTY4LDk0LjA2OSAxMTkuNzI3LDk3Ljg0MSBMMTIwLjI1OSw5OC42ODYgQzEyMC4yNiw5OC42ODUgOTQuMjgyLDExMy42ODMgOTQuMjgyLDExMy42ODMgTDcwLjE2Nyw5OS43NjEgTDE0NS42ODUsNTYuMTYxIiBpZD0iRmlsbC0xMSIgZmlsbD0iI0ZGRkZGRiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik05NC4yODIsMTEzLjgxOCBMOTQuMjIzLDExMy43ODUgTDY5LjkzMyw5OS43NjEgTDcwLjEwOCw5OS42NiBMMTQ1LjY4NSw1Ni4wMjYgTDE0NS43NDMsNTYuMDU5IEwxNzAuMDMzLDcwLjA4MyBMMTQzLjg0Miw4NS4yMDUgTDE0My43OTcsODUuMTk1IEMxNDMuNzcyLDg1LjE5IDE0Mi4zMzYsODQuODg4IDE0Mi4zMzYsODQuODg4IEMxMzUuNzg3LDgyLjcxNCAxMjguNzIzLDgxLjE2MyAxMjEuMzI3LDgwLjI3NCBDMTIwLjc4OCw4MC4yMDkgMTIwLjIzNiw4MC4xNzcgMTE5LjY4OSw4MC4xNzcgQzExNS45MzEsODAuMTc3IDExMi42MzUsODEuNzA4IDExMS44NTIsODMuODE5IEMxMTEuNjI0LDg0LjQzMiAxMTEuNjIxLDg1LjA1MyAxMTEuODQyLDg1LjY2NyBDMTEzLjM3Nyw4OS45MjUgMTE2LjA1OCw5My45OTMgMTE5LjgxLDk3Ljc1OCBMMTE5LjgyNiw5Ny43NzkgTDEyMC4zNTIsOTguNjE0IEMxMjAuMzU0LDk4LjYxNyAxMjAuMzU2LDk4LjYyIDEyMC4zNTgsOTguNjI0IEwxMjAuNDIyLDk4LjcyNiBMMTIwLjMxNyw5OC43ODcgQzEyMC4yNjQsOTguODE4IDk0LjU5OSwxMTMuNjM1IDk0LjM0LDExMy43ODUgTDk0LjI4MiwxMTMuODE4IEw5NC4yODIsMTEzLjgxOCBaIE03MC40MDEsOTkuNzYxIEw5NC4yODIsMTEzLjU0OSBMMTE5LjA4NCw5OS4yMjkgQzExOS42Myw5OC45MTQgMTE5LjkzLDk4Ljc0IDEyMC4xMDEsOTguNjU0IEwxMTkuNjM1LDk3LjkxNCBDMTE1Ljg2NCw5NC4xMjcgMTEzLjE2OCw5MC4wMzMgMTExLjYyMiw4NS43NDYgQzExMS4zODIsODUuMDc5IDExMS4zODYsODQuNDA0IDExMS42MzMsODMuNzM4IEMxMTIuNDQ4LDgxLjUzOSAxMTUuODM2LDc5Ljk0MyAxMTkuNjg5LDc5Ljk0MyBDMTIwLjI0Niw3OS45NDMgMTIwLjgwNiw3OS45NzYgMTIxLjM1NSw4MC4wNDIgQzEyOC43NjcsODAuOTMzIDEzNS44NDYsODIuNDg3IDE0Mi4zOTYsODQuNjYzIEMxNDMuMjMyLDg0LjgzOCAxNDMuNjExLDg0LjkxNyAxNDMuNzg2LDg0Ljk2NyBMMTY5LjU2Niw3MC4wODMgTDE0NS42ODUsNTYuMjk1IEw3MC40MDEsOTkuNzYxIEw3MC40MDEsOTkuNzYxIFoiIGlkPSJGaWxsLTEyIiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTE2Ny4yMywxOC45NzkgTDE2Ny4yMyw2OS44NSBMMTM5LjkwOSw4NS42MjMgTDEzMy40NDgsNzEuNDU2IEMxMzIuNTM4LDY5LjQ2IDEzMC4wMiw2OS43MTggMTI3LjgyNCw3Mi4wMyBDMTI2Ljc2OSw3My4xNCAxMjUuOTMxLDc0LjU4NSAxMjUuNDk0LDc2LjA0OCBMMTE5LjAzNCw5Ny42NzYgTDkxLjcxMiwxMTMuNDUgTDkxLjcxMiw2Mi41NzkgTDE2Ny4yMywxOC45NzkiIGlkPSJGaWxsLTEzIiBmaWxsPSIjRkZGRkZGIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTkxLjcxMiwxMTMuNTY3IEM5MS42OTIsMTEzLjU2NyA5MS42NzIsMTEzLjU2MSA5MS42NTMsMTEzLjU1MSBDOTEuNjE4LDExMy41MyA5MS41OTUsMTEzLjQ5MiA5MS41OTUsMTEzLjQ1IEw5MS41OTUsNjIuNTc5IEM5MS41OTUsNjIuNTM3IDkxLjYxOCw2Mi40OTkgOTEuNjUzLDYyLjQ3OCBMMTY3LjE3MiwxOC44NzggQzE2Ny4yMDgsMTguODU3IDE2Ny4yNTIsMTguODU3IDE2Ny4yODgsMTguODc4IEMxNjcuMzI0LDE4Ljg5OSAxNjcuMzQ3LDE4LjkzNyAxNjcuMzQ3LDE4Ljk3OSBMMTY3LjM0Nyw2OS44NSBDMTY3LjM0Nyw2OS44OTEgMTY3LjMyNCw2OS45MyAxNjcuMjg4LDY5Ljk1IEwxMzkuOTY3LDg1LjcyNSBDMTM5LjkzOSw4NS43NDEgMTM5LjkwNSw4NS43NDUgMTM5Ljg3Myw4NS43MzUgQzEzOS44NDIsODUuNzI1IDEzOS44MTYsODUuNzAyIDEzOS44MDIsODUuNjcyIEwxMzMuMzQyLDcxLjUwNCBDMTMyLjk2Nyw3MC42ODIgMTMyLjI4LDcwLjIyOSAxMzEuNDA4LDcwLjIyOSBDMTMwLjMxOSw3MC4yMjkgMTI5LjA0NCw3MC45MTUgMTI3LjkwOCw3Mi4xMSBDMTI2Ljg3NCw3My4yIDEyNi4wMzQsNzQuNjQ3IDEyNS42MDYsNzYuMDgyIEwxMTkuMTQ2LDk3LjcwOSBDMTE5LjEzNyw5Ny43MzggMTE5LjExOCw5Ny43NjIgMTE5LjA5Miw5Ny43NzcgTDkxLjc3LDExMy41NTEgQzkxLjc1MiwxMTMuNTYxIDkxLjczMiwxMTMuNTY3IDkxLjcxMiwxMTMuNTY3IEw5MS43MTIsMTEzLjU2NyBaIE05MS44MjksNjIuNjQ3IEw5MS44MjksMTEzLjI0OCBMMTE4LjkzNSw5Ny41OTggTDEyNS4zODIsNzYuMDE1IEMxMjUuODI3LDc0LjUyNSAxMjYuNjY0LDczLjA4MSAxMjcuNzM5LDcxLjk1IEMxMjguOTE5LDcwLjcwOCAxMzAuMjU2LDY5Ljk5NiAxMzEuNDA4LDY5Ljk5NiBDMTMyLjM3Nyw2OS45OTYgMTMzLjEzOSw3MC40OTcgMTMzLjU1NCw3MS40MDcgTDEzOS45NjEsODUuNDU4IEwxNjcuMTEzLDY5Ljc4MiBMMTY3LjExMywxOS4xODEgTDkxLjgyOSw2Mi42NDcgTDkxLjgyOSw2Mi42NDcgWiIgaWQ9IkZpbGwtMTQiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTY4LjU0MywxOS4yMTMgTDE2OC41NDMsNzAuMDgzIEwxNDEuMjIxLDg1Ljg1NyBMMTM0Ljc2MSw3MS42ODkgQzEzMy44NTEsNjkuNjk0IDEzMS4zMzMsNjkuOTUxIDEyOS4xMzcsNzIuMjYzIEMxMjguMDgyLDczLjM3NCAxMjcuMjQ0LDc0LjgxOSAxMjYuODA3LDc2LjI4MiBMMTIwLjM0Niw5Ny45MDkgTDkzLjAyNSwxMTMuNjgzIEw5My4wMjUsNjIuODEzIEwxNjguNTQzLDE5LjIxMyIgaWQ9IkZpbGwtMTUiIGZpbGw9IiNGRkZGRkYiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNOTMuMDI1LDExMy44IEM5My4wMDUsMTEzLjggOTIuOTg0LDExMy43OTUgOTIuOTY2LDExMy43ODUgQzkyLjkzMSwxMTMuNzY0IDkyLjkwOCwxMTMuNzI1IDkyLjkwOCwxMTMuNjg0IEw5Mi45MDgsNjIuODEzIEM5Mi45MDgsNjIuNzcxIDkyLjkzMSw2Mi43MzMgOTIuOTY2LDYyLjcxMiBMMTY4LjQ4NCwxOS4xMTIgQzE2OC41MiwxOS4wOSAxNjguNTY1LDE5LjA5IDE2OC42MDEsMTkuMTEyIEMxNjguNjM3LDE5LjEzMiAxNjguNjYsMTkuMTcxIDE2OC42NiwxOS4yMTIgTDE2OC42Niw3MC4wODMgQzE2OC42Niw3MC4xMjUgMTY4LjYzNyw3MC4xNjQgMTY4LjYwMSw3MC4xODQgTDE0MS4yOCw4NS45NTggQzE0MS4yNTEsODUuOTc1IDE0MS4yMTcsODUuOTc5IDE0MS4xODYsODUuOTY4IEMxNDEuMTU0LDg1Ljk1OCAxNDEuMTI5LDg1LjkzNiAxNDEuMTE1LDg1LjkwNiBMMTM0LjY1NSw3MS43MzggQzEzNC4yOCw3MC45MTUgMTMzLjU5Myw3MC40NjMgMTMyLjcyLDcwLjQ2MyBDMTMxLjYzMiw3MC40NjMgMTMwLjM1Nyw3MS4xNDggMTI5LjIyMSw3Mi4zNDQgQzEyOC4xODYsNzMuNDMzIDEyNy4zNDcsNzQuODgxIDEyNi45MTksNzYuMzE1IEwxMjAuNDU4LDk3Ljk0MyBDMTIwLjQ1LDk3Ljk3MiAxMjAuNDMxLDk3Ljk5NiAxMjAuNDA1LDk4LjAxIEw5My4wODMsMTEzLjc4NSBDOTMuMDY1LDExMy43OTUgOTMuMDQ1LDExMy44IDkzLjAyNSwxMTMuOCBMOTMuMDI1LDExMy44IFogTTkzLjE0Miw2Mi44ODEgTDkzLjE0MiwxMTMuNDgxIEwxMjAuMjQ4LDk3LjgzMiBMMTI2LjY5NSw3Ni4yNDggQzEyNy4xNCw3NC43NTggMTI3Ljk3Nyw3My4zMTUgMTI5LjA1Miw3Mi4xODMgQzEzMC4yMzEsNzAuOTQyIDEzMS41NjgsNzAuMjI5IDEzMi43Miw3MC4yMjkgQzEzMy42ODksNzAuMjI5IDEzNC40NTIsNzAuNzMxIDEzNC44NjcsNzEuNjQxIEwxNDEuMjc0LDg1LjY5MiBMMTY4LjQyNiw3MC4wMTYgTDE2OC40MjYsMTkuNDE1IEw5My4xNDIsNjIuODgxIEw5My4xNDIsNjIuODgxIFoiIGlkPSJGaWxsLTE2IiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTE2OS44LDcwLjA4MyBMMTQyLjQ3OCw4NS44NTcgTDEzNi4wMTgsNzEuNjg5IEMxMzUuMTA4LDY5LjY5NCAxMzIuNTksNjkuOTUxIDEzMC4zOTMsNzIuMjYzIEMxMjkuMzM5LDczLjM3NCAxMjguNSw3NC44MTkgMTI4LjA2NCw3Ni4yODIgTDEyMS42MDMsOTcuOTA5IEw5NC4yODIsMTEzLjY4MyBMOTQuMjgyLDYyLjgxMyBMMTY5LjgsMTkuMjEzIEwxNjkuOCw3MC4wODMgWiIgaWQ9IkZpbGwtMTciIGZpbGw9IiNGQUZBRkEiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNOTQuMjgyLDExMy45MTcgQzk0LjI0MSwxMTMuOTE3IDk0LjIwMSwxMTMuOTA3IDk0LjE2NSwxMTMuODg2IEM5NC4wOTMsMTEzLjg0NSA5NC4wNDgsMTEzLjc2NyA5NC4wNDgsMTEzLjY4NCBMOTQuMDQ4LDYyLjgxMyBDOTQuMDQ4LDYyLjczIDk0LjA5Myw2Mi42NTIgOTQuMTY1LDYyLjYxMSBMMTY5LjY4MywxOS4wMSBDMTY5Ljc1NSwxOC45NjkgMTY5Ljg0NCwxOC45NjkgMTY5LjkxNywxOS4wMSBDMTY5Ljk4OSwxOS4wNTIgMTcwLjAzMywxOS4xMjkgMTcwLjAzMywxOS4yMTIgTDE3MC4wMzMsNzAuMDgzIEMxNzAuMDMzLDcwLjE2NiAxNjkuOTg5LDcwLjI0NCAxNjkuOTE3LDcwLjI4NSBMMTQyLjU5NSw4Ni4wNiBDMTQyLjUzOCw4Ni4wOTIgMTQyLjQ2OSw4Ni4xIDE0Mi40MDcsODYuMDggQzE0Mi4zNDQsODYuMDYgMTQyLjI5Myw4Ni4wMTQgMTQyLjI2Niw4NS45NTQgTDEzNS44MDUsNzEuNzg2IEMxMzUuNDQ1LDcwLjk5NyAxMzQuODEzLDcwLjU4IDEzMy45NzcsNzAuNTggQzEzMi45MjEsNzAuNTggMTMxLjY3Niw3MS4yNTIgMTMwLjU2Miw3Mi40MjQgQzEyOS41NCw3My41MDEgMTI4LjcxMSw3NC45MzEgMTI4LjI4Nyw3Ni4zNDggTDEyMS44MjcsOTcuOTc2IEMxMjEuODEsOTguMDM0IDEyMS43NzEsOTguMDgyIDEyMS43Miw5OC4xMTIgTDk0LjM5OCwxMTMuODg2IEM5NC4zNjIsMTEzLjkwNyA5NC4zMjIsMTEzLjkxNyA5NC4yODIsMTEzLjkxNyBMOTQuMjgyLDExMy45MTcgWiBNOTQuNTE1LDYyLjk0OCBMOTQuNTE1LDExMy4yNzkgTDEyMS40MDYsOTcuNzU0IEwxMjcuODQsNzYuMjE1IEMxMjguMjksNzQuNzA4IDEyOS4xMzcsNzMuMjQ3IDEzMC4yMjQsNzIuMTAzIEMxMzEuNDI1LDcwLjgzOCAxMzIuNzkzLDcwLjExMiAxMzMuOTc3LDcwLjExMiBDMTM0Ljk5NSw3MC4xMTIgMTM1Ljc5NSw3MC42MzggMTM2LjIzLDcxLjU5MiBMMTQyLjU4NCw4NS41MjYgTDE2OS41NjYsNjkuOTQ4IEwxNjkuNTY2LDE5LjYxNyBMOTQuNTE1LDYyLjk0OCBMOTQuNTE1LDYyLjk0OCBaIiBpZD0iRmlsbC0xOCIgZmlsbD0iIzYwN0Q4QiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xMDkuODk0LDkyLjk0MyBMMTA5Ljg5NCw5Mi45NDMgQzEwOC4xMiw5Mi45NDMgMTA2LjY1Myw5Mi4yMTggMTA1LjY1LDkwLjgyMyBDMTA1LjU4Myw5MC43MzEgMTA1LjU5Myw5MC42MSAxMDUuNjczLDkwLjUyOSBDMTA1Ljc1Myw5MC40NDggMTA1Ljg4LDkwLjQ0IDEwNS45NzQsOTAuNTA2IEMxMDYuNzU0LDkxLjA1MyAxMDcuNjc5LDkxLjMzMyAxMDguNzI0LDkxLjMzMyBDMTEwLjA0Nyw5MS4zMzMgMTExLjQ3OCw5MC44OTQgMTEyLjk4LDkwLjAyNyBDMTE4LjI5MSw4Ni45NiAxMjIuNjExLDc5LjUwOSAxMjIuNjExLDczLjQxNiBDMTIyLjYxMSw3MS40ODkgMTIyLjE2OSw2OS44NTYgMTIxLjMzMyw2OC42OTIgQzEyMS4yNjYsNjguNiAxMjEuMjc2LDY4LjQ3MyAxMjEuMzU2LDY4LjM5MiBDMTIxLjQzNiw2OC4zMTEgMTIxLjU2Myw2OC4yOTkgMTIxLjY1Niw2OC4zNjUgQzEyMy4zMjcsNjkuNTM3IDEyNC4yNDcsNzEuNzQ2IDEyNC4yNDcsNzQuNTg0IEMxMjQuMjQ3LDgwLjgyNiAxMTkuODIxLDg4LjQ0NyAxMTQuMzgyLDkxLjU4NyBDMTEyLjgwOCw5Mi40OTUgMTExLjI5OCw5Mi45NDMgMTA5Ljg5NCw5Mi45NDMgTDEwOS44OTQsOTIuOTQzIFogTTEwNi45MjUsOTEuNDAxIEMxMDcuNzM4LDkyLjA1MiAxMDguNzQ1LDkyLjI3OCAxMDkuODkzLDkyLjI3OCBMMTA5Ljg5NCw5Mi4yNzggQzExMS4yMTUsOTIuMjc4IDExMi42NDcsOTEuOTUxIDExNC4xNDgsOTEuMDg0IEMxMTkuNDU5LDg4LjAxNyAxMjMuNzgsODAuNjIxIDEyMy43OCw3NC41MjggQzEyMy43OCw3Mi41NDkgMTIzLjMxNyw3MC45MjkgMTIyLjQ1NCw2OS43NjcgQzEyMi44NjUsNzAuODAyIDEyMy4wNzksNzIuMDQyIDEyMy4wNzksNzMuNDAyIEMxMjMuMDc5LDc5LjY0NSAxMTguNjUzLDg3LjI4NSAxMTMuMjE0LDkwLjQyNSBDMTExLjY0LDkxLjMzNCAxMTAuMTMsOTEuNzQyIDEwOC43MjQsOTEuNzQyIEMxMDguMDgzLDkxLjc0MiAxMDcuNDgxLDkxLjU5MyAxMDYuOTI1LDkxLjQwMSBMMTA2LjkyNSw5MS40MDEgWiIgaWQ9IkZpbGwtMTkiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTEzLjA5Nyw5MC4yMyBDMTE4LjQ4MSw4Ny4xMjIgMTIyLjg0NSw3OS41OTQgMTIyLjg0NSw3My40MTYgQzEyMi44NDUsNzEuMzY1IDEyMi4zNjIsNjkuNzI0IDEyMS41MjIsNjguNTU2IEMxMTkuNzM4LDY3LjMwNCAxMTcuMTQ4LDY3LjM2MiAxMTQuMjY1LDY5LjAyNiBDMTA4Ljg4MSw3Mi4xMzQgMTA0LjUxNyw3OS42NjIgMTA0LjUxNyw4NS44NCBDMTA0LjUxNyw4Ny44OTEgMTA1LDg5LjUzMiAxMDUuODQsOTAuNyBDMTA3LjYyNCw5MS45NTIgMTEwLjIxNCw5MS44OTQgMTEzLjA5Nyw5MC4yMyIgaWQ9IkZpbGwtMjAiIGZpbGw9IiNGQUZBRkEiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTA4LjcyNCw5MS42MTQgTDEwOC43MjQsOTEuNjE0IEMxMDcuNTgyLDkxLjYxNCAxMDYuNTY2LDkxLjQwMSAxMDUuNzA1LDkwLjc5NyBDMTA1LjY4NCw5MC43ODMgMTA1LjY2NSw5MC44MTEgMTA1LjY1LDkwLjc5IEMxMDQuNzU2LDg5LjU0NiAxMDQuMjgzLDg3Ljg0MiAxMDQuMjgzLDg1LjgxNyBDMTA0LjI4Myw3OS41NzUgMTA4LjcwOSw3MS45NTMgMTE0LjE0OCw2OC44MTIgQzExNS43MjIsNjcuOTA0IDExNy4yMzIsNjcuNDQ5IDExOC42MzgsNjcuNDQ5IEMxMTkuNzgsNjcuNDQ5IDEyMC43OTYsNjcuNzU4IDEyMS42NTYsNjguMzYyIEMxMjEuNjc4LDY4LjM3NyAxMjEuNjk3LDY4LjM5NyAxMjEuNzEyLDY4LjQxOCBDMTIyLjYwNiw2OS42NjIgMTIzLjA3OSw3MS4zOSAxMjMuMDc5LDczLjQxNSBDMTIzLjA3OSw3OS42NTggMTE4LjY1Myw4Ny4xOTggMTEzLjIxNCw5MC4zMzggQzExMS42NCw5MS4yNDcgMTEwLjEzLDkxLjYxNCAxMDguNzI0LDkxLjYxNCBMMTA4LjcyNCw5MS42MTQgWiBNMTA2LjAwNiw5MC41MDUgQzEwNi43OCw5MS4wMzcgMTA3LjY5NCw5MS4yODEgMTA4LjcyNCw5MS4yODEgQzExMC4wNDcsOTEuMjgxIDExMS40NzgsOTAuODY4IDExMi45OCw5MC4wMDEgQzExOC4yOTEsODYuOTM1IDEyMi42MTEsNzkuNDk2IDEyMi42MTEsNzMuNDAzIEMxMjIuNjExLDcxLjQ5NCAxMjIuMTc3LDY5Ljg4IDEyMS4zNTYsNjguNzE4IEMxMjAuNTgyLDY4LjE4NSAxMTkuNjY4LDY3LjkxOSAxMTguNjM4LDY3LjkxOSBDMTE3LjMxNSw2Ny45MTkgMTE1Ljg4Myw2OC4zNiAxMTQuMzgyLDY5LjIyNyBDMTA5LjA3MSw3Mi4yOTMgMTA0Ljc1MSw3OS43MzMgMTA0Ljc1MSw4NS44MjYgQzEwNC43NTEsODcuNzM1IDEwNS4xODUsODkuMzQzIDEwNi4wMDYsOTAuNTA1IEwxMDYuMDA2LDkwLjUwNSBaIiBpZD0iRmlsbC0yMSIgZmlsbD0iIzYwN0Q4QiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xNDkuMzE4LDcuMjYyIEwxMzkuMzM0LDE2LjE0IEwxNTUuMjI3LDI3LjE3MSBMMTYwLjgxNiwyMS4wNTkgTDE0OS4zMTgsNy4yNjIiIGlkPSJGaWxsLTIyIiBmaWxsPSIjRkFGQUZBIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTE2OS42NzYsMTMuODQgTDE1OS45MjgsMTkuNDY3IEMxNTYuMjg2LDIxLjU3IDE1MC40LDIxLjU4IDE0Ni43ODEsMTkuNDkxIEMxNDMuMTYxLDE3LjQwMiAxNDMuMTgsMTQuMDAzIDE0Ni44MjIsMTEuOSBMMTU2LjMxNyw2LjI5MiBMMTQ5LjU4OCwyLjQwNyBMNjcuNzUyLDQ5LjQ3OCBMMTEzLjY3NSw3NS45OTIgTDExNi43NTYsNzQuMjEzIEMxMTcuMzg3LDczLjg0OCAxMTcuNjI1LDczLjMxNSAxMTcuMzc0LDcyLjgyMyBDMTE1LjAxNyw2OC4xOTEgMTE0Ljc4MSw2My4yNzcgMTE2LjY5MSw1OC41NjEgQzEyMi4zMjksNDQuNjQxIDE0MS4yLDMzLjc0NiAxNjUuMzA5LDMwLjQ5MSBDMTczLjQ3OCwyOS4zODggMTgxLjk4OSwyOS41MjQgMTkwLjAxMywzMC44ODUgQzE5MC44NjUsMzEuMDMgMTkxLjc4OSwzMC44OTMgMTkyLjQyLDMwLjUyOCBMMTk1LjUwMSwyOC43NSBMMTY5LjY3NiwxMy44NCIgaWQ9IkZpbGwtMjMiIGZpbGw9IiNGQUZBRkEiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTEzLjY3NSw3Ni40NTkgQzExMy41OTQsNzYuNDU5IDExMy41MTQsNzYuNDM4IDExMy40NDIsNzYuMzk3IEw2Ny41MTgsNDkuODgyIEM2Ny4zNzQsNDkuNzk5IDY3LjI4NCw0OS42NDUgNjcuMjg1LDQ5LjQ3OCBDNjcuMjg1LDQ5LjMxMSA2Ny4zNzQsNDkuMTU3IDY3LjUxOSw0OS4wNzMgTDE0OS4zNTUsMi4wMDIgQzE0OS40OTksMS45MTkgMTQ5LjY3NywxLjkxOSAxNDkuODIxLDIuMDAyIEwxNTYuNTUsNS44ODcgQzE1Ni43NzQsNi4wMTcgMTU2Ljg1LDYuMzAyIDE1Ni43MjIsNi41MjYgQzE1Ni41OTIsNi43NDkgMTU2LjMwNyw2LjgyNiAxNTYuMDgzLDYuNjk2IEwxNDkuNTg3LDIuOTQ2IEw2OC42ODcsNDkuNDc5IEwxMTMuNjc1LDc1LjQ1MiBMMTE2LjUyMyw3My44MDggQzExNi43MTUsNzMuNjk3IDExNy4xNDMsNzMuMzk5IDExNi45NTgsNzMuMDM1IEMxMTQuNTQyLDY4LjI4NyAxMTQuMyw2My4yMjEgMTE2LjI1OCw1OC4zODUgQzExOS4wNjQsNTEuNDU4IDEyNS4xNDMsNDUuMTQzIDEzMy44NCw0MC4xMjIgQzE0Mi40OTcsMzUuMTI0IDE1My4zNTgsMzEuNjMzIDE2NS4yNDcsMzAuMDI4IEMxNzMuNDQ1LDI4LjkyMSAxODIuMDM3LDI5LjA1OCAxOTAuMDkxLDMwLjQyNSBDMTkwLjgzLDMwLjU1IDE5MS42NTIsMzAuNDMyIDE5Mi4xODYsMzAuMTI0IEwxOTQuNTY3LDI4Ljc1IEwxNjkuNDQyLDE0LjI0NCBDMTY5LjIxOSwxNC4xMTUgMTY5LjE0MiwxMy44MjkgMTY5LjI3MSwxMy42MDYgQzE2OS40LDEzLjM4MiAxNjkuNjg1LDEzLjMwNiAxNjkuOTA5LDEzLjQzNSBMMTk1LjczNCwyOC4zNDUgQzE5NS44NzksMjguNDI4IDE5NS45NjgsMjguNTgzIDE5NS45NjgsMjguNzUgQzE5NS45NjgsMjguOTE2IDE5NS44NzksMjkuMDcxIDE5NS43MzQsMjkuMTU0IEwxOTIuNjUzLDMwLjkzMyBDMTkxLjkzMiwzMS4zNSAxOTAuODksMzEuNTA4IDE4OS45MzUsMzEuMzQ2IEMxODEuOTcyLDI5Ljk5NSAxNzMuNDc4LDI5Ljg2IDE2NS4zNzIsMzAuOTU0IEMxNTMuNjAyLDMyLjU0MyAxNDIuODYsMzUuOTkzIDEzNC4zMDcsNDAuOTMxIEMxMjUuNzkzLDQ1Ljg0NyAxMTkuODUxLDUyLjAwNCAxMTcuMTI0LDU4LjczNiBDMTE1LjI3LDYzLjMxNCAxMTUuNTAxLDY4LjExMiAxMTcuNzksNzIuNjExIEMxMTguMTYsNzMuMzM2IDExNy44NDUsNzQuMTI0IDExNi45OSw3NC42MTcgTDExMy45MDksNzYuMzk3IEMxMTMuODM2LDc2LjQzOCAxMTMuNzU2LDc2LjQ1OSAxMTMuNjc1LDc2LjQ1OSIgaWQ9IkZpbGwtMjQiIGZpbGw9IiM0NTVBNjQiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTUzLjMxNiwyMS4yNzkgQzE1MC45MDMsMjEuMjc5IDE0OC40OTUsMjAuNzUxIDE0Ni42NjQsMTkuNjkzIEMxNDQuODQ2LDE4LjY0NCAxNDMuODQ0LDE3LjIzMiAxNDMuODQ0LDE1LjcxOCBDMTQzLjg0NCwxNC4xOTEgMTQ0Ljg2LDEyLjc2MyAxNDYuNzA1LDExLjY5OCBMMTU2LjE5OCw2LjA5MSBDMTU2LjMwOSw2LjAyNSAxNTYuNDUyLDYuMDYyIDE1Ni41MTgsNi4xNzMgQzE1Ni41ODMsNi4yODQgMTU2LjU0Nyw2LjQyNyAxNTYuNDM2LDYuNDkzIEwxNDYuOTQsMTIuMTAyIEMxNDUuMjQ0LDEzLjA4MSAxNDQuMzEyLDE0LjM2NSAxNDQuMzEyLDE1LjcxOCBDMTQ0LjMxMiwxNy4wNTggMTQ1LjIzLDE4LjMyNiAxNDYuODk3LDE5LjI4OSBDMTUwLjQ0NiwyMS4zMzggMTU2LjI0LDIxLjMyNyAxNTkuODExLDE5LjI2NSBMMTY5LjU1OSwxMy42MzcgQzE2OS42NywxMy41NzMgMTY5LjgxMywxMy42MTEgMTY5Ljg3OCwxMy43MjMgQzE2OS45NDMsMTMuODM0IDE2OS45MDQsMTMuOTc3IDE2OS43OTMsMTQuMDQyIEwxNjAuMDQ1LDE5LjY3IEMxNTguMTg3LDIwLjc0MiAxNTUuNzQ5LDIxLjI3OSAxNTMuMzE2LDIxLjI3OSIgaWQ9IkZpbGwtMjUiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTEzLjY3NSw3NS45OTIgTDY3Ljc2Miw0OS40ODQiIGlkPSJGaWxsLTI2IiBmaWxsPSIjNDU1QTY0Ij48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTExMy42NzUsNzYuMzQyIEMxMTMuNjE1LDc2LjM0MiAxMTMuNTU1LDc2LjMyNyAxMTMuNSw3Ni4yOTUgTDY3LjU4Nyw0OS43ODcgQzY3LjQxOSw0OS42OSA2Ny4zNjIsNDkuNDc2IDY3LjQ1OSw0OS4zMDkgQzY3LjU1Niw0OS4xNDEgNjcuNzcsNDkuMDgzIDY3LjkzNyw0OS4xOCBMMTEzLjg1LDc1LjY4OCBDMTE0LjAxOCw3NS43ODUgMTE0LjA3NSw3NiAxMTMuOTc4LDc2LjE2NyBDMTEzLjkxNCw3Ni4yNzkgMTEzLjc5Niw3Ni4zNDIgMTEzLjY3NSw3Ni4zNDIiIGlkPSJGaWxsLTI3IiBmaWxsPSIjNDU1QTY0Ij48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTY3Ljc2Miw0OS40ODQgTDY3Ljc2MiwxMDMuNDg1IEM2Ny43NjIsMTA0LjU3NSA2OC41MzIsMTA1LjkwMyA2OS40ODIsMTA2LjQ1MiBMMTExLjk1NSwxMzAuOTczIEMxMTIuOTA1LDEzMS41MjIgMTEzLjY3NSwxMzEuMDgzIDExMy42NzUsMTI5Ljk5MyBMMTEzLjY3NSw3NS45OTIiIGlkPSJGaWxsLTI4IiBmaWxsPSIjRkFGQUZBIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTExMi43MjcsMTMxLjU2MSBDMTEyLjQzLDEzMS41NjEgMTEyLjEwNywxMzEuNDY2IDExMS43OCwxMzEuMjc2IEw2OS4zMDcsMTA2Ljc1NSBDNjguMjQ0LDEwNi4xNDIgNjcuNDEyLDEwNC43MDUgNjcuNDEyLDEwMy40ODUgTDY3LjQxMiw0OS40ODQgQzY3LjQxMiw0OS4yOSA2Ny41NjksNDkuMTM0IDY3Ljc2Miw0OS4xMzQgQzY3Ljk1Niw0OS4xMzQgNjguMTEzLDQ5LjI5IDY4LjExMyw0OS40ODQgTDY4LjExMywxMDMuNDg1IEM2OC4xMTMsMTA0LjQ0NSA2OC44MiwxMDUuNjY1IDY5LjY1NywxMDYuMTQ4IEwxMTIuMTMsMTMwLjY3IEMxMTIuNDc0LDEzMC44NjggMTEyLjc5MSwxMzAuOTEzIDExMywxMzAuNzkyIEMxMTMuMjA2LDEzMC42NzMgMTEzLjMyNSwxMzAuMzgxIDExMy4zMjUsMTI5Ljk5MyBMMTEzLjMyNSw3NS45OTIgQzExMy4zMjUsNzUuNzk4IDExMy40ODIsNzUuNjQxIDExMy42NzUsNzUuNjQxIEMxMTMuODY5LDc1LjY0MSAxMTQuMDI1LDc1Ljc5OCAxMTQuMDI1LDc1Ljk5MiBMMTE0LjAyNSwxMjkuOTkzIEMxMTQuMDI1LDEzMC42NDggMTEzLjc4NiwxMzEuMTQ3IDExMy4zNSwxMzEuMzk5IEMxMTMuMTYyLDEzMS41MDcgMTEyLjk1MiwxMzEuNTYxIDExMi43MjcsMTMxLjU2MSIgaWQ9IkZpbGwtMjkiIGZpbGw9IiM0NTVBNjQiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTEyLjg2LDQwLjUxMiBDMTEyLjg2LDQwLjUxMiAxMTIuODYsNDAuNTEyIDExMi44NTksNDAuNTEyIEMxMTAuNTQxLDQwLjUxMiAxMDguMzYsMzkuOTkgMTA2LjcxNywzOS4wNDEgQzEwNS4wMTIsMzguMDU3IDEwNC4wNzQsMzYuNzI2IDEwNC4wNzQsMzUuMjkyIEMxMDQuMDc0LDMzLjg0NyAxMDUuMDI2LDMyLjUwMSAxMDYuNzU0LDMxLjUwNCBMMTE4Ljc5NSwyNC41NTEgQzEyMC40NjMsMjMuNTg5IDEyMi42NjksMjMuMDU4IDEyNS4wMDcsMjMuMDU4IEMxMjcuMzI1LDIzLjA1OCAxMjkuNTA2LDIzLjU4MSAxMzEuMTUsMjQuNTMgQzEzMi44NTQsMjUuNTE0IDEzMy43OTMsMjYuODQ1IDEzMy43OTMsMjguMjc4IEMxMzMuNzkzLDI5LjcyNCAxMzIuODQxLDMxLjA2OSAxMzEuMTEzLDMyLjA2NyBMMTE5LjA3MSwzOS4wMTkgQzExNy40MDMsMzkuOTgyIDExNS4xOTcsNDAuNTEyIDExMi44Niw0MC41MTIgTDExMi44Niw0MC41MTIgWiBNMTI1LjAwNywyMy43NTkgQzEyMi43OSwyMy43NTkgMTIwLjcwOSwyNC4yNTYgMTE5LjE0NiwyNS4xNTggTDEwNy4xMDQsMzIuMTEgQzEwNS42MDIsMzIuOTc4IDEwNC43NzQsMzQuMTA4IDEwNC43NzQsMzUuMjkyIEMxMDQuNzc0LDM2LjQ2NSAxMDUuNTg5LDM3LjU4MSAxMDcuMDY3LDM4LjQzNCBDMTA4LjYwNSwzOS4zMjMgMTEwLjY2MywzOS44MTIgMTEyLjg1OSwzOS44MTIgTDExMi44NiwzOS44MTIgQzExNS4wNzYsMzkuODEyIDExNy4xNTgsMzkuMzE1IDExOC43MjEsMzguNDEzIEwxMzAuNzYyLDMxLjQ2IEMxMzIuMjY0LDMwLjU5MyAxMzMuMDkyLDI5LjQ2MyAxMzMuMDkyLDI4LjI3OCBDMTMzLjA5MiwyNy4xMDYgMTMyLjI3OCwyNS45OSAxMzAuOCwyNS4xMzYgQzEyOS4yNjEsMjQuMjQ4IDEyNy4yMDQsMjMuNzU5IDEyNS4wMDcsMjMuNzU5IEwxMjUuMDA3LDIzLjc1OSBaIiBpZD0iRmlsbC0zMCIgZmlsbD0iIzYwN0Q4QiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xNjUuNjMsMTYuMjE5IEwxNTkuODk2LDE5LjUzIEMxNTYuNzI5LDIxLjM1OCAxNTEuNjEsMjEuMzY3IDE0OC40NjMsMTkuNTUgQzE0NS4zMTYsMTcuNzMzIDE0NS4zMzIsMTQuNzc4IDE0OC40OTksMTIuOTQ5IEwxNTQuMjMzLDkuNjM5IEwxNjUuNjMsMTYuMjE5IiBpZD0iRmlsbC0zMSIgZmlsbD0iI0ZBRkFGQSI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xNTQuMjMzLDEwLjQ0OCBMMTY0LjIyOCwxNi4yMTkgTDE1OS41NDYsMTguOTIzIEMxNTguMTEyLDE5Ljc1IDE1Ni4xOTQsMjAuMjA2IDE1NC4xNDcsMjAuMjA2IEMxNTIuMTE4LDIwLjIwNiAxNTAuMjI0LDE5Ljc1NyAxNDguODE0LDE4Ljk0MyBDMTQ3LjUyNCwxOC4xOTkgMTQ2LjgxNCwxNy4yNDkgMTQ2LjgxNCwxNi4yNjkgQzE0Ni44MTQsMTUuMjc4IDE0Ny41MzcsMTQuMzE0IDE0OC44NSwxMy41NTYgTDE1NC4yMzMsMTAuNDQ4IE0xNTQuMjMzLDkuNjM5IEwxNDguNDk5LDEyLjk0OSBDMTQ1LjMzMiwxNC43NzggMTQ1LjMxNiwxNy43MzMgMTQ4LjQ2MywxOS41NSBDMTUwLjAzMSwyMC40NTUgMTUyLjA4NiwyMC45MDcgMTU0LjE0NywyMC45MDcgQzE1Ni4yMjQsMjAuOTA3IDE1OC4zMDYsMjAuNDQ3IDE1OS44OTYsMTkuNTMgTDE2NS42MywxNi4yMTkgTDE1NC4yMzMsOS42MzkiIGlkPSJGaWxsLTMyIiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTE0NS40NDUsNzIuNjY3IEwxNDUuNDQ1LDcyLjY2NyBDMTQzLjY3Miw3Mi42NjcgMTQyLjIwNCw3MS44MTcgMTQxLjIwMiw3MC40MjIgQzE0MS4xMzUsNzAuMzMgMTQxLjE0NSw3MC4xNDcgMTQxLjIyNSw3MC4wNjYgQzE0MS4zMDUsNjkuOTg1IDE0MS40MzIsNjkuOTQ2IDE0MS41MjUsNzAuMDExIEMxNDIuMzA2LDcwLjU1OSAxNDMuMjMxLDcwLjgyMyAxNDQuMjc2LDcwLjgyMiBDMTQ1LjU5OCw3MC44MjIgMTQ3LjAzLDcwLjM3NiAxNDguNTMyLDY5LjUwOSBDMTUzLjg0Miw2Ni40NDMgMTU4LjE2Myw1OC45ODcgMTU4LjE2Myw1Mi44OTQgQzE1OC4xNjMsNTAuOTY3IDE1Ny43MjEsNDkuMzMyIDE1Ni44ODQsNDguMTY4IEMxNTYuODE4LDQ4LjA3NiAxNTYuODI4LDQ3Ljk0OCAxNTYuOTA4LDQ3Ljg2NyBDMTU2Ljk4OCw0Ny43ODYgMTU3LjExNCw0Ny43NzQgMTU3LjIwOCw0Ny44NCBDMTU4Ljg3OCw0OS4wMTIgMTU5Ljc5OCw1MS4yMiAxNTkuNzk4LDU0LjA1OSBDMTU5Ljc5OCw2MC4zMDEgMTU1LjM3Myw2OC4wNDYgMTQ5LjkzMyw3MS4xODYgQzE0OC4zNiw3Mi4wOTQgMTQ2Ljg1LDcyLjY2NyAxNDUuNDQ1LDcyLjY2NyBMMTQ1LjQ0NSw3Mi42NjcgWiBNMTQyLjQ3Niw3MSBDMTQzLjI5LDcxLjY1MSAxNDQuMjk2LDcyLjAwMiAxNDUuNDQ1LDcyLjAwMiBDMTQ2Ljc2Nyw3Mi4wMDIgMTQ4LjE5OCw3MS41NSAxNDkuNyw3MC42ODIgQzE1NS4wMSw2Ny42MTcgMTU5LjMzMSw2MC4xNTkgMTU5LjMzMSw1NC4wNjUgQzE1OS4zMzEsNTIuMDg1IDE1OC44NjgsNTAuNDM1IDE1OC4wMDYsNDkuMjcyIEMxNTguNDE3LDUwLjMwNyAxNTguNjMsNTEuNTMyIDE1OC42Myw1Mi44OTIgQzE1OC42Myw1OS4xMzQgMTU0LjIwNSw2Ni43NjcgMTQ4Ljc2NSw2OS45MDcgQzE0Ny4xOTIsNzAuODE2IDE0NS42ODEsNzEuMjgzIDE0NC4yNzYsNzEuMjgzIEMxNDMuNjM0LDcxLjI4MyAxNDMuMDMzLDcxLjE5MiAxNDIuNDc2LDcxIEwxNDIuNDc2LDcxIFoiIGlkPSJGaWxsLTMzIiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTE0OC42NDgsNjkuNzA0IEMxNTQuMDMyLDY2LjU5NiAxNTguMzk2LDU5LjA2OCAxNTguMzk2LDUyLjg5MSBDMTU4LjM5Niw1MC44MzkgMTU3LjkxMyw0OS4xOTggMTU3LjA3NCw0OC4wMyBDMTU1LjI4OSw0Ni43NzggMTUyLjY5OSw0Ni44MzYgMTQ5LjgxNiw0OC41MDEgQzE0NC40MzMsNTEuNjA5IDE0MC4wNjgsNTkuMTM3IDE0MC4wNjgsNjUuMzE0IEMxNDAuMDY4LDY3LjM2NSAxNDAuNTUyLDY5LjAwNiAxNDEuMzkxLDcwLjE3NCBDMTQzLjE3Niw3MS40MjcgMTQ1Ljc2NSw3MS4zNjkgMTQ4LjY0OCw2OS43MDQiIGlkPSJGaWxsLTM0IiBmaWxsPSIjRkFGQUZBIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTE0NC4yNzYsNzEuMjc2IEwxNDQuMjc2LDcxLjI3NiBDMTQzLjEzMyw3MS4yNzYgMTQyLjExOCw3MC45NjkgMTQxLjI1Nyw3MC4zNjUgQzE0MS4yMzYsNzAuMzUxIDE0MS4yMTcsNzAuMzMyIDE0MS4yMDIsNzAuMzExIEMxNDAuMzA3LDY5LjA2NyAxMzkuODM1LDY3LjMzOSAxMzkuODM1LDY1LjMxNCBDMTM5LjgzNSw1OS4wNzMgMTQ0LjI2LDUxLjQzOSAxNDkuNyw0OC4yOTggQzE1MS4yNzMsNDcuMzkgMTUyLjc4NCw0Ni45MjkgMTU0LjE4OSw0Ni45MjkgQzE1NS4zMzIsNDYuOTI5IDE1Ni4zNDcsNDcuMjM2IDE1Ny4yMDgsNDcuODM5IEMxNTcuMjI5LDQ3Ljg1NCAxNTcuMjQ4LDQ3Ljg3MyAxNTcuMjYzLDQ3Ljg5NCBDMTU4LjE1Nyw0OS4xMzggMTU4LjYzLDUwLjg2NSAxNTguNjMsNTIuODkxIEMxNTguNjMsNTkuMTMyIDE1NC4yMDUsNjYuNzY2IDE0OC43NjUsNjkuOTA3IEMxNDcuMTkyLDcwLjgxNSAxNDUuNjgxLDcxLjI3NiAxNDQuMjc2LDcxLjI3NiBMMTQ0LjI3Niw3MS4yNzYgWiBNMTQxLjU1OCw3MC4xMDQgQzE0Mi4zMzEsNzAuNjM3IDE0My4yNDUsNzEuMDA1IDE0NC4yNzYsNzEuMDA1IEMxNDUuNTk4LDcxLjAwNSAxNDcuMDMsNzAuNDY3IDE0OC41MzIsNjkuNiBDMTUzLjg0Miw2Ni41MzQgMTU4LjE2Myw1OS4wMzMgMTU4LjE2Myw1Mi45MzkgQzE1OC4xNjMsNTEuMDMxIDE1Ny43MjksNDkuMzg1IDE1Ni45MDcsNDguMjIzIEMxNTYuMTMzLDQ3LjY5MSAxNTUuMjE5LDQ3LjQwOSAxNTQuMTg5LDQ3LjQwOSBDMTUyLjg2Nyw0Ny40MDkgMTUxLjQzNSw0Ny44NDIgMTQ5LjkzMyw0OC43MDkgQzE0NC42MjMsNTEuNzc1IDE0MC4zMDIsNTkuMjczIDE0MC4zMDIsNjUuMzY2IEMxNDAuMzAyLDY3LjI3NiAxNDAuNzM2LDY4Ljk0MiAxNDEuNTU4LDcwLjEwNCBMMTQxLjU1OCw3MC4xMDQgWiIgaWQ9IkZpbGwtMzUiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTUwLjcyLDY1LjM2MSBMMTUwLjM1Nyw2NS4wNjYgQzE1MS4xNDcsNjQuMDkyIDE1MS44NjksNjMuMDQgMTUyLjUwNSw2MS45MzggQzE1My4zMTMsNjAuNTM5IDE1My45NzgsNTkuMDY3IDE1NC40ODIsNTcuNTYzIEwxNTQuOTI1LDU3LjcxMiBDMTU0LjQxMiw1OS4yNDUgMTUzLjczMyw2MC43NDUgMTUyLjkxLDYyLjE3MiBDMTUyLjI2Miw2My4yOTUgMTUxLjUyNSw2NC4zNjggMTUwLjcyLDY1LjM2MSIgaWQ9IkZpbGwtMzYiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTE1LjkxNyw4NC41MTQgTDExNS41NTQsODQuMjIgQzExNi4zNDQsODMuMjQ1IDExNy4wNjYsODIuMTk0IDExNy43MDIsODEuMDkyIEMxMTguNTEsNzkuNjkyIDExOS4xNzUsNzguMjIgMTE5LjY3OCw3Ni43MTcgTDEyMC4xMjEsNzYuODY1IEMxMTkuNjA4LDc4LjM5OCAxMTguOTMsNzkuODk5IDExOC4xMDYsODEuMzI2IEMxMTcuNDU4LDgyLjQ0OCAxMTYuNzIyLDgzLjUyMSAxMTUuOTE3LDg0LjUxNCIgaWQ9IkZpbGwtMzciIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTE0LDEzMC40NzYgTDExNCwxMzAuMDA4IEwxMTQsNzYuMDUyIEwxMTQsNzUuNTg0IEwxMTQsNzYuMDUyIEwxMTQsMTMwLjAwOCBMMTE0LDEzMC40NzYiIGlkPSJGaWxsLTM4IiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICA8L2c+CiAgICAgICAgICAgICAgICA8ZyBpZD0iSW1wb3J0ZWQtTGF5ZXJzLUNvcHkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDYyLjAwMDAwMCwgMC4wMDAwMDApIiBza2V0Y2g6dHlwZT0iTVNTaGFwZUdyb3VwIj4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTkuODIyLDM3LjQ3NCBDMTkuODM5LDM3LjMzOSAxOS43NDcsMzcuMTk0IDE5LjU1NSwzNy4wODIgQzE5LjIyOCwzNi44OTQgMTguNzI5LDM2Ljg3MiAxOC40NDYsMzcuMDM3IEwxMi40MzQsNDAuNTA4IEMxMi4zMDMsNDAuNTg0IDEyLjI0LDQwLjY4NiAxMi4yNDMsNDAuNzkzIEMxMi4yNDUsNDAuOTI1IDEyLjI0NSw0MS4yNTQgMTIuMjQ1LDQxLjM3MSBMMTIuMjQ1LDQxLjQxNCBMMTIuMjM4LDQxLjU0MiBDOC4xNDgsNDMuODg3IDUuNjQ3LDQ1LjMyMSA1LjY0Nyw0NS4zMjEgQzUuNjQ2LDQ1LjMyMSAzLjU3LDQ2LjM2NyAyLjg2LDUwLjUxMyBDMi44Niw1MC41MTMgMS45NDgsNTcuNDc0IDEuOTYyLDcwLjI1OCBDMS45NzcsODIuODI4IDIuNTY4LDg3LjMyOCAzLjEyOSw5MS42MDkgQzMuMzQ5LDkzLjI5MyA2LjEzLDkzLjczNCA2LjEzLDkzLjczNCBDNi40NjEsOTMuNzc0IDYuODI4LDkzLjcwNyA3LjIxLDkzLjQ4NiBMODIuNDgzLDQ5LjkzNSBDODQuMjkxLDQ4Ljg2NiA4NS4xNSw0Ni4yMTYgODUuNTM5LDQzLjY1MSBDODYuNzUyLDM1LjY2MSA4Ny4yMTQsMTAuNjczIDg1LjI2NCwzLjc3MyBDODUuMDY4LDMuMDggODQuNzU0LDIuNjkgODQuMzk2LDIuNDkxIEw4Mi4zMSwxLjcwMSBDODEuNTgzLDEuNzI5IDgwLjg5NCwyLjE2OCA4MC43NzYsMi4yMzYgQzgwLjYzNiwyLjMxNyA0MS44MDcsMjQuNTg1IDIwLjAzMiwzNy4wNzIgTDE5LjgyMiwzNy40NzQiIGlkPSJGaWxsLTEiIGZpbGw9IiNGRkZGRkYiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNODIuMzExLDEuNzAxIEw4NC4zOTYsMi40OTEgQzg0Ljc1NCwyLjY5IDg1LjA2OCwzLjA4IDg1LjI2NCwzLjc3MyBDODcuMjEzLDEwLjY3MyA4Ni43NTEsMzUuNjYgODUuNTM5LDQzLjY1MSBDODUuMTQ5LDQ2LjIxNiA4NC4yOSw0OC44NjYgODIuNDgzLDQ5LjkzNSBMNy4yMSw5My40ODYgQzYuODk3LDkzLjY2NyA2LjU5NSw5My43NDQgNi4zMTQsOTMuNzQ0IEw2LjEzMSw5My43MzMgQzYuMTMxLDkzLjczNCAzLjM0OSw5My4yOTMgMy4xMjgsOTEuNjA5IEMyLjU2OCw4Ny4zMjcgMS45NzcsODIuODI4IDEuOTYzLDcwLjI1OCBDMS45NDgsNTcuNDc0IDIuODYsNTAuNTEzIDIuODYsNTAuNTEzIEMzLjU3LDQ2LjM2NyA1LjY0Nyw0NS4zMjEgNS42NDcsNDUuMzIxIEM1LjY0Nyw0NS4zMjEgOC4xNDgsNDMuODg3IDEyLjIzOCw0MS41NDIgTDEyLjI0NSw0MS40MTQgTDEyLjI0NSw0MS4zNzEgQzEyLjI0NSw0MS4yNTQgMTIuMjQ1LDQwLjkyNSAxMi4yNDMsNDAuNzkzIEMxMi4yNCw0MC42ODYgMTIuMzAyLDQwLjU4MyAxMi40MzQsNDAuNTA4IEwxOC40NDYsMzcuMDM2IEMxOC41NzQsMzYuOTYyIDE4Ljc0NiwzNi45MjYgMTguOTI3LDM2LjkyNiBDMTkuMTQ1LDM2LjkyNiAxOS4zNzYsMzYuOTc5IDE5LjU1NCwzNy4wODIgQzE5Ljc0NywzNy4xOTQgMTkuODM5LDM3LjM0IDE5LjgyMiwzNy40NzQgTDIwLjAzMywzNy4wNzIgQzQxLjgwNiwyNC41ODUgODAuNjM2LDIuMzE4IDgwLjc3NywyLjIzNiBDODAuODk0LDIuMTY4IDgxLjU4MywxLjcyOSA4Mi4zMTEsMS43MDEgTTgyLjMxMSwwLjcwNCBMODIuMjcyLDAuNzA1IEM4MS42NTQsMC43MjggODAuOTg5LDAuOTQ5IDgwLjI5OCwxLjM2MSBMODAuMjc3LDEuMzczIEM4MC4xMjksMS40NTggNTkuNzY4LDEzLjEzNSAxOS43NTgsMzYuMDc5IEMxOS41LDM1Ljk4MSAxOS4yMTQsMzUuOTI5IDE4LjkyNywzNS45MjkgQzE4LjU2MiwzNS45MjkgMTguMjIzLDM2LjAxMyAxNy45NDcsMzYuMTczIEwxMS45MzUsMzkuNjQ0IEMxMS40OTMsMzkuODk5IDExLjIzNiw0MC4zMzQgMTEuMjQ2LDQwLjgxIEwxMS4yNDcsNDAuOTYgTDUuMTY3LDQ0LjQ0NyBDNC43OTQsNDQuNjQ2IDIuNjI1LDQ1Ljk3OCAxLjg3Nyw1MC4zNDUgTDEuODcxLDUwLjM4NCBDMS44NjIsNTAuNDU0IDAuOTUxLDU3LjU1NyAwLjk2NSw3MC4yNTkgQzAuOTc5LDgyLjg3OSAxLjU2OCw4Ny4zNzUgMi4xMzcsOTEuNzI0IEwyLjEzOSw5MS43MzkgQzIuNDQ3LDk0LjA5NCA1LjYxNCw5NC42NjIgNS45NzUsOTQuNzE5IEw2LjAwOSw5NC43MjMgQzYuMTEsOTQuNzM2IDYuMjEzLDk0Ljc0MiA2LjMxNCw5NC43NDIgQzYuNzksOTQuNzQyIDcuMjYsOTQuNjEgNy43MSw5NC4zNSBMODIuOTgzLDUwLjc5OCBDODQuNzk0LDQ5LjcyNyA4NS45ODIsNDcuMzc1IDg2LjUyNSw0My44MDEgQzg3LjcxMSwzNS45ODcgODguMjU5LDEwLjcwNSA4Ni4yMjQsMy41MDIgQzg1Ljk3MSwyLjYwOSA4NS41MiwxLjk3NSA4NC44ODEsMS42MiBMODQuNzQ5LDEuNTU4IEw4Mi42NjQsMC43NjkgQzgyLjU1MSwwLjcyNSA4Mi40MzEsMC43MDQgODIuMzExLDAuNzA0IiBpZD0iRmlsbC0yIiBmaWxsPSIjNDU1QTY0Ij48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTY2LjI2NywxMS41NjUgTDY3Ljc2MiwxMS45OTkgTDExLjQyMyw0NC4zMjUiIGlkPSJGaWxsLTMiIGZpbGw9IiNGRkZGRkYiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTIuMjAyLDkwLjU0NSBDMTIuMDI5LDkwLjU0NSAxMS44NjIsOTAuNDU1IDExLjc2OSw5MC4yOTUgQzExLjYzMiw5MC4wNTcgMTEuNzEzLDg5Ljc1MiAxMS45NTIsODkuNjE0IEwzMC4zODksNzguOTY5IEMzMC42MjgsNzguODMxIDMwLjkzMyw3OC45MTMgMzEuMDcxLDc5LjE1MiBDMzEuMjA4LDc5LjM5IDMxLjEyNyw3OS42OTYgMzAuODg4LDc5LjgzMyBMMTIuNDUxLDkwLjQ3OCBMMTIuMjAyLDkwLjU0NSIgaWQ9IkZpbGwtNCIgZmlsbD0iIzYwN0Q4QiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xMy43NjQsNDIuNjU0IEwxMy42NTYsNDIuNTkyIEwxMy43MDIsNDIuNDIxIEwxOC44MzcsMzkuNDU3IEwxOS4wMDcsMzkuNTAyIEwxOC45NjIsMzkuNjczIEwxMy44MjcsNDIuNjM3IEwxMy43NjQsNDIuNjU0IiBpZD0iRmlsbC01IiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTguNTIsOTAuMzc1IEw4LjUyLDQ2LjQyMSBMOC41ODMsNDYuMzg1IEw3NS44NCw3LjU1NCBMNzUuODQsNTEuNTA4IEw3NS43NzgsNTEuNTQ0IEw4LjUyLDkwLjM3NSBMOC41Miw5MC4zNzUgWiBNOC43Nyw0Ni41NjQgTDguNzcsODkuOTQ0IEw3NS41OTEsNTEuMzY1IEw3NS41OTEsNy45ODUgTDguNzcsNDYuNTY0IEw4Ljc3LDQ2LjU2NCBaIiBpZD0iRmlsbC02IiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTI0Ljk4Niw4My4xODIgQzI0Ljc1Niw4My4zMzEgMjQuMzc0LDgzLjU2NiAyNC4xMzcsODMuNzA1IEwxMi42MzIsOTAuNDA2IEMxMi4zOTUsOTAuNTQ1IDEyLjQyNiw5MC42NTggMTIuNyw5MC42NTggTDEzLjI2NSw5MC42NTggQzEzLjU0LDkwLjY1OCAxMy45NTgsOTAuNTQ1IDE0LjE5NSw5MC40MDYgTDI1LjcsODMuNzA1IEMyNS45MzcsODMuNTY2IDI2LjEyOCw4My40NTIgMjYuMTI1LDgzLjQ0OSBDMjYuMTIyLDgzLjQ0NyAyNi4xMTksODMuMjIgMjYuMTE5LDgyLjk0NiBDMjYuMTE5LDgyLjY3MiAyNS45MzEsODIuNTY5IDI1LjcwMSw4Mi43MTkgTDI0Ljk4Niw4My4xODIiIGlkPSJGaWxsLTciIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTMuMjY2LDkwLjc4MiBMMTIuNyw5MC43ODIgQzEyLjUsOTAuNzgyIDEyLjM4NCw5MC43MjYgMTIuMzU0LDkwLjYxNiBDMTIuMzI0LDkwLjUwNiAxMi4zOTcsOTAuMzk5IDEyLjU2OSw5MC4yOTkgTDI0LjA3NCw4My41OTcgQzI0LjMxLDgzLjQ1OSAyNC42ODksODMuMjI2IDI0LjkxOCw4My4wNzggTDI1LjYzMyw4Mi42MTQgQzI1LjcyMyw4Mi41NTUgMjUuODEzLDgyLjUyNSAyNS44OTksODIuNTI1IEMyNi4wNzEsODIuNTI1IDI2LjI0NCw4Mi42NTUgMjYuMjQ0LDgyLjk0NiBDMjYuMjQ0LDgzLjE2IDI2LjI0NSw4My4zMDkgMjYuMjQ3LDgzLjM4MyBMMjYuMjUzLDgzLjM4NyBMMjYuMjQ5LDgzLjQ1NiBDMjYuMjQ2LDgzLjUzMSAyNi4yNDYsODMuNTMxIDI1Ljc2Myw4My44MTIgTDE0LjI1OCw5MC41MTQgQzE0LDkwLjY2NSAxMy41NjQsOTAuNzgyIDEzLjI2Niw5MC43ODIgTDEzLjI2Niw5MC43ODIgWiBNMTIuNjY2LDkwLjUzMiBMMTIuNyw5MC41MzMgTDEzLjI2Niw5MC41MzMgQzEzLjUxOCw5MC41MzMgMTMuOTE1LDkwLjQyNSAxNC4xMzIsOTAuMjk5IEwyNS42MzcsODMuNTk3IEMyNS44MDUsODMuNDk5IDI1LjkzMSw4My40MjQgMjUuOTk4LDgzLjM4MyBDMjUuOTk0LDgzLjI5OSAyNS45OTQsODMuMTY1IDI1Ljk5NCw4Mi45NDYgTDI1Ljg5OSw4Mi43NzUgTDI1Ljc2OCw4Mi44MjQgTDI1LjA1NCw4My4yODcgQzI0LjgyMiw4My40MzcgMjQuNDM4LDgzLjY3MyAyNC4yLDgzLjgxMiBMMTIuNjk1LDkwLjUxNCBMMTIuNjY2LDkwLjUzMiBMMTIuNjY2LDkwLjUzMiBaIiBpZD0iRmlsbC04IiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTEzLjI2Niw4OS44NzEgTDEyLjcsODkuODcxIEMxMi41LDg5Ljg3MSAxMi4zODQsODkuODE1IDEyLjM1NCw4OS43MDUgQzEyLjMyNCw4OS41OTUgMTIuMzk3LDg5LjQ4OCAxMi41NjksODkuMzg4IEwyNC4wNzQsODIuNjg2IEMyNC4zMzIsODIuNTM1IDI0Ljc2OCw4Mi40MTggMjUuMDY3LDgyLjQxOCBMMjUuNjMyLDgyLjQxOCBDMjUuODMyLDgyLjQxOCAyNS45NDgsODIuNDc0IDI1Ljk3OCw4Mi41ODQgQzI2LjAwOCw4Mi42OTQgMjUuOTM1LDgyLjgwMSAyNS43NjMsODIuOTAxIEwxNC4yNTgsODkuNjAzIEMxNCw4OS43NTQgMTMuNTY0LDg5Ljg3MSAxMy4yNjYsODkuODcxIEwxMy4yNjYsODkuODcxIFogTTEyLjY2Niw4OS42MjEgTDEyLjcsODkuNjIyIEwxMy4yNjYsODkuNjIyIEMxMy41MTgsODkuNjIyIDEzLjkxNSw4OS41MTUgMTQuMTMyLDg5LjM4OCBMMjUuNjM3LDgyLjY4NiBMMjUuNjY3LDgyLjY2OCBMMjUuNjMyLDgyLjY2NyBMMjUuMDY3LDgyLjY2NyBDMjQuODE1LDgyLjY2NyAyNC40MTgsODIuNzc1IDI0LjIsODIuOTAxIEwxMi42OTUsODkuNjAzIEwxMi42NjYsODkuNjIxIEwxMi42NjYsODkuNjIxIFoiIGlkPSJGaWxsLTkiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTIuMzcsOTAuODAxIEwxMi4zNyw4OS41NTQgTDEyLjM3LDkwLjgwMSIgaWQ9IkZpbGwtMTAiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNNi4xMyw5My45MDEgQzUuMzc5LDkzLjgwOCA0LjgxNiw5My4xNjQgNC42OTEsOTIuNTI1IEMzLjg2LDg4LjI4NyAzLjU0LDgzLjc0MyAzLjUyNiw3MS4xNzMgQzMuNTExLDU4LjM4OSA0LjQyMyw1MS40MjggNC40MjMsNTEuNDI4IEM1LjEzNCw0Ny4yODIgNy4yMSw0Ni4yMzYgNy4yMSw0Ni4yMzYgQzcuMjEsNDYuMjM2IDgxLjY2NywzLjI1IDgyLjA2OSwzLjAxNyBDODIuMjkyLDIuODg4IDg0LjU1NiwxLjQzMyA4NS4yNjQsMy45NCBDODcuMjE0LDEwLjg0IDg2Ljc1MiwzNS44MjcgODUuNTM5LDQzLjgxOCBDODUuMTUsNDYuMzgzIDg0LjI5MSw0OS4wMzMgODIuNDgzLDUwLjEwMSBMNy4yMSw5My42NTMgQzYuODI4LDkzLjg3NCA2LjQ2MSw5My45NDEgNi4xMyw5My45MDEgQzYuMTMsOTMuOTAxIDMuMzQ5LDkzLjQ2IDMuMTI5LDkxLjc3NiBDMi41NjgsODcuNDk1IDEuOTc3LDgyLjk5NSAxLjk2Miw3MC40MjUgQzEuOTQ4LDU3LjY0MSAyLjg2LDUwLjY4IDIuODYsNTAuNjggQzMuNTcsNDYuNTM0IDUuNjQ3LDQ1LjQ4OSA1LjY0Nyw0NS40ODkgQzUuNjQ2LDQ1LjQ4OSA4LjA2NSw0NC4wOTIgMTIuMjQ1LDQxLjY3OSBMMTMuMTE2LDQxLjU2IEwxOS43MTUsMzcuNzMgTDE5Ljc2MSwzNy4yNjkgTDYuMTMsOTMuOTAxIiBpZD0iRmlsbC0xMSIgZmlsbD0iI0ZBRkFGQSI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik02LjMxNyw5NC4xNjEgTDYuMTAyLDk0LjE0OCBMNi4xMDEsOTQuMTQ4IEw1Ljg1Nyw5NC4xMDEgQzUuMTM4LDkzLjk0NSAzLjA4NSw5My4zNjUgMi44ODEsOTEuODA5IEMyLjMxMyw4Ny40NjkgMS43MjcsODIuOTk2IDEuNzEzLDcwLjQyNSBDMS42OTksNTcuNzcxIDIuNjA0LDUwLjcxOCAyLjYxMyw1MC42NDggQzMuMzM4LDQ2LjQxNyA1LjQ0NSw0NS4zMSA1LjUzNSw0NS4yNjYgTDEyLjE2Myw0MS40MzkgTDEzLjAzMyw0MS4zMiBMMTkuNDc5LDM3LjU3OCBMMTkuNTEzLDM3LjI0NCBDMTkuNTI2LDM3LjEwNyAxOS42NDcsMzcuMDA4IDE5Ljc4NiwzNy4wMjEgQzE5LjkyMiwzNy4wMzQgMjAuMDIzLDM3LjE1NiAyMC4wMDksMzcuMjkzIEwxOS45NSwzNy44ODIgTDEzLjE5OCw0MS44MDEgTDEyLjMyOCw0MS45MTkgTDUuNzcyLDQ1LjcwNCBDNS43NDEsNDUuNzIgMy43ODIsNDYuNzcyIDMuMTA2LDUwLjcyMiBDMy4wOTksNTAuNzgyIDIuMTk4LDU3LjgwOCAyLjIxMiw3MC40MjQgQzIuMjI2LDgyLjk2MyAyLjgwOSw4Ny40MiAzLjM3Myw5MS43MjkgQzMuNDY0LDkyLjQyIDQuMDYyLDkyLjg4MyA0LjY4Miw5My4xODEgQzQuNTY2LDkyLjk4NCA0LjQ4Niw5Mi43NzYgNC40NDYsOTIuNTcyIEMzLjY2NSw4OC41ODggMy4yOTEsODQuMzcgMy4yNzYsNzEuMTczIEMzLjI2Miw1OC41MiA0LjE2Nyw1MS40NjYgNC4xNzYsNTEuMzk2IEM0LjkwMSw0Ny4xNjUgNy4wMDgsNDYuMDU5IDcuMDk4LDQ2LjAxNCBDNy4wOTQsNDYuMDE1IDgxLjU0MiwzLjAzNCA4MS45NDQsMi44MDIgTDgxLjk3MiwyLjc4NSBDODIuODc2LDIuMjQ3IDgzLjY5MiwyLjA5NyA4NC4zMzIsMi4zNTIgQzg0Ljg4NywyLjU3MyA4NS4yODEsMy4wODUgODUuNTA0LDMuODcyIEM4Ny41MTgsMTEgODYuOTY0LDM2LjA5MSA4NS43ODUsNDMuODU1IEM4NS4yNzgsNDcuMTk2IDg0LjIxLDQ5LjM3IDgyLjYxLDUwLjMxNyBMNy4zMzUsOTMuODY5IEM2Ljk5OSw5NC4wNjMgNi42NTgsOTQuMTYxIDYuMzE3LDk0LjE2MSBMNi4zMTcsOTQuMTYxIFogTTYuMTcsOTMuNjU0IEM2LjQ2Myw5My42OSA2Ljc3NCw5My42MTcgNy4wODUsOTMuNDM3IEw4Mi4zNTgsNDkuODg2IEM4NC4xODEsNDguODA4IDg0Ljk2LDQ1Ljk3MSA4NS4yOTIsNDMuNzggQzg2LjQ2NiwzNi4wNDkgODcuMDIzLDExLjA4NSA4NS4wMjQsNC4wMDggQzg0Ljg0NiwzLjM3NyA4NC41NTEsMi45NzYgODQuMTQ4LDIuODE2IEM4My42NjQsMi42MjMgODIuOTgyLDIuNzY0IDgyLjIyNywzLjIxMyBMODIuMTkzLDMuMjM0IEM4MS43OTEsMy40NjYgNy4zMzUsNDYuNDUyIDcuMzM1LDQ2LjQ1MiBDNy4zMDQsNDYuNDY5IDUuMzQ2LDQ3LjUyMSA0LjY2OSw1MS40NzEgQzQuNjYyLDUxLjUzIDMuNzYxLDU4LjU1NiAzLjc3NSw3MS4xNzMgQzMuNzksODQuMzI4IDQuMTYxLDg4LjUyNCA0LjkzNiw5Mi40NzYgQzUuMDI2LDkyLjkzNyA1LjQxMiw5My40NTkgNS45NzMsOTMuNjE1IEM2LjA4Nyw5My42NCA2LjE1OCw5My42NTIgNi4xNjksOTMuNjU0IEw2LjE3LDkzLjY1NCBMNi4xNyw5My42NTQgWiIgaWQ9IkZpbGwtMTIiIGZpbGw9IiM0NTVBNjQiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNNy4zMTcsNjguOTgyIEM3LjgwNiw2OC43MDEgOC4yMDIsNjguOTI2IDguMjAyLDY5LjQ4NyBDOC4yMDIsNzAuMDQ3IDcuODA2LDcwLjczIDcuMzE3LDcxLjAxMiBDNi44MjksNzEuMjk0IDYuNDMzLDcxLjA2OSA2LjQzMyw3MC41MDggQzYuNDMzLDY5Ljk0OCA2LjgyOSw2OS4yNjUgNy4zMTcsNjguOTgyIiBpZD0iRmlsbC0xMyIgZmlsbD0iI0ZGRkZGRiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik02LjkyLDcxLjEzMyBDNi42MzEsNzEuMTMzIDYuNDMzLDcwLjkwNSA2LjQzMyw3MC41MDggQzYuNDMzLDY5Ljk0OCA2LjgyOSw2OS4yNjUgNy4zMTcsNjguOTgyIEM3LjQ2LDY4LjkgNy41OTUsNjguODYxIDcuNzE0LDY4Ljg2MSBDOC4wMDMsNjguODYxIDguMjAyLDY5LjA5IDguMjAyLDY5LjQ4NyBDOC4yMDIsNzAuMDQ3IDcuODA2LDcwLjczIDcuMzE3LDcxLjAxMiBDNy4xNzQsNzEuMDk0IDcuMDM5LDcxLjEzMyA2LjkyLDcxLjEzMyBNNy43MTQsNjguNjc0IEM3LjU1Nyw2OC42NzQgNy4zOTIsNjguNzIzIDcuMjI0LDY4LjgyMSBDNi42NzYsNjkuMTM4IDYuMjQ2LDY5Ljg3OSA2LjI0Niw3MC41MDggQzYuMjQ2LDcwLjk5NCA2LjUxNyw3MS4zMiA2LjkyLDcxLjMyIEM3LjA3OCw3MS4zMiA3LjI0Myw3MS4yNzEgNy40MTEsNzEuMTc0IEM3Ljk1OSw3MC44NTcgOC4zODksNzAuMTE3IDguMzg5LDY5LjQ4NyBDOC4zODksNjkuMDAxIDguMTE3LDY4LjY3NCA3LjcxNCw2OC42NzQiIGlkPSJGaWxsLTE0IiBmaWxsPSIjODA5N0EyIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTYuOTIsNzAuOTQ3IEM2LjY0OSw3MC45NDcgNi42MjEsNzAuNjQgNi42MjEsNzAuNTA4IEM2LjYyMSw3MC4wMTcgNi45ODIsNjkuMzkyIDcuNDExLDY5LjE0NSBDNy41MjEsNjkuMDgyIDcuNjI1LDY5LjA0OSA3LjcxNCw2OS4wNDkgQzcuOTg2LDY5LjA0OSA4LjAxNSw2OS4zNTUgOC4wMTUsNjkuNDg3IEM4LjAxNSw2OS45NzggNy42NTIsNzAuNjAzIDcuMjI0LDcwLjg1MSBDNy4xMTUsNzAuOTE0IDcuMDEsNzAuOTQ3IDYuOTIsNzAuOTQ3IE03LjcxNCw2OC44NjEgQzcuNTk1LDY4Ljg2MSA3LjQ2LDY4LjkgNy4zMTcsNjguOTgyIEM2LjgyOSw2OS4yNjUgNi40MzMsNjkuOTQ4IDYuNDMzLDcwLjUwOCBDNi40MzMsNzAuOTA1IDYuNjMxLDcxLjEzMyA2LjkyLDcxLjEzMyBDNy4wMzksNzEuMTMzIDcuMTc0LDcxLjA5NCA3LjMxNyw3MS4wMTIgQzcuODA2LDcwLjczIDguMjAyLDcwLjA0NyA4LjIwMiw2OS40ODcgQzguMjAyLDY5LjA5IDguMDAzLDY4Ljg2MSA3LjcxNCw2OC44NjEiIGlkPSJGaWxsLTE1IiBmaWxsPSIjODA5N0EyIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTcuNDQ0LDg1LjM1IEM3LjcwOCw4NS4xOTggNy45MjEsODUuMzE5IDcuOTIxLDg1LjYyMiBDNy45MjEsODUuOTI1IDcuNzA4LDg2LjI5MiA3LjQ0NCw4Ni40NDQgQzcuMTgxLDg2LjU5NyA2Ljk2Nyw4Ni40NzUgNi45NjcsODYuMTczIEM2Ljk2Nyw4NS44NzEgNy4xODEsODUuNTAyIDcuNDQ0LDg1LjM1IiBpZD0iRmlsbC0xNiIgZmlsbD0iI0ZGRkZGRiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik03LjIzLDg2LjUxIEM3LjA3NCw4Ni41MSA2Ljk2Nyw4Ni4zODcgNi45NjcsODYuMTczIEM2Ljk2Nyw4NS44NzEgNy4xODEsODUuNTAyIDcuNDQ0LDg1LjM1IEM3LjUyMSw4NS4zMDUgNy41OTQsODUuMjg0IDcuNjU4LDg1LjI4NCBDNy44MTQsODUuMjg0IDcuOTIxLDg1LjQwOCA3LjkyMSw4NS42MjIgQzcuOTIxLDg1LjkyNSA3LjcwOCw4Ni4yOTIgNy40NDQsODYuNDQ0IEM3LjM2Nyw4Ni40ODkgNy4yOTQsODYuNTEgNy4yMyw4Ni41MSBNNy42NTgsODUuMDk4IEM3LjU1OCw4NS4wOTggNy40NTUsODUuMTI3IDcuMzUxLDg1LjE4OCBDNy4wMzEsODUuMzczIDYuNzgxLDg1LjgwNiA2Ljc4MSw4Ni4xNzMgQzYuNzgxLDg2LjQ4MiA2Ljk2Niw4Ni42OTcgNy4yMyw4Ni42OTcgQzcuMzMsODYuNjk3IDcuNDMzLDg2LjY2NiA3LjUzOCw4Ni42MDcgQzcuODU4LDg2LjQyMiA4LjEwOCw4NS45ODkgOC4xMDgsODUuNjIyIEM4LjEwOCw4NS4zMTMgNy45MjMsODUuMDk4IDcuNjU4LDg1LjA5OCIgaWQ9IkZpbGwtMTciIGZpbGw9IiM4MDk3QTIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNNy4yMyw4Ni4zMjIgTDcuMTU0LDg2LjE3MyBDNy4xNTQsODUuOTM4IDcuMzMzLDg1LjYyOSA3LjUzOCw4NS41MTIgTDcuNjU4LDg1LjQ3MSBMNy43MzQsODUuNjIyIEM3LjczNCw4NS44NTYgNy41NTUsODYuMTY0IDcuMzUxLDg2LjI4MiBMNy4yMyw4Ni4zMjIgTTcuNjU4LDg1LjI4NCBDNy41OTQsODUuMjg0IDcuNTIxLDg1LjMwNSA3LjQ0NCw4NS4zNSBDNy4xODEsODUuNTAyIDYuOTY3LDg1Ljg3MSA2Ljk2Nyw4Ni4xNzMgQzYuOTY3LDg2LjM4NyA3LjA3NCw4Ni41MSA3LjIzLDg2LjUxIEM3LjI5NCw4Ni41MSA3LjM2Nyw4Ni40ODkgNy40NDQsODYuNDQ0IEM3LjcwOCw4Ni4yOTIgNy45MjEsODUuOTI1IDcuOTIxLDg1LjYyMiBDNy45MjEsODUuNDA4IDcuODE0LDg1LjI4NCA3LjY1OCw4NS4yODQiIGlkPSJGaWxsLTE4IiBmaWxsPSIjODA5N0EyIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTc3LjI3OCw3Ljc2OSBMNzcuMjc4LDUxLjQzNiBMMTAuMjA4LDkwLjE2IEwxMC4yMDgsNDYuNDkzIEw3Ny4yNzgsNy43NjkiIGlkPSJGaWxsLTE5IiBmaWxsPSIjNDU1QTY0Ij48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTEwLjA4Myw5MC4zNzUgTDEwLjA4Myw0Ni40MjEgTDEwLjE0Niw0Ni4zODUgTDc3LjQwMyw3LjU1NCBMNzcuNDAzLDUxLjUwOCBMNzcuMzQxLDUxLjU0NCBMMTAuMDgzLDkwLjM3NSBMMTAuMDgzLDkwLjM3NSBaIE0xMC4zMzMsNDYuNTY0IEwxMC4zMzMsODkuOTQ0IEw3Ny4xNTQsNTEuMzY1IEw3Ny4xNTQsNy45ODUgTDEwLjMzMyw0Ni41NjQgTDEwLjMzMyw0Ni41NjQgWiIgaWQ9IkZpbGwtMjAiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgIDwvZz4KICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xMjUuNzM3LDg4LjY0NyBMMTE4LjA5OCw5MS45ODEgTDExOC4wOTgsODQgTDEwNi42MzksODguNzEzIEwxMDYuNjM5LDk2Ljk4MiBMOTksMTAwLjMxNSBMMTEyLjM2OSwxMDMuOTYxIEwxMjUuNzM3LDg4LjY0NyIgaWQ9IkltcG9ydGVkLUxheWVycy1Db3B5LTIiIGZpbGw9IiM0NTVBNjQiIHNrZXRjaDp0eXBlPSJNU1NoYXBlR3JvdXAiPjwvcGF0aD4KICAgICAgICAgICAgPC9nPgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+';
  40971. function RotateInstructions() {
  40972. this.loadIcon_();
  40973. var overlay = document.createElement('div');
  40974. var s = overlay.style;
  40975. s.position = 'fixed';
  40976. s.top = 0;
  40977. s.right = 0;
  40978. s.bottom = 0;
  40979. s.left = 0;
  40980. s.backgroundColor = 'gray';
  40981. s.fontFamily = 'sans-serif';
  40982. s.zIndex = 1000000;
  40983. var img = document.createElement('img');
  40984. img.src = this.icon;
  40985. var s = img.style;
  40986. s.marginLeft = '25%';
  40987. s.marginTop = '25%';
  40988. s.width = '50%';
  40989. overlay.appendChild(img);
  40990. var text = document.createElement('div');
  40991. var s = text.style;
  40992. s.textAlign = 'center';
  40993. s.fontSize = '16px';
  40994. s.lineHeight = '24px';
  40995. s.margin = '24px 25%';
  40996. s.width = '50%';
  40997. text.innerHTML = 'Place your phone into your Cardboard viewer.';
  40998. overlay.appendChild(text);
  40999. var snackbar = document.createElement('div');
  41000. var s = snackbar.style;
  41001. s.backgroundColor = '#CFD8DC';
  41002. s.position = 'fixed';
  41003. s.bottom = 0;
  41004. s.width = '100%';
  41005. s.height = '48px';
  41006. s.padding = '14px 24px';
  41007. s.boxSizing = 'border-box';
  41008. s.color = '#656A6B';
  41009. overlay.appendChild(snackbar);
  41010. var snackbarText = document.createElement('div');
  41011. snackbarText.style.float = 'left';
  41012. snackbarText.innerHTML = 'No Cardboard viewer?';
  41013. var snackbarButton = document.createElement('a');
  41014. snackbarButton.href = 'https://www.google.com/get/cardboard/get-cardboard/';
  41015. snackbarButton.innerHTML = 'get one';
  41016. snackbarButton.target = '_blank';
  41017. var s = snackbarButton.style;
  41018. s.float = 'right';
  41019. s.fontWeight = 600;
  41020. s.textTransform = 'uppercase';
  41021. s.borderLeft = '1px solid gray';
  41022. s.paddingLeft = '24px';
  41023. s.textDecoration = 'none';
  41024. s.color = '#656A6B';
  41025. snackbar.appendChild(snackbarText);
  41026. snackbar.appendChild(snackbarButton);
  41027. this.overlay = overlay;
  41028. this.text = text;
  41029. this.hide();
  41030. }
  41031. RotateInstructions.prototype.show = function (parent) {
  41032. if (!parent && !this.overlay.parentElement) {
  41033. document.body.appendChild(this.overlay);
  41034. } else if (parent) {
  41035. if (this.overlay.parentElement && this.overlay.parentElement != parent) this.overlay.parentElement.removeChild(this.overlay);
  41036. parent.appendChild(this.overlay);
  41037. }
  41038. this.overlay.style.display = 'block';
  41039. var img = this.overlay.querySelector('img');
  41040. var s = img.style;
  41041. if (isLandscapeMode()) {
  41042. s.width = '20%';
  41043. s.marginLeft = '40%';
  41044. s.marginTop = '3%';
  41045. } else {
  41046. s.width = '50%';
  41047. s.marginLeft = '25%';
  41048. s.marginTop = '25%';
  41049. }
  41050. };
  41051. RotateInstructions.prototype.hide = function () {
  41052. this.overlay.style.display = 'none';
  41053. };
  41054. RotateInstructions.prototype.showTemporarily = function (ms, parent) {
  41055. this.show(parent);
  41056. this.timer = setTimeout(this.hide.bind(this), ms);
  41057. };
  41058. RotateInstructions.prototype.disableShowTemporarily = function () {
  41059. clearTimeout(this.timer);
  41060. };
  41061. RotateInstructions.prototype.update = function () {
  41062. this.disableShowTemporarily();
  41063. if (!isLandscapeMode() && isMobile()) {
  41064. this.show();
  41065. } else {
  41066. this.hide();
  41067. }
  41068. };
  41069. RotateInstructions.prototype.loadIcon_ = function () {
  41070. this.icon = base64('image/svg+xml', rotateInstructionsAsset);
  41071. };
  41072. var DEFAULT_VIEWER = 'CardboardV1';
  41073. var VIEWER_KEY = 'WEBVR_CARDBOARD_VIEWER';
  41074. var CLASS_NAME = 'webvr-polyfill-viewer-selector';
  41075. function ViewerSelector(defaultViewer) {
  41076. try {
  41077. this.selectedKey = localStorage.getItem(VIEWER_KEY);
  41078. } catch (error) {
  41079. console.error('Failed to load viewer profile: %s', error);
  41080. }
  41081. if (!this.selectedKey) {
  41082. this.selectedKey = defaultViewer || DEFAULT_VIEWER;
  41083. }
  41084. this.dialog = this.createDialog_(DeviceInfo.Viewers);
  41085. this.root = null;
  41086. this.onChangeCallbacks_ = [];
  41087. }
  41088. ViewerSelector.prototype.show = function (root) {
  41089. this.root = root;
  41090. root.appendChild(this.dialog);
  41091. var selected = this.dialog.querySelector('#' + this.selectedKey);
  41092. selected.checked = true;
  41093. this.dialog.style.display = 'block';
  41094. };
  41095. ViewerSelector.prototype.hide = function () {
  41096. if (this.root && this.root.contains(this.dialog)) {
  41097. this.root.removeChild(this.dialog);
  41098. }
  41099. this.dialog.style.display = 'none';
  41100. };
  41101. ViewerSelector.prototype.getCurrentViewer = function () {
  41102. return DeviceInfo.Viewers[this.selectedKey];
  41103. };
  41104. ViewerSelector.prototype.getSelectedKey_ = function () {
  41105. var input = this.dialog.querySelector('input[name=field]:checked');
  41106. if (input) {
  41107. return input.id;
  41108. }
  41109. return null;
  41110. };
  41111. ViewerSelector.prototype.onChange = function (cb) {
  41112. this.onChangeCallbacks_.push(cb);
  41113. };
  41114. ViewerSelector.prototype.fireOnChange_ = function (viewer) {
  41115. for (var i = 0; i < this.onChangeCallbacks_.length; i++) {
  41116. this.onChangeCallbacks_[i](viewer);
  41117. }
  41118. };
  41119. ViewerSelector.prototype.onSave_ = function () {
  41120. this.selectedKey = this.getSelectedKey_();
  41121. if (!this.selectedKey || !DeviceInfo.Viewers[this.selectedKey]) {
  41122. console.error('ViewerSelector.onSave_: this should never happen!');
  41123. return;
  41124. }
  41125. this.fireOnChange_(DeviceInfo.Viewers[this.selectedKey]);
  41126. try {
  41127. localStorage.setItem(VIEWER_KEY, this.selectedKey);
  41128. } catch (error) {
  41129. console.error('Failed to save viewer profile: %s', error);
  41130. }
  41131. this.hide();
  41132. };
  41133. ViewerSelector.prototype.createDialog_ = function (options) {
  41134. var container = document.createElement('div');
  41135. container.classList.add(CLASS_NAME);
  41136. container.style.display = 'none';
  41137. var overlay = document.createElement('div');
  41138. var s = overlay.style;
  41139. s.position = 'fixed';
  41140. s.left = 0;
  41141. s.top = 0;
  41142. s.width = '100%';
  41143. s.height = '100%';
  41144. s.background = 'rgba(0, 0, 0, 0.3)';
  41145. overlay.addEventListener('click', this.hide.bind(this));
  41146. var width = 280;
  41147. var dialog = document.createElement('div');
  41148. var s = dialog.style;
  41149. s.boxSizing = 'border-box';
  41150. s.position = 'fixed';
  41151. s.top = '24px';
  41152. s.left = '50%';
  41153. s.marginLeft = -width / 2 + 'px';
  41154. s.width = width + 'px';
  41155. s.padding = '24px';
  41156. s.overflow = 'hidden';
  41157. s.background = '#fafafa';
  41158. s.fontFamily = "'Roboto', sans-serif";
  41159. s.boxShadow = '0px 5px 20px #666';
  41160. dialog.appendChild(this.createH1_('Select your viewer'));
  41161. for (var id in options) {
  41162. dialog.appendChild(this.createChoice_(id, options[id].label));
  41163. }
  41164. dialog.appendChild(this.createButton_('Save', this.onSave_.bind(this)));
  41165. container.appendChild(overlay);
  41166. container.appendChild(dialog);
  41167. return container;
  41168. };
  41169. ViewerSelector.prototype.createH1_ = function (name) {
  41170. var h1 = document.createElement('h1');
  41171. var s = h1.style;
  41172. s.color = 'black';
  41173. s.fontSize = '20px';
  41174. s.fontWeight = 'bold';
  41175. s.marginTop = 0;
  41176. s.marginBottom = '24px';
  41177. h1.innerHTML = name;
  41178. return h1;
  41179. };
  41180. ViewerSelector.prototype.createChoice_ = function (id, name) {
  41181. var div = document.createElement('div');
  41182. div.style.marginTop = '8px';
  41183. div.style.color = 'black';
  41184. var input = document.createElement('input');
  41185. input.style.fontSize = '30px';
  41186. input.setAttribute('id', id);
  41187. input.setAttribute('type', 'radio');
  41188. input.setAttribute('value', id);
  41189. input.setAttribute('name', 'field');
  41190. var label = document.createElement('label');
  41191. label.style.marginLeft = '4px';
  41192. label.setAttribute('for', id);
  41193. label.innerHTML = name;
  41194. div.appendChild(input);
  41195. div.appendChild(label);
  41196. return div;
  41197. };
  41198. ViewerSelector.prototype.createButton_ = function (label, onclick) {
  41199. var button = document.createElement('button');
  41200. button.innerHTML = label;
  41201. var s = button.style;
  41202. s.float = 'right';
  41203. s.textTransform = 'uppercase';
  41204. s.color = '#1094f7';
  41205. s.fontSize = '14px';
  41206. s.letterSpacing = 0;
  41207. s.border = 0;
  41208. s.background = 'none';
  41209. s.marginTop = '16px';
  41210. button.addEventListener('click', onclick);
  41211. return button;
  41212. };
  41213. var commonjsGlobal$$1 = typeof window !== 'undefined' ? window : typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof self !== 'undefined' ? self : {};
  41214. function unwrapExports$$1 (x) {
  41215. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  41216. }
  41217. function createCommonjsModule$$1(fn, module) {
  41218. return module = { exports: {} }, fn(module, module.exports), module.exports;
  41219. }
  41220. var NoSleep = createCommonjsModule$$1(function (module, exports) {
  41221. (function webpackUniversalModuleDefinition(root, factory) {
  41222. module.exports = factory();
  41223. })(commonjsGlobal$$1, function() {
  41224. return (function(modules) {
  41225. var installedModules = {};
  41226. function __webpack_require__(moduleId) {
  41227. if(installedModules[moduleId]) {
  41228. return installedModules[moduleId].exports;
  41229. }
  41230. var module = installedModules[moduleId] = {
  41231. i: moduleId,
  41232. l: false,
  41233. exports: {}
  41234. };
  41235. modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  41236. module.l = true;
  41237. return module.exports;
  41238. }
  41239. __webpack_require__.m = modules;
  41240. __webpack_require__.c = installedModules;
  41241. __webpack_require__.d = function(exports, name, getter) {
  41242. if(!__webpack_require__.o(exports, name)) {
  41243. Object.defineProperty(exports, name, {
  41244. configurable: false,
  41245. enumerable: true,
  41246. get: getter
  41247. });
  41248. }
  41249. };
  41250. __webpack_require__.n = function(module) {
  41251. var getter = module && module.__esModule ?
  41252. function getDefault() { return module['default']; } :
  41253. function getModuleExports() { return module; };
  41254. __webpack_require__.d(getter, 'a', getter);
  41255. return getter;
  41256. };
  41257. __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  41258. __webpack_require__.p = "";
  41259. return __webpack_require__(__webpack_require__.s = 0);
  41260. })
  41261. ([
  41262. (function(module, exports, __webpack_require__) {
  41263. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  41264. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  41265. var mediaFile = __webpack_require__(1);
  41266. var oldIOS = typeof navigator !== 'undefined' && parseFloat(('' + (/CPU.*OS ([0-9_]{3,4})[0-9_]{0,1}|(CPU like).*AppleWebKit.*Mobile/i.exec(navigator.userAgent) || [0, ''])[1]).replace('undefined', '3_2').replace('_', '.').replace('_', '')) < 10 && !window.MSStream;
  41267. var NoSleep = function () {
  41268. function NoSleep() {
  41269. _classCallCheck(this, NoSleep);
  41270. if (oldIOS) {
  41271. this.noSleepTimer = null;
  41272. } else {
  41273. this.noSleepVideo = document.createElement('video');
  41274. this.noSleepVideo.setAttribute('playsinline', '');
  41275. this.noSleepVideo.setAttribute('src', mediaFile);
  41276. this.noSleepVideo.addEventListener('timeupdate', function (e) {
  41277. if (this.noSleepVideo.currentTime > 0.5) {
  41278. this.noSleepVideo.currentTime = Math.random();
  41279. }
  41280. }.bind(this));
  41281. }
  41282. }
  41283. _createClass(NoSleep, [{
  41284. key: 'enable',
  41285. value: function enable() {
  41286. if (oldIOS) {
  41287. this.disable();
  41288. this.noSleepTimer = window.setInterval(function () {
  41289. window.location.href = '/';
  41290. window.setTimeout(window.stop, 0);
  41291. }, 15000);
  41292. } else {
  41293. this.noSleepVideo.play();
  41294. }
  41295. }
  41296. }, {
  41297. key: 'disable',
  41298. value: function disable() {
  41299. if (oldIOS) {
  41300. if (this.noSleepTimer) {
  41301. window.clearInterval(this.noSleepTimer);
  41302. this.noSleepTimer = null;
  41303. }
  41304. } else {
  41305. this.noSleepVideo.pause();
  41306. }
  41307. }
  41308. }]);
  41309. return NoSleep;
  41310. }();
  41311. module.exports = NoSleep;
  41312. }),
  41313. (function(module, exports, __webpack_require__) {
  41314. module.exports = 'data:video/mp4;base64,AAAAIGZ0eXBtcDQyAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAACKBtZGF0AAAC8wYF///v3EXpvebZSLeWLNgg2SPu73gyNjQgLSBjb3JlIDE0MiByMjQ3OSBkZDc5YTYxIC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAxNCAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTEgcmVmPTEgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MToweDExMSBtZT1oZXggc3VibWU9MiBwc3k9MSBwc3lfcmQ9MS4wMDowLjAwIG1peGVkX3JlZj0wIG1lX3JhbmdlPTE2IGNocm9tYV9tZT0xIHRyZWxsaXM9MCA4eDhkY3Q9MCBjcW09MCBkZWFkem9uZT0yMSwxMSBmYXN0X3Bza2lwPTEgY2hyb21hX3FwX29mZnNldD0wIHRocmVhZHM9NiBsb29rYWhlYWRfdGhyZWFkcz0xIHNsaWNlZF90aHJlYWRzPTAgbnI9MCBkZWNpbWF0ZT0xIGludGVybGFjZWQ9MCBibHVyYXlfY29tcGF0PTAgY29uc3RyYWluZWRfaW50cmE9MCBiZnJhbWVzPTMgYl9weXJhbWlkPTIgYl9hZGFwdD0xIGJfYmlhcz0wIGRpcmVjdD0xIHdlaWdodGI9MSBvcGVuX2dvcD0wIHdlaWdodHA9MSBrZXlpbnQ9MzAwIGtleWludF9taW49MzAgc2NlbmVjdXQ9NDAgaW50cmFfcmVmcmVzaD0wIHJjX2xvb2thaGVhZD0xMCByYz1jcmYgbWJ0cmVlPTEgY3JmPTIwLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IHZidl9tYXhyYXRlPTIwMDAwIHZidl9idWZzaXplPTI1MDAwIGNyZl9tYXg9MC4wIG5hbF9ocmQ9bm9uZSBmaWxsZXI9MCBpcF9yYXRpbz0xLjQwIGFxPTE6MS4wMACAAAAAOWWIhAA3//p+C7v8tDDSTjf97w55i3SbRPO4ZY+hkjD5hbkAkL3zpJ6h/LR1CAABzgB1kqqzUorlhQAAAAxBmiQYhn/+qZYADLgAAAAJQZ5CQhX/AAj5IQADQGgcIQADQGgcAAAACQGeYUQn/wALKCEAA0BoHAAAAAkBnmNEJ/8ACykhAANAaBwhAANAaBwAAAANQZpoNExDP/6plgAMuSEAA0BoHAAAAAtBnoZFESwr/wAI+SEAA0BoHCEAA0BoHAAAAAkBnqVEJ/8ACykhAANAaBwAAAAJAZ6nRCf/AAsoIQADQGgcIQADQGgcAAAADUGarDRMQz/+qZYADLghAANAaBwAAAALQZ7KRRUsK/8ACPkhAANAaBwAAAAJAZ7pRCf/AAsoIQADQGgcIQADQGgcAAAACQGe60Qn/wALKCEAA0BoHAAAAA1BmvA0TEM//qmWAAy5IQADQGgcIQADQGgcAAAAC0GfDkUVLCv/AAj5IQADQGgcAAAACQGfLUQn/wALKSEAA0BoHCEAA0BoHAAAAAkBny9EJ/8ACyghAANAaBwAAAANQZs0NExDP/6plgAMuCEAA0BoHAAAAAtBn1JFFSwr/wAI+SEAA0BoHCEAA0BoHAAAAAkBn3FEJ/8ACyghAANAaBwAAAAJAZ9zRCf/AAsoIQADQGgcIQADQGgcAAAADUGbeDRMQz/+qZYADLkhAANAaBwAAAALQZ+WRRUsK/8ACPghAANAaBwhAANAaBwAAAAJAZ+1RCf/AAspIQADQGgcAAAACQGft0Qn/wALKSEAA0BoHCEAA0BoHAAAAA1Bm7w0TEM//qmWAAy4IQADQGgcAAAAC0Gf2kUVLCv/AAj5IQADQGgcAAAACQGf+UQn/wALKCEAA0BoHCEAA0BoHAAAAAkBn/tEJ/8ACykhAANAaBwAAAANQZvgNExDP/6plgAMuSEAA0BoHCEAA0BoHAAAAAtBnh5FFSwr/wAI+CEAA0BoHAAAAAkBnj1EJ/8ACyghAANAaBwhAANAaBwAAAAJAZ4/RCf/AAspIQADQGgcAAAADUGaJDRMQz/+qZYADLghAANAaBwAAAALQZ5CRRUsK/8ACPkhAANAaBwhAANAaBwAAAAJAZ5hRCf/AAsoIQADQGgcAAAACQGeY0Qn/wALKSEAA0BoHCEAA0BoHAAAAA1Bmmg0TEM//qmWAAy5IQADQGgcAAAAC0GehkUVLCv/AAj5IQADQGgcIQADQGgcAAAACQGepUQn/wALKSEAA0BoHAAAAAkBnqdEJ/8ACyghAANAaBwAAAANQZqsNExDP/6plgAMuCEAA0BoHCEAA0BoHAAAAAtBnspFFSwr/wAI+SEAA0BoHAAAAAkBnulEJ/8ACyghAANAaBwhAANAaBwAAAAJAZ7rRCf/AAsoIQADQGgcAAAADUGa8DRMQz/+qZYADLkhAANAaBwhAANAaBwAAAALQZ8ORRUsK/8ACPkhAANAaBwAAAAJAZ8tRCf/AAspIQADQGgcIQADQGgcAAAACQGfL0Qn/wALKCEAA0BoHAAAAA1BmzQ0TEM//qmWAAy4IQADQGgcAAAAC0GfUkUVLCv/AAj5IQADQGgcIQADQGgcAAAACQGfcUQn/wALKCEAA0BoHAAAAAkBn3NEJ/8ACyghAANAaBwhAANAaBwAAAANQZt4NExC//6plgAMuSEAA0BoHAAAAAtBn5ZFFSwr/wAI+CEAA0BoHCEAA0BoHAAAAAkBn7VEJ/8ACykhAANAaBwAAAAJAZ+3RCf/AAspIQADQGgcAAAADUGbuzRMQn/+nhAAYsAhAANAaBwhAANAaBwAAAAJQZ/aQhP/AAspIQADQGgcAAAACQGf+UQn/wALKCEAA0BoHCEAA0BoHCEAA0BoHCEAA0BoHCEAA0BoHCEAA0BoHAAACiFtb292AAAAbG12aGQAAAAA1YCCX9WAgl8AAAPoAAAH/AABAAABAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAGGlvZHMAAAAAEICAgAcAT////v7/AAAF+XRyYWsAAABcdGtoZAAAAAPVgIJf1YCCXwAAAAEAAAAAAAAH0AAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAygAAAMoAAAAAACRlZHRzAAAAHGVsc3QAAAAAAAAAAQAAB9AAABdwAAEAAAAABXFtZGlhAAAAIG1kaGQAAAAA1YCCX9WAgl8AAV+QAAK/IFXEAAAAAAAtaGRscgAAAAAAAAAAdmlkZQAAAAAAAAAAAAAAAFZpZGVvSGFuZGxlcgAAAAUcbWluZgAAABR2bWhkAAAAAQAAAAAAAAAAAAAAJGRpbmYAAAAcZHJlZgAAAAAAAAABAAAADHVybCAAAAABAAAE3HN0YmwAAACYc3RzZAAAAAAAAAABAAAAiGF2YzEAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAygDKAEgAAABIAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY//8AAAAyYXZjQwFNQCj/4QAbZ01AKOyho3ySTUBAQFAAAAMAEAAr8gDxgxlgAQAEaO+G8gAAABhzdHRzAAAAAAAAAAEAAAA8AAALuAAAABRzdHNzAAAAAAAAAAEAAAABAAAB8GN0dHMAAAAAAAAAPAAAAAEAABdwAAAAAQAAOpgAAAABAAAXcAAAAAEAAAAAAAAAAQAAC7gAAAABAAA6mAAAAAEAABdwAAAAAQAAAAAAAAABAAALuAAAAAEAADqYAAAAAQAAF3AAAAABAAAAAAAAAAEAAAu4AAAAAQAAOpgAAAABAAAXcAAAAAEAAAAAAAAAAQAAC7gAAAABAAA6mAAAAAEAABdwAAAAAQAAAAAAAAABAAALuAAAAAEAADqYAAAAAQAAF3AAAAABAAAAAAAAAAEAAAu4AAAAAQAAOpgAAAABAAAXcAAAAAEAAAAAAAAAAQAAC7gAAAABAAA6mAAAAAEAABdwAAAAAQAAAAAAAAABAAALuAAAAAEAADqYAAAAAQAAF3AAAAABAAAAAAAAAAEAAAu4AAAAAQAAOpgAAAABAAAXcAAAAAEAAAAAAAAAAQAAC7gAAAABAAA6mAAAAAEAABdwAAAAAQAAAAAAAAABAAALuAAAAAEAADqYAAAAAQAAF3AAAAABAAAAAAAAAAEAAAu4AAAAAQAAOpgAAAABAAAXcAAAAAEAAAAAAAAAAQAAC7gAAAABAAA6mAAAAAEAABdwAAAAAQAAAAAAAAABAAALuAAAAAEAAC7gAAAAAQAAF3AAAAABAAAAAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAQAAAAEAAAEEc3RzegAAAAAAAAAAAAAAPAAAAzQAAAAQAAAADQAAAA0AAAANAAAAEQAAAA8AAAANAAAADQAAABEAAAAPAAAADQAAAA0AAAARAAAADwAAAA0AAAANAAAAEQAAAA8AAAANAAAADQAAABEAAAAPAAAADQAAAA0AAAARAAAADwAAAA0AAAANAAAAEQAAAA8AAAANAAAADQAAABEAAAAPAAAADQAAAA0AAAARAAAADwAAAA0AAAANAAAAEQAAAA8AAAANAAAADQAAABEAAAAPAAAADQAAAA0AAAARAAAADwAAAA0AAAANAAAAEQAAAA8AAAANAAAADQAAABEAAAANAAAADQAAAQBzdGNvAAAAAAAAADwAAAAwAAADZAAAA3QAAAONAAADoAAAA7kAAAPQAAAD6wAAA/4AAAQXAAAELgAABEMAAARcAAAEbwAABIwAAAShAAAEugAABM0AAATkAAAE/wAABRIAAAUrAAAFQgAABV0AAAVwAAAFiQAABaAAAAW1AAAFzgAABeEAAAX+AAAGEwAABiwAAAY/AAAGVgAABnEAAAaEAAAGnQAABrQAAAbPAAAG4gAABvUAAAcSAAAHJwAAB0AAAAdTAAAHcAAAB4UAAAeeAAAHsQAAB8gAAAfjAAAH9gAACA8AAAgmAAAIQQAACFQAAAhnAAAIhAAACJcAAAMsdHJhawAAAFx0a2hkAAAAA9WAgl/VgIJfAAAAAgAAAAAAAAf8AAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAACsm1kaWEAAAAgbWRoZAAAAADVgIJf1YCCXwAArEQAAWAAVcQAAAAAACdoZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU3RlcmVvAAAAAmNtaW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAidzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAADDUAAAAAABYCAgAISEAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAABYAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAQAAAAEAAAAUc3RzegAAAAAAAAAGAAAAWAAAAXBzdGNvAAAAAAAAAFgAAAOBAAADhwAAA5oAAAOtAAADswAAA8oAAAPfAAAD5QAAA/gAAAQLAAAEEQAABCgAAAQ9AAAEUAAABFYAAARpAAAEgAAABIYAAASbAAAErgAABLQAAATHAAAE3gAABPMAAAT5AAAFDAAABR8AAAUlAAAFPAAABVEAAAVXAAAFagAABX0AAAWDAAAFmgAABa8AAAXCAAAFyAAABdsAAAXyAAAF+AAABg0AAAYgAAAGJgAABjkAAAZQAAAGZQAABmsAAAZ+AAAGkQAABpcAAAauAAAGwwAABskAAAbcAAAG7wAABwYAAAcMAAAHIQAABzQAAAc6AAAHTQAAB2QAAAdqAAAHfwAAB5IAAAeYAAAHqwAAB8IAAAfXAAAH3QAAB/AAAAgDAAAICQAACCAAAAg1AAAIOwAACE4AAAhhAAAIeAAACH4AAAiRAAAIpAAACKoAAAiwAAAItgAACLwAAAjCAAAAFnVkdGEAAAAObmFtZVN0ZXJlbwAAAHB1ZHRhAAAAaG1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAAO2lsc3QAAAAzqXRvbwAAACtkYXRhAAAAAQAAAABIYW5kQnJha2UgMC4xMC4yIDIwMTUwNjExMDA=';
  41315. })
  41316. ]);
  41317. });
  41318. });
  41319. var NoSleep$1 = unwrapExports$$1(NoSleep);
  41320. var nextDisplayId = 1000;
  41321. var defaultLeftBounds = [0, 0, 0.5, 1];
  41322. var defaultRightBounds = [0.5, 0, 0.5, 1];
  41323. var raf = window.requestAnimationFrame;
  41324. var caf = window.cancelAnimationFrame;
  41325. function VRFrameData() {
  41326. this.leftProjectionMatrix = new Float32Array(16);
  41327. this.leftViewMatrix = new Float32Array(16);
  41328. this.rightProjectionMatrix = new Float32Array(16);
  41329. this.rightViewMatrix = new Float32Array(16);
  41330. this.pose = null;
  41331. }
  41332. function VRDisplayCapabilities(config) {
  41333. Object.defineProperties(this, {
  41334. hasPosition: {
  41335. writable: false, enumerable: true, value: config.hasPosition
  41336. },
  41337. hasExternalDisplay: {
  41338. writable: false, enumerable: true, value: config.hasExternalDisplay
  41339. },
  41340. canPresent: {
  41341. writable: false, enumerable: true, value: config.canPresent
  41342. },
  41343. maxLayers: {
  41344. writable: false, enumerable: true, value: config.maxLayers
  41345. },
  41346. hasOrientation: {
  41347. enumerable: true, get: function get() {
  41348. deprecateWarning('VRDisplayCapabilities.prototype.hasOrientation', 'VRDisplay.prototype.getFrameData');
  41349. return config.hasOrientation;
  41350. }
  41351. }
  41352. });
  41353. }
  41354. function VRDisplay(config) {
  41355. config = config || {};
  41356. var USE_WAKELOCK = 'wakelock' in config ? config.wakelock : true;
  41357. this.isPolyfilled = true;
  41358. this.displayId = nextDisplayId++;
  41359. this.displayName = '';
  41360. this.depthNear = 0.01;
  41361. this.depthFar = 10000.0;
  41362. this.isPresenting = false;
  41363. Object.defineProperty(this, 'isConnected', {
  41364. get: function get() {
  41365. deprecateWarning('VRDisplay.prototype.isConnected', 'VRDisplayCapabilities.prototype.hasExternalDisplay');
  41366. return false;
  41367. }
  41368. });
  41369. this.capabilities = new VRDisplayCapabilities({
  41370. hasPosition: false,
  41371. hasOrientation: false,
  41372. hasExternalDisplay: false,
  41373. canPresent: false,
  41374. maxLayers: 1
  41375. });
  41376. this.stageParameters = null;
  41377. this.waitingForPresent_ = false;
  41378. this.layer_ = null;
  41379. this.originalParent_ = null;
  41380. this.fullscreenElement_ = null;
  41381. this.fullscreenWrapper_ = null;
  41382. this.fullscreenElementCachedStyle_ = null;
  41383. this.fullscreenEventTarget_ = null;
  41384. this.fullscreenChangeHandler_ = null;
  41385. this.fullscreenErrorHandler_ = null;
  41386. if (USE_WAKELOCK && isMobile()) {
  41387. this.wakelock_ = new NoSleep$1();
  41388. }
  41389. }
  41390. VRDisplay.prototype.getFrameData = function (frameData) {
  41391. return frameDataFromPose(frameData, this._getPose(), this);
  41392. };
  41393. VRDisplay.prototype.getPose = function () {
  41394. deprecateWarning('VRDisplay.prototype.getPose', 'VRDisplay.prototype.getFrameData');
  41395. return this._getPose();
  41396. };
  41397. VRDisplay.prototype.resetPose = function () {
  41398. deprecateWarning('VRDisplay.prototype.resetPose');
  41399. return this._resetPose();
  41400. };
  41401. VRDisplay.prototype.getImmediatePose = function () {
  41402. deprecateWarning('VRDisplay.prototype.getImmediatePose', 'VRDisplay.prototype.getFrameData');
  41403. return this._getPose();
  41404. };
  41405. VRDisplay.prototype.requestAnimationFrame = function (callback) {
  41406. return raf(callback);
  41407. };
  41408. VRDisplay.prototype.cancelAnimationFrame = function (id) {
  41409. return caf(id);
  41410. };
  41411. VRDisplay.prototype.wrapForFullscreen = function (element) {
  41412. if (isIOS()) {
  41413. return element;
  41414. }
  41415. if (!this.fullscreenWrapper_) {
  41416. this.fullscreenWrapper_ = document.createElement('div');
  41417. var cssProperties = ['height: ' + Math.min(screen.height, screen.width) + 'px !important', 'top: 0 !important', 'left: 0 !important', 'right: 0 !important', 'border: 0', 'margin: 0', 'padding: 0', 'z-index: 999999 !important', 'position: fixed'];
  41418. this.fullscreenWrapper_.setAttribute('style', cssProperties.join('; ') + ';');
  41419. this.fullscreenWrapper_.classList.add('webvr-polyfill-fullscreen-wrapper');
  41420. }
  41421. if (this.fullscreenElement_ == element) {
  41422. return this.fullscreenWrapper_;
  41423. }
  41424. if (this.fullscreenElement_) {
  41425. if (this.originalParent_) {
  41426. this.originalParent_.appendChild(this.fullscreenElement_);
  41427. } else {
  41428. this.fullscreenElement_.parentElement.removeChild(this.fullscreenElement_);
  41429. }
  41430. }
  41431. this.fullscreenElement_ = element;
  41432. this.originalParent_ = element.parentElement;
  41433. if (!this.originalParent_) {
  41434. document.body.appendChild(element);
  41435. }
  41436. if (!this.fullscreenWrapper_.parentElement) {
  41437. var parent = this.fullscreenElement_.parentElement;
  41438. parent.insertBefore(this.fullscreenWrapper_, this.fullscreenElement_);
  41439. parent.removeChild(this.fullscreenElement_);
  41440. }
  41441. this.fullscreenWrapper_.insertBefore(this.fullscreenElement_, this.fullscreenWrapper_.firstChild);
  41442. this.fullscreenElementCachedStyle_ = this.fullscreenElement_.getAttribute('style');
  41443. var self = this;
  41444. function applyFullscreenElementStyle() {
  41445. if (!self.fullscreenElement_) {
  41446. return;
  41447. }
  41448. var cssProperties = ['position: absolute', 'top: 0', 'left: 0', 'width: ' + Math.max(screen.width, screen.height) + 'px', 'height: ' + Math.min(screen.height, screen.width) + 'px', 'border: 0', 'margin: 0', 'padding: 0'];
  41449. self.fullscreenElement_.setAttribute('style', cssProperties.join('; ') + ';');
  41450. }
  41451. applyFullscreenElementStyle();
  41452. return this.fullscreenWrapper_;
  41453. };
  41454. VRDisplay.prototype.removeFullscreenWrapper = function () {
  41455. if (!this.fullscreenElement_) {
  41456. return;
  41457. }
  41458. var element = this.fullscreenElement_;
  41459. if (this.fullscreenElementCachedStyle_) {
  41460. element.setAttribute('style', this.fullscreenElementCachedStyle_);
  41461. } else {
  41462. element.removeAttribute('style');
  41463. }
  41464. this.fullscreenElement_ = null;
  41465. this.fullscreenElementCachedStyle_ = null;
  41466. var parent = this.fullscreenWrapper_.parentElement;
  41467. this.fullscreenWrapper_.removeChild(element);
  41468. if (this.originalParent_ === parent) {
  41469. parent.insertBefore(element, this.fullscreenWrapper_);
  41470. }
  41471. else if (this.originalParent_) {
  41472. this.originalParent_.appendChild(element);
  41473. }
  41474. parent.removeChild(this.fullscreenWrapper_);
  41475. return element;
  41476. };
  41477. VRDisplay.prototype.requestPresent = function (layers) {
  41478. var wasPresenting = this.isPresenting;
  41479. var self = this;
  41480. if (!(layers instanceof Array)) {
  41481. deprecateWarning('VRDisplay.prototype.requestPresent with non-array argument', 'an array of VRLayers as the first argument');
  41482. layers = [layers];
  41483. }
  41484. return new Promise(function (resolve, reject) {
  41485. if (!self.capabilities.canPresent) {
  41486. reject(new Error('VRDisplay is not capable of presenting.'));
  41487. return;
  41488. }
  41489. if (layers.length == 0 || layers.length > self.capabilities.maxLayers) {
  41490. reject(new Error('Invalid number of layers.'));
  41491. return;
  41492. }
  41493. var incomingLayer = layers[0];
  41494. if (!incomingLayer.source) {
  41495. resolve();
  41496. return;
  41497. }
  41498. var leftBounds = incomingLayer.leftBounds || defaultLeftBounds;
  41499. var rightBounds = incomingLayer.rightBounds || defaultRightBounds;
  41500. if (wasPresenting) {
  41501. var layer = self.layer_;
  41502. if (layer.source !== incomingLayer.source) {
  41503. layer.source = incomingLayer.source;
  41504. }
  41505. for (var i = 0; i < 4; i++) {
  41506. layer.leftBounds[i] = leftBounds[i];
  41507. layer.rightBounds[i] = rightBounds[i];
  41508. }
  41509. self.wrapForFullscreen(self.layer_.source);
  41510. self.updatePresent_();
  41511. resolve();
  41512. return;
  41513. }
  41514. self.layer_ = {
  41515. predistorted: incomingLayer.predistorted,
  41516. source: incomingLayer.source,
  41517. leftBounds: leftBounds.slice(0),
  41518. rightBounds: rightBounds.slice(0)
  41519. };
  41520. self.waitingForPresent_ = false;
  41521. if (self.layer_ && self.layer_.source) {
  41522. var fullscreenElement = self.wrapForFullscreen(self.layer_.source);
  41523. var onFullscreenChange = function onFullscreenChange() {
  41524. var actualFullscreenElement = getFullscreenElement();
  41525. self.isPresenting = fullscreenElement === actualFullscreenElement;
  41526. if (self.isPresenting) {
  41527. if (screen.orientation && screen.orientation.lock) {
  41528. screen.orientation.lock('landscape-primary').catch(function (error) {
  41529. console.error('screen.orientation.lock() failed due to', error.message);
  41530. });
  41531. }
  41532. self.waitingForPresent_ = false;
  41533. self.beginPresent_();
  41534. resolve();
  41535. } else {
  41536. if (screen.orientation && screen.orientation.unlock) {
  41537. screen.orientation.unlock();
  41538. }
  41539. self.removeFullscreenWrapper();
  41540. self.disableWakeLock();
  41541. self.endPresent_();
  41542. self.removeFullscreenListeners_();
  41543. }
  41544. self.fireVRDisplayPresentChange_();
  41545. };
  41546. var onFullscreenError = function onFullscreenError() {
  41547. if (!self.waitingForPresent_) {
  41548. return;
  41549. }
  41550. self.removeFullscreenWrapper();
  41551. self.removeFullscreenListeners_();
  41552. self.disableWakeLock();
  41553. self.waitingForPresent_ = false;
  41554. self.isPresenting = false;
  41555. reject(new Error('Unable to present.'));
  41556. };
  41557. self.addFullscreenListeners_(fullscreenElement, onFullscreenChange, onFullscreenError);
  41558. if (requestFullscreen(fullscreenElement)) {
  41559. self.enableWakeLock();
  41560. self.waitingForPresent_ = true;
  41561. } else if (isIOS() || isWebViewAndroid()) {
  41562. self.enableWakeLock();
  41563. self.isPresenting = true;
  41564. self.beginPresent_();
  41565. self.fireVRDisplayPresentChange_();
  41566. resolve();
  41567. }
  41568. }
  41569. if (!self.waitingForPresent_ && !isIOS()) {
  41570. exitFullscreen();
  41571. reject(new Error('Unable to present.'));
  41572. }
  41573. });
  41574. };
  41575. VRDisplay.prototype.exitPresent = function () {
  41576. var wasPresenting = this.isPresenting;
  41577. var self = this;
  41578. this.isPresenting = false;
  41579. this.layer_ = null;
  41580. this.disableWakeLock();
  41581. return new Promise(function (resolve, reject) {
  41582. if (wasPresenting) {
  41583. if (!exitFullscreen() && isIOS()) {
  41584. self.endPresent_();
  41585. self.fireVRDisplayPresentChange_();
  41586. }
  41587. if (isWebViewAndroid()) {
  41588. self.removeFullscreenWrapper();
  41589. self.removeFullscreenListeners_();
  41590. self.endPresent_();
  41591. self.fireVRDisplayPresentChange_();
  41592. }
  41593. resolve();
  41594. } else {
  41595. reject(new Error('Was not presenting to VRDisplay.'));
  41596. }
  41597. });
  41598. };
  41599. VRDisplay.prototype.getLayers = function () {
  41600. if (this.layer_) {
  41601. return [this.layer_];
  41602. }
  41603. return [];
  41604. };
  41605. VRDisplay.prototype.fireVRDisplayPresentChange_ = function () {
  41606. var event = new CustomEvent('vrdisplaypresentchange', { detail: { display: this } });
  41607. window.dispatchEvent(event);
  41608. };
  41609. VRDisplay.prototype.fireVRDisplayConnect_ = function () {
  41610. var event = new CustomEvent('vrdisplayconnect', { detail: { display: this } });
  41611. window.dispatchEvent(event);
  41612. };
  41613. VRDisplay.prototype.addFullscreenListeners_ = function (element, changeHandler, errorHandler) {
  41614. this.removeFullscreenListeners_();
  41615. this.fullscreenEventTarget_ = element;
  41616. this.fullscreenChangeHandler_ = changeHandler;
  41617. this.fullscreenErrorHandler_ = errorHandler;
  41618. if (changeHandler) {
  41619. if (document.fullscreenEnabled) {
  41620. element.addEventListener('fullscreenchange', changeHandler, false);
  41621. } else if (document.webkitFullscreenEnabled) {
  41622. element.addEventListener('webkitfullscreenchange', changeHandler, false);
  41623. } else if (document.mozFullScreenEnabled) {
  41624. document.addEventListener('mozfullscreenchange', changeHandler, false);
  41625. } else if (document.msFullscreenEnabled) {
  41626. element.addEventListener('msfullscreenchange', changeHandler, false);
  41627. }
  41628. }
  41629. if (errorHandler) {
  41630. if (document.fullscreenEnabled) {
  41631. element.addEventListener('fullscreenerror', errorHandler, false);
  41632. } else if (document.webkitFullscreenEnabled) {
  41633. element.addEventListener('webkitfullscreenerror', errorHandler, false);
  41634. } else if (document.mozFullScreenEnabled) {
  41635. document.addEventListener('mozfullscreenerror', errorHandler, false);
  41636. } else if (document.msFullscreenEnabled) {
  41637. element.addEventListener('msfullscreenerror', errorHandler, false);
  41638. }
  41639. }
  41640. };
  41641. VRDisplay.prototype.removeFullscreenListeners_ = function () {
  41642. if (!this.fullscreenEventTarget_) return;
  41643. var element = this.fullscreenEventTarget_;
  41644. if (this.fullscreenChangeHandler_) {
  41645. var changeHandler = this.fullscreenChangeHandler_;
  41646. element.removeEventListener('fullscreenchange', changeHandler, false);
  41647. element.removeEventListener('webkitfullscreenchange', changeHandler, false);
  41648. document.removeEventListener('mozfullscreenchange', changeHandler, false);
  41649. element.removeEventListener('msfullscreenchange', changeHandler, false);
  41650. }
  41651. if (this.fullscreenErrorHandler_) {
  41652. var errorHandler = this.fullscreenErrorHandler_;
  41653. element.removeEventListener('fullscreenerror', errorHandler, false);
  41654. element.removeEventListener('webkitfullscreenerror', errorHandler, false);
  41655. document.removeEventListener('mozfullscreenerror', errorHandler, false);
  41656. element.removeEventListener('msfullscreenerror', errorHandler, false);
  41657. }
  41658. this.fullscreenEventTarget_ = null;
  41659. this.fullscreenChangeHandler_ = null;
  41660. this.fullscreenErrorHandler_ = null;
  41661. };
  41662. VRDisplay.prototype.enableWakeLock = function () {
  41663. if (this.wakelock_) {
  41664. this.wakelock_.enable();
  41665. }
  41666. };
  41667. VRDisplay.prototype.disableWakeLock = function () {
  41668. if (this.wakelock_) {
  41669. this.wakelock_.disable();
  41670. }
  41671. };
  41672. VRDisplay.prototype.beginPresent_ = function () {
  41673. };
  41674. VRDisplay.prototype.endPresent_ = function () {
  41675. };
  41676. VRDisplay.prototype.submitFrame = function (pose) {
  41677. };
  41678. VRDisplay.prototype.getEyeParameters = function (whichEye) {
  41679. return null;
  41680. };
  41681. var config = {
  41682. ADDITIONAL_VIEWERS: [],
  41683. DEFAULT_VIEWER: '',
  41684. MOBILE_WAKE_LOCK: true,
  41685. DEBUG: false,
  41686. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  41687. K_FILTER: 0.98,
  41688. PREDICTION_TIME_S: 0.040,
  41689. CARDBOARD_UI_DISABLED: false,
  41690. ROTATE_INSTRUCTIONS_DISABLED: false,
  41691. YAW_ONLY: false,
  41692. BUFFER_SCALE: 0.5,
  41693. DIRTY_SUBMIT_FRAME_BINDINGS: false
  41694. };
  41695. var Eye = {
  41696. LEFT: 'left',
  41697. RIGHT: 'right'
  41698. };
  41699. function CardboardVRDisplay(config$$1) {
  41700. var defaults = extend({}, config);
  41701. config$$1 = extend(defaults, config$$1 || {});
  41702. VRDisplay.call(this, {
  41703. wakelock: config$$1.MOBILE_WAKE_LOCK
  41704. });
  41705. this.config = config$$1;
  41706. this.displayName = 'Cardboard VRDisplay';
  41707. this.capabilities = new VRDisplayCapabilities({
  41708. hasPosition: false,
  41709. hasOrientation: true,
  41710. hasExternalDisplay: false,
  41711. canPresent: true,
  41712. maxLayers: 1
  41713. });
  41714. this.stageParameters = null;
  41715. this.bufferScale_ = this.config.BUFFER_SCALE;
  41716. this.poseSensor_ = new PoseSensor(this.config);
  41717. this.distorter_ = null;
  41718. this.cardboardUI_ = null;
  41719. this.dpdb_ = new Dpdb(this.config.DPDB_URL, this.onDeviceParamsUpdated_.bind(this));
  41720. this.deviceInfo_ = new DeviceInfo(this.dpdb_.getDeviceParams(), config$$1.ADDITIONAL_VIEWERS);
  41721. this.viewerSelector_ = new ViewerSelector(config$$1.DEFAULT_VIEWER);
  41722. this.viewerSelector_.onChange(this.onViewerChanged_.bind(this));
  41723. this.deviceInfo_.setViewer(this.viewerSelector_.getCurrentViewer());
  41724. if (!this.config.ROTATE_INSTRUCTIONS_DISABLED) {
  41725. this.rotateInstructions_ = new RotateInstructions();
  41726. }
  41727. if (isIOS()) {
  41728. window.addEventListener('resize', this.onResize_.bind(this));
  41729. }
  41730. }
  41731. CardboardVRDisplay.prototype = Object.create(VRDisplay.prototype);
  41732. CardboardVRDisplay.prototype._getPose = function () {
  41733. return {
  41734. position: null,
  41735. orientation: this.poseSensor_.getOrientation(),
  41736. linearVelocity: null,
  41737. linearAcceleration: null,
  41738. angularVelocity: null,
  41739. angularAcceleration: null
  41740. };
  41741. };
  41742. CardboardVRDisplay.prototype._resetPose = function () {
  41743. if (this.poseSensor_.resetPose) {
  41744. this.poseSensor_.resetPose();
  41745. }
  41746. };
  41747. CardboardVRDisplay.prototype._getFieldOfView = function (whichEye) {
  41748. var fieldOfView;
  41749. if (whichEye == Eye.LEFT) {
  41750. fieldOfView = this.deviceInfo_.getFieldOfViewLeftEye();
  41751. } else if (whichEye == Eye.RIGHT) {
  41752. fieldOfView = this.deviceInfo_.getFieldOfViewRightEye();
  41753. } else {
  41754. console.error('Invalid eye provided: %s', whichEye);
  41755. return null;
  41756. }
  41757. return fieldOfView;
  41758. };
  41759. CardboardVRDisplay.prototype._getEyeOffset = function (whichEye) {
  41760. var offset;
  41761. if (whichEye == Eye.LEFT) {
  41762. offset = [-this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  41763. } else if (whichEye == Eye.RIGHT) {
  41764. offset = [this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  41765. } else {
  41766. console.error('Invalid eye provided: %s', whichEye);
  41767. return null;
  41768. }
  41769. return offset;
  41770. };
  41771. CardboardVRDisplay.prototype.getEyeParameters = function (whichEye) {
  41772. var offset = this._getEyeOffset(whichEye);
  41773. var fieldOfView = this._getFieldOfView(whichEye);
  41774. var eyeParams = {
  41775. offset: offset,
  41776. renderWidth: this.deviceInfo_.device.width * 0.5 * this.bufferScale_,
  41777. renderHeight: this.deviceInfo_.device.height * this.bufferScale_
  41778. };
  41779. Object.defineProperty(eyeParams, 'fieldOfView', {
  41780. enumerable: true,
  41781. get: function get() {
  41782. deprecateWarning('VRFieldOfView', 'VRFrameData\'s projection matrices');
  41783. return fieldOfView;
  41784. }
  41785. });
  41786. return eyeParams;
  41787. };
  41788. CardboardVRDisplay.prototype.onDeviceParamsUpdated_ = function (newParams) {
  41789. if (this.config.DEBUG) {
  41790. console.log('DPDB reported that device params were updated.');
  41791. }
  41792. this.deviceInfo_.updateDeviceParams(newParams);
  41793. if (this.distorter_) {
  41794. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  41795. }
  41796. };
  41797. CardboardVRDisplay.prototype.updateBounds_ = function () {
  41798. if (this.layer_ && this.distorter_ && (this.layer_.leftBounds || this.layer_.rightBounds)) {
  41799. this.distorter_.setTextureBounds(this.layer_.leftBounds, this.layer_.rightBounds);
  41800. }
  41801. };
  41802. CardboardVRDisplay.prototype.beginPresent_ = function () {
  41803. var gl = this.layer_.source.getContext('webgl');
  41804. if (!gl) gl = this.layer_.source.getContext('experimental-webgl');
  41805. if (!gl) gl = this.layer_.source.getContext('webgl2');
  41806. if (!gl) return;
  41807. if (this.layer_.predistorted) {
  41808. if (!this.config.CARDBOARD_UI_DISABLED) {
  41809. gl.canvas.width = getScreenWidth() * this.bufferScale_;
  41810. gl.canvas.height = getScreenHeight() * this.bufferScale_;
  41811. this.cardboardUI_ = new CardboardUI(gl);
  41812. }
  41813. } else {
  41814. if (!this.config.CARDBOARD_UI_DISABLED) {
  41815. this.cardboardUI_ = new CardboardUI(gl);
  41816. }
  41817. this.distorter_ = new CardboardDistorter(gl, this.cardboardUI_, this.config.BUFFER_SCALE, this.config.DIRTY_SUBMIT_FRAME_BINDINGS);
  41818. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  41819. }
  41820. if (this.cardboardUI_) {
  41821. this.cardboardUI_.listen(function (e) {
  41822. this.viewerSelector_.show(this.layer_.source.parentElement);
  41823. e.stopPropagation();
  41824. e.preventDefault();
  41825. }.bind(this), function (e) {
  41826. this.exitPresent();
  41827. e.stopPropagation();
  41828. e.preventDefault();
  41829. }.bind(this));
  41830. }
  41831. if (this.rotateInstructions_) {
  41832. if (isLandscapeMode() && isMobile()) {
  41833. this.rotateInstructions_.showTemporarily(3000, this.layer_.source.parentElement);
  41834. } else {
  41835. this.rotateInstructions_.update();
  41836. }
  41837. }
  41838. this.orientationHandler = this.onOrientationChange_.bind(this);
  41839. window.addEventListener('orientationchange', this.orientationHandler);
  41840. this.vrdisplaypresentchangeHandler = this.updateBounds_.bind(this);
  41841. window.addEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  41842. this.fireVRDisplayDeviceParamsChange_();
  41843. };
  41844. CardboardVRDisplay.prototype.endPresent_ = function () {
  41845. if (this.distorter_) {
  41846. this.distorter_.destroy();
  41847. this.distorter_ = null;
  41848. }
  41849. if (this.cardboardUI_) {
  41850. this.cardboardUI_.destroy();
  41851. this.cardboardUI_ = null;
  41852. }
  41853. if (this.rotateInstructions_) {
  41854. this.rotateInstructions_.hide();
  41855. }
  41856. this.viewerSelector_.hide();
  41857. window.removeEventListener('orientationchange', this.orientationHandler);
  41858. window.removeEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  41859. };
  41860. CardboardVRDisplay.prototype.updatePresent_ = function () {
  41861. this.endPresent_();
  41862. this.beginPresent_();
  41863. };
  41864. CardboardVRDisplay.prototype.submitFrame = function (pose) {
  41865. if (this.distorter_) {
  41866. this.updateBounds_();
  41867. this.distorter_.submitFrame();
  41868. } else if (this.cardboardUI_ && this.layer_) {
  41869. var canvas = this.layer_.source.getContext('webgl').canvas;
  41870. if (canvas.width != this.lastWidth || canvas.height != this.lastHeight) {
  41871. this.cardboardUI_.onResize();
  41872. }
  41873. this.lastWidth = canvas.width;
  41874. this.lastHeight = canvas.height;
  41875. this.cardboardUI_.render();
  41876. }
  41877. };
  41878. CardboardVRDisplay.prototype.onOrientationChange_ = function (e) {
  41879. this.viewerSelector_.hide();
  41880. if (this.rotateInstructions_) {
  41881. this.rotateInstructions_.update();
  41882. }
  41883. this.onResize_();
  41884. };
  41885. CardboardVRDisplay.prototype.onResize_ = function (e) {
  41886. if (this.layer_) {
  41887. var gl = this.layer_.source.getContext('webgl');
  41888. var cssProperties = ['position: absolute', 'top: 0', 'left: 0',
  41889. 'width: 100vw', 'height: 100vh', 'border: 0', 'margin: 0',
  41890. 'padding: 0px', 'box-sizing: content-box'];
  41891. gl.canvas.setAttribute('style', cssProperties.join('; ') + ';');
  41892. safariCssSizeWorkaround(gl.canvas);
  41893. }
  41894. };
  41895. CardboardVRDisplay.prototype.onViewerChanged_ = function (viewer) {
  41896. this.deviceInfo_.setViewer(viewer);
  41897. if (this.distorter_) {
  41898. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  41899. }
  41900. this.fireVRDisplayDeviceParamsChange_();
  41901. };
  41902. CardboardVRDisplay.prototype.fireVRDisplayDeviceParamsChange_ = function () {
  41903. var event = new CustomEvent('vrdisplaydeviceparamschange', {
  41904. detail: {
  41905. vrdisplay: this,
  41906. deviceInfo: this.deviceInfo_
  41907. }
  41908. });
  41909. window.dispatchEvent(event);
  41910. };
  41911. CardboardVRDisplay.VRFrameData = VRFrameData;
  41912. CardboardVRDisplay.VRDisplay = VRDisplay;
  41913. return CardboardVRDisplay;
  41914. })));
  41915. });
  41916. var CardboardVRDisplay = unwrapExports(cardboardVrDisplay);
  41917. var version = "0.10.8";
  41918. var DefaultConfig = {
  41919. ADDITIONAL_VIEWERS: [],
  41920. DEFAULT_VIEWER: '',
  41921. PROVIDE_MOBILE_VRDISPLAY: true,
  41922. GET_VR_DISPLAYS_TIMEOUT: 1000,
  41923. MOBILE_WAKE_LOCK: true,
  41924. DEBUG: false,
  41925. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  41926. K_FILTER: 0.98,
  41927. PREDICTION_TIME_S: 0.040,
  41928. CARDBOARD_UI_DISABLED: false,
  41929. ROTATE_INSTRUCTIONS_DISABLED: false,
  41930. YAW_ONLY: false,
  41931. BUFFER_SCALE: 0.5,
  41932. DIRTY_SUBMIT_FRAME_BINDINGS: false
  41933. };
  41934. function WebVRPolyfill(config) {
  41935. this.config = extend(extend({}, DefaultConfig), config);
  41936. this.polyfillDisplays = [];
  41937. this.enabled = false;
  41938. this.hasNative = 'getVRDisplays' in navigator;
  41939. this.native = {};
  41940. this.native.getVRDisplays = navigator.getVRDisplays;
  41941. this.native.VRFrameData = window.VRFrameData;
  41942. this.native.VRDisplay = window.VRDisplay;
  41943. if (!this.hasNative || this.config.PROVIDE_MOBILE_VRDISPLAY && isMobile()) {
  41944. this.enable();
  41945. this.getVRDisplays().then(function (displays) {
  41946. if (displays && displays[0] && displays[0].fireVRDisplayConnect_) {
  41947. displays[0].fireVRDisplayConnect_();
  41948. }
  41949. });
  41950. }
  41951. }
  41952. WebVRPolyfill.prototype.getPolyfillDisplays = function () {
  41953. if (this._polyfillDisplaysPopulated) {
  41954. return this.polyfillDisplays;
  41955. }
  41956. if (isMobile()) {
  41957. var vrDisplay = new CardboardVRDisplay({
  41958. ADDITIONAL_VIEWERS: this.config.ADDITIONAL_VIEWERS,
  41959. DEFAULT_VIEWER: this.config.DEFAULT_VIEWER,
  41960. MOBILE_WAKE_LOCK: this.config.MOBILE_WAKE_LOCK,
  41961. DEBUG: this.config.DEBUG,
  41962. DPDB_URL: this.config.DPDB_URL,
  41963. CARDBOARD_UI_DISABLED: this.config.CARDBOARD_UI_DISABLED,
  41964. K_FILTER: this.config.K_FILTER,
  41965. PREDICTION_TIME_S: this.config.PREDICTION_TIME_S,
  41966. ROTATE_INSTRUCTIONS_DISABLED: this.config.ROTATE_INSTRUCTIONS_DISABLED,
  41967. YAW_ONLY: this.config.YAW_ONLY,
  41968. BUFFER_SCALE: this.config.BUFFER_SCALE,
  41969. DIRTY_SUBMIT_FRAME_BINDINGS: this.config.DIRTY_SUBMIT_FRAME_BINDINGS
  41970. });
  41971. this.polyfillDisplays.push(vrDisplay);
  41972. }
  41973. this._polyfillDisplaysPopulated = true;
  41974. return this.polyfillDisplays;
  41975. };
  41976. WebVRPolyfill.prototype.enable = function () {
  41977. this.enabled = true;
  41978. if (this.hasNative && this.native.VRFrameData) {
  41979. var NativeVRFrameData = this.native.VRFrameData;
  41980. var nativeFrameData = new this.native.VRFrameData();
  41981. var nativeGetFrameData = this.native.VRDisplay.prototype.getFrameData;
  41982. window.VRDisplay.prototype.getFrameData = function (frameData) {
  41983. if (frameData instanceof NativeVRFrameData) {
  41984. nativeGetFrameData.call(this, frameData);
  41985. return;
  41986. }
  41987. nativeGetFrameData.call(this, nativeFrameData);
  41988. frameData.pose = nativeFrameData.pose;
  41989. copyArray(nativeFrameData.leftProjectionMatrix, frameData.leftProjectionMatrix);
  41990. copyArray(nativeFrameData.rightProjectionMatrix, frameData.rightProjectionMatrix);
  41991. copyArray(nativeFrameData.leftViewMatrix, frameData.leftViewMatrix);
  41992. copyArray(nativeFrameData.rightViewMatrix, frameData.rightViewMatrix);
  41993. };
  41994. }
  41995. navigator.getVRDisplays = this.getVRDisplays.bind(this);
  41996. window.VRDisplay = CardboardVRDisplay.VRDisplay;
  41997. window.VRFrameData = CardboardVRDisplay.VRFrameData;
  41998. };
  41999. WebVRPolyfill.prototype.getVRDisplays = function () {
  42000. var _this = this;
  42001. var config = this.config;
  42002. if (!this.hasNative) {
  42003. return Promise.resolve(this.getPolyfillDisplays());
  42004. }
  42005. var timeoutId;
  42006. var vrDisplaysNative = this.native.getVRDisplays.call(navigator);
  42007. var timeoutPromise = new Promise(function (resolve) {
  42008. timeoutId = setTimeout(function () {
  42009. console.warn('Native WebVR implementation detected, but `getVRDisplays()` failed to resolve. Falling back to polyfill.');
  42010. resolve([]);
  42011. }, config.GET_VR_DISPLAYS_TIMEOUT);
  42012. });
  42013. return race([vrDisplaysNative, timeoutPromise]).then(function (nativeDisplays) {
  42014. clearTimeout(timeoutId);
  42015. return nativeDisplays.length > 0 ? nativeDisplays : _this.getPolyfillDisplays();
  42016. });
  42017. };
  42018. WebVRPolyfill.version = version;
  42019. WebVRPolyfill.VRFrameData = CardboardVRDisplay.VRFrameData;
  42020. WebVRPolyfill.VRDisplay = CardboardVRDisplay.VRDisplay;
  42021. var webvrPolyfill = Object.freeze({
  42022. default: WebVRPolyfill
  42023. });
  42024. var require$$0 = ( webvrPolyfill && WebVRPolyfill ) || webvrPolyfill;
  42025. if (typeof commonjsGlobal !== 'undefined' && commonjsGlobal.window) {
  42026. if (!commonjsGlobal.document) {
  42027. commonjsGlobal.document = commonjsGlobal.window.document;
  42028. }
  42029. if (!commonjsGlobal.navigator) {
  42030. commonjsGlobal.navigator = commonjsGlobal.window.navigator;
  42031. }
  42032. }
  42033. var src = require$$0;
  42034. return src;
  42035. })));
  42036. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  42037. },{}],47:[function(_dereq_,module,exports){
  42038. var newline = /\n/
  42039. var newlineChar = '\n'
  42040. var whitespace = /\s/
  42041. module.exports = function(text, opt) {
  42042. var lines = module.exports.lines(text, opt)
  42043. return lines.map(function(line) {
  42044. return text.substring(line.start, line.end)
  42045. }).join('\n')
  42046. }
  42047. module.exports.lines = function wordwrap(text, opt) {
  42048. opt = opt||{}
  42049. //zero width results in nothing visible
  42050. if (opt.width === 0 && opt.mode !== 'nowrap')
  42051. return []
  42052. text = text||''
  42053. var width = typeof opt.width === 'number' ? opt.width : Number.MAX_VALUE
  42054. var start = Math.max(0, opt.start||0)
  42055. var end = typeof opt.end === 'number' ? opt.end : text.length
  42056. var mode = opt.mode
  42057. var measure = opt.measure || monospace
  42058. if (mode === 'pre')
  42059. return pre(measure, text, start, end, width)
  42060. else
  42061. return greedy(measure, text, start, end, width, mode)
  42062. }
  42063. function idxOf(text, chr, start, end) {
  42064. var idx = text.indexOf(chr, start)
  42065. if (idx === -1 || idx > end)
  42066. return end
  42067. return idx
  42068. }
  42069. function isWhitespace(chr) {
  42070. return whitespace.test(chr)
  42071. }
  42072. function pre(measure, text, start, end, width) {
  42073. var lines = []
  42074. var lineStart = start
  42075. for (var i=start; i<end && i<text.length; i++) {
  42076. var chr = text.charAt(i)
  42077. var isNewline = newline.test(chr)
  42078. //If we've reached a newline, then step down a line
  42079. //Or if we've reached the EOF
  42080. if (isNewline || i===end-1) {
  42081. var lineEnd = isNewline ? i : i+1
  42082. var measured = measure(text, lineStart, lineEnd, width)
  42083. lines.push(measured)
  42084. lineStart = i+1
  42085. }
  42086. }
  42087. return lines
  42088. }
  42089. function greedy(measure, text, start, end, width, mode) {
  42090. //A greedy word wrapper based on LibGDX algorithm
  42091. //https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java
  42092. var lines = []
  42093. var testWidth = width
  42094. //if 'nowrap' is specified, we only wrap on newline chars
  42095. if (mode === 'nowrap')
  42096. testWidth = Number.MAX_VALUE
  42097. while (start < end && start < text.length) {
  42098. //get next newline position
  42099. var newLine = idxOf(text, newlineChar, start, end)
  42100. //eat whitespace at start of line
  42101. while (start < newLine) {
  42102. if (!isWhitespace( text.charAt(start) ))
  42103. break
  42104. start++
  42105. }
  42106. //determine visible # of glyphs for the available width
  42107. var measured = measure(text, start, newLine, testWidth)
  42108. var lineEnd = start + (measured.end-measured.start)
  42109. var nextStart = lineEnd + newlineChar.length
  42110. //if we had to cut the line before the next newline...
  42111. if (lineEnd < newLine) {
  42112. //find char to break on
  42113. while (lineEnd > start) {
  42114. if (isWhitespace(text.charAt(lineEnd)))
  42115. break
  42116. lineEnd--
  42117. }
  42118. if (lineEnd === start) {
  42119. if (nextStart > start + newlineChar.length) nextStart--
  42120. lineEnd = nextStart // If no characters to break, show all.
  42121. } else {
  42122. nextStart = lineEnd
  42123. //eat whitespace at end of line
  42124. while (lineEnd > start) {
  42125. if (!isWhitespace(text.charAt(lineEnd - newlineChar.length)))
  42126. break
  42127. lineEnd--
  42128. }
  42129. }
  42130. }
  42131. if (lineEnd >= start) {
  42132. var result = measure(text, start, lineEnd, testWidth)
  42133. lines.push(result)
  42134. }
  42135. start = nextStart
  42136. }
  42137. return lines
  42138. }
  42139. //determines the visible number of glyphs within a given width
  42140. function monospace(text, start, end, width) {
  42141. var glyphs = Math.min(width, end-start)
  42142. return {
  42143. start: start,
  42144. end: start+glyphs
  42145. }
  42146. }
  42147. },{}],48:[function(_dereq_,module,exports){
  42148. "use strict";
  42149. var window = _dereq_("global/window")
  42150. var isFunction = _dereq_("is-function")
  42151. var parseHeaders = _dereq_("parse-headers")
  42152. var xtend = _dereq_("xtend")
  42153. module.exports = createXHR
  42154. createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
  42155. createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
  42156. forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
  42157. createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
  42158. options = initParams(uri, options, callback)
  42159. options.method = method.toUpperCase()
  42160. return _createXHR(options)
  42161. }
  42162. })
  42163. function forEachArray(array, iterator) {
  42164. for (var i = 0; i < array.length; i++) {
  42165. iterator(array[i])
  42166. }
  42167. }
  42168. function isEmpty(obj){
  42169. for(var i in obj){
  42170. if(obj.hasOwnProperty(i)) return false
  42171. }
  42172. return true
  42173. }
  42174. function initParams(uri, options, callback) {
  42175. var params = uri
  42176. if (isFunction(options)) {
  42177. callback = options
  42178. if (typeof uri === "string") {
  42179. params = {uri:uri}
  42180. }
  42181. } else {
  42182. params = xtend(options, {uri: uri})
  42183. }
  42184. params.callback = callback
  42185. return params
  42186. }
  42187. function createXHR(uri, options, callback) {
  42188. options = initParams(uri, options, callback)
  42189. return _createXHR(options)
  42190. }
  42191. function _createXHR(options) {
  42192. if(typeof options.callback === "undefined"){
  42193. throw new Error("callback argument missing")
  42194. }
  42195. var called = false
  42196. var callback = function cbOnce(err, response, body){
  42197. if(!called){
  42198. called = true
  42199. options.callback(err, response, body)
  42200. }
  42201. }
  42202. function readystatechange() {
  42203. if (xhr.readyState === 4) {
  42204. setTimeout(loadFunc, 0)
  42205. }
  42206. }
  42207. function getBody() {
  42208. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  42209. var body = undefined
  42210. if (xhr.response) {
  42211. body = xhr.response
  42212. } else {
  42213. body = xhr.responseText || getXml(xhr)
  42214. }
  42215. if (isJson) {
  42216. try {
  42217. body = JSON.parse(body)
  42218. } catch (e) {}
  42219. }
  42220. return body
  42221. }
  42222. function errorFunc(evt) {
  42223. clearTimeout(timeoutTimer)
  42224. if(!(evt instanceof Error)){
  42225. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
  42226. }
  42227. evt.statusCode = 0
  42228. return callback(evt, failureResponse)
  42229. }
  42230. // will load the data & process the response in a special response object
  42231. function loadFunc() {
  42232. if (aborted) return
  42233. var status
  42234. clearTimeout(timeoutTimer)
  42235. if(options.useXDR && xhr.status===undefined) {
  42236. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  42237. status = 200
  42238. } else {
  42239. status = (xhr.status === 1223 ? 204 : xhr.status)
  42240. }
  42241. var response = failureResponse
  42242. var err = null
  42243. if (status !== 0){
  42244. response = {
  42245. body: getBody(),
  42246. statusCode: status,
  42247. method: method,
  42248. headers: {},
  42249. url: uri,
  42250. rawRequest: xhr
  42251. }
  42252. if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
  42253. response.headers = parseHeaders(xhr.getAllResponseHeaders())
  42254. }
  42255. } else {
  42256. err = new Error("Internal XMLHttpRequest Error")
  42257. }
  42258. return callback(err, response, response.body)
  42259. }
  42260. var xhr = options.xhr || null
  42261. if (!xhr) {
  42262. if (options.cors || options.useXDR) {
  42263. xhr = new createXHR.XDomainRequest()
  42264. }else{
  42265. xhr = new createXHR.XMLHttpRequest()
  42266. }
  42267. }
  42268. var key
  42269. var aborted
  42270. var uri = xhr.url = options.uri || options.url
  42271. var method = xhr.method = options.method || "GET"
  42272. var body = options.body || options.data
  42273. var headers = xhr.headers = options.headers || {}
  42274. var sync = !!options.sync
  42275. var isJson = false
  42276. var timeoutTimer
  42277. var failureResponse = {
  42278. body: undefined,
  42279. headers: {},
  42280. statusCode: 0,
  42281. method: method,
  42282. url: uri,
  42283. rawRequest: xhr
  42284. }
  42285. if ("json" in options && options.json !== false) {
  42286. isJson = true
  42287. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
  42288. if (method !== "GET" && method !== "HEAD") {
  42289. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
  42290. body = JSON.stringify(options.json === true ? body : options.json)
  42291. }
  42292. }
  42293. xhr.onreadystatechange = readystatechange
  42294. xhr.onload = loadFunc
  42295. xhr.onerror = errorFunc
  42296. // IE9 must have onprogress be set to a unique function.
  42297. xhr.onprogress = function () {
  42298. // IE must die
  42299. }
  42300. xhr.onabort = function(){
  42301. aborted = true;
  42302. }
  42303. xhr.ontimeout = errorFunc
  42304. xhr.open(method, uri, !sync, options.username, options.password)
  42305. //has to be after open
  42306. if(!sync) {
  42307. xhr.withCredentials = !!options.withCredentials
  42308. }
  42309. // Cannot set timeout with sync request
  42310. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  42311. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  42312. if (!sync && options.timeout > 0 ) {
  42313. timeoutTimer = setTimeout(function(){
  42314. if (aborted) return
  42315. aborted = true//IE9 may still call readystatechange
  42316. xhr.abort("timeout")
  42317. var e = new Error("XMLHttpRequest timeout")
  42318. e.code = "ETIMEDOUT"
  42319. errorFunc(e)
  42320. }, options.timeout )
  42321. }
  42322. if (xhr.setRequestHeader) {
  42323. for(key in headers){
  42324. if(headers.hasOwnProperty(key)){
  42325. xhr.setRequestHeader(key, headers[key])
  42326. }
  42327. }
  42328. } else if (options.headers && !isEmpty(options.headers)) {
  42329. throw new Error("Headers cannot be set on an XDomainRequest object")
  42330. }
  42331. if ("responseType" in options) {
  42332. xhr.responseType = options.responseType
  42333. }
  42334. if ("beforeSend" in options &&
  42335. typeof options.beforeSend === "function"
  42336. ) {
  42337. options.beforeSend(xhr)
  42338. }
  42339. // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  42340. // XMLHttpRequest spec says to pass null as body to indicate no body
  42341. // See https://github.com/naugtur/xhr/issues/100.
  42342. xhr.send(body || null)
  42343. return xhr
  42344. }
  42345. function getXml(xhr) {
  42346. // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException"
  42347. // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.
  42348. try {
  42349. if (xhr.responseType === "document") {
  42350. return xhr.responseXML
  42351. }
  42352. var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
  42353. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  42354. return xhr.responseXML
  42355. }
  42356. } catch (e) {}
  42357. return null
  42358. }
  42359. function noop() {}
  42360. },{"global/window":15,"is-function":19,"parse-headers":30,"xtend":50}],49:[function(_dereq_,module,exports){
  42361. module.exports = (function xmlparser() {
  42362. //common browsers
  42363. if (typeof self.DOMParser !== 'undefined') {
  42364. return function(str) {
  42365. var parser = new self.DOMParser()
  42366. return parser.parseFromString(str, 'application/xml')
  42367. }
  42368. }
  42369. //IE8 fallback
  42370. if (typeof self.ActiveXObject !== 'undefined'
  42371. && new self.ActiveXObject('Microsoft.XMLDOM')) {
  42372. return function(str) {
  42373. var xmlDoc = new self.ActiveXObject("Microsoft.XMLDOM")
  42374. xmlDoc.async = "false"
  42375. xmlDoc.loadXML(str)
  42376. return xmlDoc
  42377. }
  42378. }
  42379. //last resort fallback
  42380. return function(str) {
  42381. var div = document.createElement('div')
  42382. div.innerHTML = str
  42383. return div
  42384. }
  42385. })()
  42386. },{}],50:[function(_dereq_,module,exports){
  42387. module.exports = extend
  42388. var hasOwnProperty = Object.prototype.hasOwnProperty;
  42389. function extend() {
  42390. var target = {}
  42391. for (var i = 0; i < arguments.length; i++) {
  42392. var source = arguments[i]
  42393. for (var key in source) {
  42394. if (hasOwnProperty.call(source, key)) {
  42395. target[key] = source[key]
  42396. }
  42397. }
  42398. }
  42399. return target
  42400. }
  42401. },{}],51:[function(_dereq_,module,exports){
  42402. module.exports={
  42403. "name": "aframe",
  42404. "version": "0.8.2",
  42405. "description": "A web framework for building virtual reality experiences.",
  42406. "homepage": "https://aframe.io/",
  42407. "main": "dist/aframe-master.js",
  42408. "scripts": {
  42409. "browserify": "browserify src/index.js -s 'AFRAME' -p browserify-derequire",
  42410. "build": "shx mkdir -p build/ && npm run browserify -- --debug -t [envify --INSPECTOR_VERSION dev] -o build/aframe.js",
  42411. "codecov": "codecov",
  42412. "dev": "npm run build && cross-env INSPECTOR_VERSION=dev node ./scripts/budo -t envify",
  42413. "dist": "node scripts/updateVersionLog.js && npm run dist:min && npm run dist:max",
  42414. "dist:max": "npm run browserify -s -- --debug | exorcist dist/aframe-master.js.map > dist/aframe-master.js",
  42415. "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",
  42416. "docs": "markserv --dir docs --port 9001",
  42417. "preghpages": "node ./scripts/preghpages.js",
  42418. "ghpages": "ghpages -p gh-pages/",
  42419. "lint": "semistandard -v | snazzy",
  42420. "lint:fix": "semistandard --fix",
  42421. "precommit": "npm run lint",
  42422. "prepush": "node scripts/testOnlyCheck.js",
  42423. "prerelease": "node scripts/release.js 0.7.1 0.8.0",
  42424. "start": "npm run dev",
  42425. "test": "karma start ./tests/karma.conf.js",
  42426. "test:docs": "node scripts/docsLint.js",
  42427. "test:firefox": "npm test -- --browsers Firefox",
  42428. "test:chrome": "npm test -- --browsers Chrome",
  42429. "test:nobrowser": "NO_BROWSER=true npm test",
  42430. "test:node": "mocha --ui tdd tests/node"
  42431. },
  42432. "repository": "aframevr/aframe",
  42433. "license": "MIT",
  42434. "files": [
  42435. "dist/*",
  42436. "docs/**/*",
  42437. "src/**/*",
  42438. "vendor/**/*"
  42439. ],
  42440. "dependencies": {
  42441. "animejs": "^2.2.0",
  42442. "browserify-css": "^0.8.4",
  42443. "debug": "ngokevin/debug#noTimestamp",
  42444. "deep-assign": "^2.0.0",
  42445. "document-register-element": "dmarcos/document-register-element#8ccc532b7f3744be954574caf3072a5fd260ca90",
  42446. "envify": "^3.4.1",
  42447. "load-bmfont": "^1.2.3",
  42448. "object-assign": "^4.0.1",
  42449. "present": "0.0.6",
  42450. "promise-polyfill": "^3.1.0",
  42451. "style-attr": "^1.0.2",
  42452. "three": "dmarcos/three.js#webXRSupport",
  42453. "three-bmfont-text": "^2.1.0",
  42454. "webvr-polyfill": "^0.10.8"
  42455. },
  42456. "devDependencies": {
  42457. "browserify": "^13.1.0",
  42458. "browserify-derequire": "^0.9.4",
  42459. "browserify-istanbul": "^2.0.0",
  42460. "budo": "^9.2.0",
  42461. "chai": "^3.5.0",
  42462. "chai-shallow-deep-equal": "^1.4.0",
  42463. "chalk": "^1.1.3",
  42464. "codecov": "^1.0.1",
  42465. "cross-env": "^5.0.1",
  42466. "exorcist": "^0.4.0",
  42467. "ghpages": "0.0.8",
  42468. "git-rev": "^0.2.1",
  42469. "glob": "^7.1.1",
  42470. "husky": "^0.11.7",
  42471. "istanbul": "^0.4.5",
  42472. "jsdom": "^9.11.0",
  42473. "karma": "1.4.1",
  42474. "karma-browserify": "^5.1.0",
  42475. "karma-chai-shallow-deep-equal": "0.0.4",
  42476. "karma-chrome-launcher": "^2.0.0",
  42477. "karma-coverage": "^1.1.1",
  42478. "karma-env-preprocessor": "^0.1.1",
  42479. "karma-firefox-launcher": "^1.0.0",
  42480. "karma-mocha": "^1.1.1",
  42481. "karma-mocha-reporter": "^2.1.0",
  42482. "karma-sinon-chai": "1.2.4",
  42483. "lolex": "^1.5.1",
  42484. "markserv": "github:sukima/markserv#feature/fix-broken-websoketio-link",
  42485. "minifyify": "^7.3.3",
  42486. "mocha": "^3.0.2",
  42487. "mozilla-download": "^1.1.1",
  42488. "replace-in-file": "^2.5.3",
  42489. "semistandard": "^9.0.0",
  42490. "shelljs": "^0.7.7",
  42491. "shx": "^0.2.2",
  42492. "sinon": "^1.17.5",
  42493. "sinon-chai": "2.8.0",
  42494. "snazzy": "^5.0.0",
  42495. "too-wordy": "ngokevin/too-wordy",
  42496. "uglifyjs": "^2.4.10",
  42497. "write-good": "^0.9.1"
  42498. },
  42499. "link": true,
  42500. "browserify": {
  42501. "transform": [
  42502. "browserify-css",
  42503. "envify"
  42504. ]
  42505. },
  42506. "semistandard": {
  42507. "ignore": [
  42508. "build/**",
  42509. "dist/**",
  42510. "examples/**/shaders/*.js",
  42511. "**/vendor/**"
  42512. ]
  42513. },
  42514. "keywords": [
  42515. "3d",
  42516. "aframe",
  42517. "cardboard",
  42518. "components",
  42519. "oculus",
  42520. "three",
  42521. "three.js",
  42522. "rift",
  42523. "vive",
  42524. "vr",
  42525. "web-components",
  42526. "webvr"
  42527. ],
  42528. "browserify-css": {
  42529. "minify": true
  42530. },
  42531. "engines": {
  42532. "node": ">= 4.6.0",
  42533. "npm": "^2.15.9"
  42534. }
  42535. }
  42536. },{}],52:[function(_dereq_,module,exports){
  42537. var anime = _dereq_('animejs');
  42538. var components = _dereq_('../core/component').components;
  42539. var registerComponent = _dereq_('../core/component').registerComponent;
  42540. var THREE = _dereq_('../lib/three');
  42541. var utils = _dereq_('../utils');
  42542. var colorHelperFrom = new THREE.Color();
  42543. var colorHelperTo = new THREE.Color();
  42544. var getComponentProperty = utils.entity.getComponentProperty;
  42545. var setComponentProperty = utils.entity.setComponentProperty;
  42546. var splitCache = {};
  42547. var TYPE_COLOR = 'color';
  42548. var PROP_POSITION = 'position';
  42549. var PROP_ROTATION = 'rotation';
  42550. var PROP_SCALE = 'scale';
  42551. var STRING_COMPONENTS = 'components';
  42552. var STRING_OBJECT3D = 'object3D';
  42553. /**
  42554. * Animation component for A-Frame using anime.js.
  42555. *
  42556. * The component manually controls the tick by setting `autoplay: false` on anime.js and
  42557. * manually * calling `animation.tick()` in the tick handler. To pause or resume, we toggle a
  42558. * boolean * flag * `isAnimationPlaying`.
  42559. *
  42560. * anime.js animation config for tweenining Javascript objects and values works as:
  42561. *
  42562. * config = {
  42563. * targets: {foo: 0.0, bar: '#000'},
  42564. * foo: 1.0,
  42565. * bar: '#FFF'
  42566. * }
  42567. *
  42568. * The above will tween each property in `targets`. The `to` values are set in the root of
  42569. * the config.
  42570. *
  42571. * @member {object} animation - anime.js instance.
  42572. * @member {boolean} animationIsPlaying - Control if animation is playing.
  42573. */
  42574. module.exports.Component = registerComponent('animation', {
  42575. schema: {
  42576. autoplay: {default: true},
  42577. delay: {default: 0},
  42578. dir: {default: ''},
  42579. dur: {default: 1000},
  42580. easing: {default: 'easeInQuad'},
  42581. elasticity: {default: 400},
  42582. enabled: {default: true},
  42583. from: {default: ''},
  42584. loop: {
  42585. default: 0,
  42586. parse: function (value) {
  42587. // Boolean or integer.
  42588. if (value === true || value === 'true') { return true; }
  42589. if (value === false || value === 'false') { return false; }
  42590. return parseInt(value, 10);
  42591. }
  42592. },
  42593. property: {default: ''},
  42594. startEvents: {type: 'array'},
  42595. pauseEvents: {type: 'array'},
  42596. resumeEvents: {type: 'array'},
  42597. round: {default: false},
  42598. to: {default: ''},
  42599. type: {default: ''},
  42600. isRawProperty: {default: false}
  42601. },
  42602. multiple: true,
  42603. init: function () {
  42604. var self = this;
  42605. this.eventDetail = {name: this.attrName};
  42606. this.time = 0;
  42607. this.animation = null;
  42608. this.animationIsPlaying = false;
  42609. this.onStartEvent = this.onStartEvent.bind(this);
  42610. this.beginAnimation = this.beginAnimation.bind(this);
  42611. this.pauseAnimation = this.pauseAnimation.bind(this);
  42612. this.resumeAnimation = this.resumeAnimation.bind(this);
  42613. this.fromColor = {};
  42614. this.toColor = {};
  42615. this.targets = {};
  42616. this.targetsArray = [];
  42617. this.updateConfigForDefault = this.updateConfigForDefault.bind(this);
  42618. this.updateConfigForRawColor = this.updateConfigForRawColor.bind(this);
  42619. this.config = {
  42620. complete: function () {
  42621. self.animationIsPlaying = false;
  42622. self.el.emit('animationcomplete', self.eventDetail, false);
  42623. if (self.id) {
  42624. self.el.emit('animationcomplete__' + self.id, self.eventDetail, false);
  42625. }
  42626. }
  42627. };
  42628. },
  42629. update: function (oldData) {
  42630. var config = this.config;
  42631. var data = this.data;
  42632. this.animationIsPlaying = false;
  42633. if (!this.data.enabled) { return; }
  42634. if (!data.property) { return; }
  42635. // Base config.
  42636. config.autoplay = false;
  42637. config.direction = data.dir;
  42638. config.duration = data.dur;
  42639. config.easing = data.easing;
  42640. config.elasticity = data.elasticity;
  42641. config.loop = data.loop;
  42642. config.round = data.round;
  42643. // Start new animation.
  42644. this.createAndStartAnimation();
  42645. },
  42646. tick: function (t, dt) {
  42647. if (!this.animationIsPlaying) { return; }
  42648. this.time += dt;
  42649. this.animation.tick(this.time);
  42650. },
  42651. remove: function () {
  42652. this.pauseAnimation();
  42653. this.removeEventListeners();
  42654. },
  42655. pause: function () {
  42656. this.paused = true;
  42657. this.pausedWasPlaying = this.animationIsPlaying;
  42658. this.pauseAnimation();
  42659. this.removeEventListeners();
  42660. },
  42661. /**
  42662. * `play` handler only for resuming scene.
  42663. */
  42664. play: function () {
  42665. if (!this.paused) { return; }
  42666. this.paused = false;
  42667. this.addEventListeners();
  42668. if (this.pausedWasPlaying) {
  42669. this.resumeAnimation();
  42670. this.pausedWasPlaying = false;
  42671. }
  42672. },
  42673. /**
  42674. * Start animation from scratch.
  42675. */
  42676. createAndStartAnimation: function () {
  42677. var data = this.data;
  42678. this.updateConfig();
  42679. this.animationIsPlaying = false;
  42680. this.animation = anime(this.config);
  42681. this.removeEventListeners();
  42682. this.addEventListeners();
  42683. // Wait for start events for animation.
  42684. if (!data.autoplay || data.startEvents && data.startEvents.length) { return; }
  42685. // Delay animation.
  42686. if (data.delay) {
  42687. setTimeout(this.beginAnimation, data.delay);
  42688. return;
  42689. }
  42690. // Play animation.
  42691. this.beginAnimation();
  42692. },
  42693. /**
  42694. * This is before animation start (including from startEvents).
  42695. * Set to initial state (config.from, time = 0, seekTime = 0).
  42696. */
  42697. beginAnimation: function () {
  42698. this.updateConfig();
  42699. this.time = 0;
  42700. this.animationIsPlaying = true;
  42701. this.stopRelatedAnimations();
  42702. this.el.emit('animationbegin', this.eventDetail);
  42703. },
  42704. pauseAnimation: function () {
  42705. this.animationIsPlaying = false;
  42706. },
  42707. resumeAnimation: function () {
  42708. this.animationIsPlaying = true;
  42709. },
  42710. /**
  42711. * startEvents callback.
  42712. */
  42713. onStartEvent: function () {
  42714. if (!this.data.enabled) { return; }
  42715. this.updateConfig();
  42716. if (this.animation) {
  42717. this.animation.pause();
  42718. }
  42719. this.animation = anime(this.config);
  42720. // Include the delay before each start event.
  42721. if (this.data.delay) {
  42722. setTimeout(this.beginAnimation, this.data.delay);
  42723. return;
  42724. }
  42725. this.beginAnimation();
  42726. },
  42727. /**
  42728. * rawProperty: true and type: color;
  42729. */
  42730. updateConfigForRawColor: function () {
  42731. var config = this.config;
  42732. var data = this.data;
  42733. var el = this.el;
  42734. var from;
  42735. var key;
  42736. var to;
  42737. if (this.waitComponentInitRawProperty(this.updateConfigForRawColor)) {
  42738. return;
  42739. }
  42740. from = data.from === '' ? getRawProperty(el, data.property) : data.from;
  42741. to = data.to;
  42742. // Use r/g/b vector for color type.
  42743. this.setColorConfig(from, to);
  42744. from = this.fromColor;
  42745. to = this.toColor;
  42746. this.targetsArray.length = 0;
  42747. this.targetsArray.push(from);
  42748. config.targets = this.targetsArray;
  42749. for (key in to) { config[key] = to[key]; }
  42750. config.update = (function () {
  42751. var lastValue = {};
  42752. return function (anim) {
  42753. var value;
  42754. value = anim.animatables[0].target;
  42755. // For animation timeline.
  42756. if (value.r === lastValue.r &&
  42757. value.g === lastValue.g &&
  42758. value.b === lastValue.b) { return; }
  42759. setRawProperty(el, data.property, value, data.type);
  42760. };
  42761. })();
  42762. },
  42763. /**
  42764. * Stuff property into generic `property` key.
  42765. */
  42766. updateConfigForDefault: function () {
  42767. var config = this.config;
  42768. var data = this.data;
  42769. var el = this.el;
  42770. var from;
  42771. var isBoolean;
  42772. var isNumber;
  42773. var to;
  42774. if (this.waitComponentInitRawProperty(this.updateConfigForDefault)) {
  42775. return;
  42776. }
  42777. if (data.from === '') {
  42778. // Infer from.
  42779. from = isRawProperty(data)
  42780. ? getRawProperty(el, data.property)
  42781. : getComponentProperty(el, data.property);
  42782. } else {
  42783. // Explicit from.
  42784. from = data.from;
  42785. }
  42786. to = data.to;
  42787. isNumber = !isNaN(from || to);
  42788. if (isNumber) {
  42789. from = parseFloat(from);
  42790. to = parseFloat(to);
  42791. } else {
  42792. from = from ? from.toString() : from;
  42793. to = to ? to.toString() : to;
  42794. }
  42795. // Convert booleans to integer to allow boolean flipping.
  42796. isBoolean = data.to === 'true' || data.to === 'false' ||
  42797. data.to === true || data.to === false;
  42798. if (isBoolean) {
  42799. from = data.from === 'true' || data.from === true ? 1 : 0;
  42800. to = data.to === 'true' || data.to === true ? 1 : 0;
  42801. }
  42802. this.targets.aframeProperty = from;
  42803. config.targets = this.targets;
  42804. config.aframeProperty = to;
  42805. config.update = (function () {
  42806. var lastValue;
  42807. return function (anim) {
  42808. var value;
  42809. value = anim.animatables[0].target.aframeProperty;
  42810. // Need to do a last value check for animation timeline since all the tweening
  42811. // begins simultaenously even if the value has not changed. Also better for perf
  42812. // anyways.
  42813. if (value === lastValue) { return; }
  42814. lastValue = value;
  42815. if (isBoolean) { value = value >= 1; }
  42816. if (isRawProperty(data)) {
  42817. setRawProperty(el, data.property, value, data.type);
  42818. } else {
  42819. setComponentProperty(el, data.property, value);
  42820. }
  42821. };
  42822. })();
  42823. },
  42824. /**
  42825. * Extend x/y/z/w onto the config.
  42826. * Update vector by modifying object3D.
  42827. */
  42828. updateConfigForVector: function () {
  42829. var config = this.config;
  42830. var data = this.data;
  42831. var el = this.el;
  42832. var key;
  42833. var from;
  42834. var to;
  42835. // Parse coordinates.
  42836. from = data.from !== ''
  42837. ? utils.coordinates.parse(data.from) // If data.from defined, use that.
  42838. : getComponentProperty(el, data.property); // If data.from not defined, get on the fly.
  42839. to = utils.coordinates.parse(data.to);
  42840. if (data.property === PROP_ROTATION) {
  42841. toRadians(from);
  42842. toRadians(to);
  42843. }
  42844. // Set to and from.
  42845. this.targetsArray.length = 0;
  42846. this.targetsArray.push(from);
  42847. config.targets = this.targetsArray;
  42848. for (key in to) { config[key] = to[key]; }
  42849. // If animating object3D transformation, run more optimized updater.
  42850. if (data.property === PROP_POSITION || data.property === PROP_ROTATION ||
  42851. data.property === PROP_SCALE) {
  42852. config.update = (function () {
  42853. var lastValue = {};
  42854. return function (anim) {
  42855. var value = anim.animatables[0].target;
  42856. if (data.property === PROP_SCALE) {
  42857. value.x = Math.max(0.0001, value.x);
  42858. value.y = Math.max(0.0001, value.y);
  42859. value.z = Math.max(0.0001, value.z);
  42860. }
  42861. // For animation timeline.
  42862. if (value.x === lastValue.x &&
  42863. value.y === lastValue.y &&
  42864. value.z === lastValue.z) { return; }
  42865. lastValue.x = value.x;
  42866. lastValue.y = value.y;
  42867. lastValue.z = value.z;
  42868. el.object3D[data.property].set(value.x, value.y, value.z);
  42869. };
  42870. })();
  42871. return;
  42872. }
  42873. // Animating some vector.
  42874. config.update = (function () {
  42875. var lastValue = {};
  42876. return function (anim) {
  42877. var value = anim.animations[0].target;
  42878. // Animate rotation through radians.
  42879. // For animation timeline.
  42880. if (value.x === lastValue.x &&
  42881. value.y === lastValue.y &&
  42882. value.z === lastValue.z) { return; }
  42883. lastValue.x = value.x;
  42884. lastValue.y = value.y;
  42885. lastValue.z = value.z;
  42886. setComponentProperty(el, data.property, value);
  42887. };
  42888. })();
  42889. },
  42890. /**
  42891. * Update the config before each run.
  42892. */
  42893. updateConfig: function () {
  42894. var propType;
  42895. // Route config type.
  42896. propType = getPropertyType(this.el, this.data.property);
  42897. if (isRawProperty(this.data) && this.data.type === TYPE_COLOR) {
  42898. this.updateConfigForRawColor();
  42899. } else if (propType === 'vec2' || propType === 'vec3' || propType === 'vec4') {
  42900. this.updateConfigForVector();
  42901. } else {
  42902. this.updateConfigForDefault();
  42903. }
  42904. },
  42905. /**
  42906. * Wait for component to initialize.
  42907. */
  42908. waitComponentInitRawProperty: function (cb) {
  42909. var componentName;
  42910. var data = this.data;
  42911. var el = this.el;
  42912. var self = this;
  42913. if (data.from !== '') { return false; }
  42914. if (!data.property.startsWith(STRING_COMPONENTS)) { return false; }
  42915. componentName = splitDot(data.property)[1];
  42916. if (el.components[componentName]) { return false; }
  42917. el.addEventListener('componentinitialized', function wait (evt) {
  42918. if (evt.detail.name !== componentName) { return; }
  42919. cb();
  42920. // Since the config was created async, create the animation now since we missed it
  42921. // earlier.
  42922. self.animation = anime(self.config);
  42923. el.removeEventListener('componentinitialized', wait);
  42924. });
  42925. return true;
  42926. },
  42927. /**
  42928. * Make sure two animations on the same property don't fight each other.
  42929. * e.g., animation__mouseenter="property: material.opacity"
  42930. * animation__mouseleave="property: material.opacity"
  42931. */
  42932. stopRelatedAnimations: function () {
  42933. var component;
  42934. var componentName;
  42935. for (componentName in this.el.components) {
  42936. component = this.el.components[componentName];
  42937. if (componentName === this.attrName) { continue; }
  42938. if (component.name !== 'animation') { continue; }
  42939. if (!component.animationIsPlaying) { continue; }
  42940. if (component.data.property !== this.data.property) { continue; }
  42941. component.animationIsPlaying = false;
  42942. }
  42943. },
  42944. addEventListeners: function () {
  42945. var data = this.data;
  42946. var el = this.el;
  42947. addEventListeners(el, data.startEvents, this.onStartEvent);
  42948. addEventListeners(el, data.pauseEvents, this.pauseAnimation);
  42949. addEventListeners(el, data.resumeEvents, this.resumeAnimation);
  42950. },
  42951. removeEventListeners: function () {
  42952. var data = this.data;
  42953. var el = this.el;
  42954. removeEventListeners(el, data.startEvents, this.onStartEvent);
  42955. removeEventListeners(el, data.pauseEvents, this.pauseAnimation);
  42956. removeEventListeners(el, data.resumeEvents, this.resumeAnimation);
  42957. },
  42958. setColorConfig: function (from, to) {
  42959. colorHelperFrom.set(from);
  42960. colorHelperTo.set(to);
  42961. from = this.fromColor;
  42962. to = this.toColor;
  42963. from.r = colorHelperFrom.r;
  42964. from.g = colorHelperFrom.g;
  42965. from.b = colorHelperFrom.b;
  42966. to.r = colorHelperTo.r;
  42967. to.g = colorHelperTo.g;
  42968. to.b = colorHelperTo.b;
  42969. }
  42970. });
  42971. /**
  42972. * Given property name, check schema to see what type we are animating.
  42973. * We just care whether the property is a vector.
  42974. */
  42975. function getPropertyType (el, property) {
  42976. var component;
  42977. var componentName;
  42978. var split;
  42979. var propertyName;
  42980. split = property.split('.');
  42981. componentName = split[0];
  42982. propertyName = split[1];
  42983. component = el.components[componentName] || components[componentName];
  42984. // Primitives.
  42985. if (!component) { return null; }
  42986. // Dynamic schema. We only care about vectors anyways.
  42987. if (propertyName && !component.schema[propertyName]) { return null; }
  42988. // Multi-prop.
  42989. if (propertyName) { return component.schema[propertyName].type; }
  42990. // Single-prop.
  42991. return component.schema.type;
  42992. }
  42993. /**
  42994. * Convert object to radians.
  42995. */
  42996. function toRadians (obj) {
  42997. obj.x = THREE.Math.degToRad(obj.x);
  42998. obj.y = THREE.Math.degToRad(obj.y);
  42999. obj.z = THREE.Math.degToRad(obj.z);
  43000. }
  43001. function addEventListeners (el, eventNames, handler) {
  43002. var i;
  43003. for (i = 0; i < eventNames.length; i++) {
  43004. el.addEventListener(eventNames[i], handler);
  43005. }
  43006. }
  43007. function removeEventListeners (el, eventNames, handler) {
  43008. var i;
  43009. for (i = 0; i < eventNames.length; i++) {
  43010. el.removeEventListener(eventNames[i], handler);
  43011. }
  43012. }
  43013. function getRawProperty (el, path) {
  43014. var i;
  43015. var split;
  43016. var value;
  43017. split = splitDot(path);
  43018. value = el;
  43019. for (i = 0; i < split.length; i++) {
  43020. value = value[split[i]];
  43021. }
  43022. return value;
  43023. }
  43024. function setRawProperty (el, path, value, type) {
  43025. var i;
  43026. var split;
  43027. var propertyName;
  43028. var targetValue;
  43029. if (path.startsWith('object3D.rotation')) {
  43030. value = THREE.Math.degToRad(value);
  43031. }
  43032. // Walk.
  43033. split = splitDot(path);
  43034. targetValue = el;
  43035. for (i = 0; i < split.length - 1; i++) { targetValue = targetValue[split[i]]; }
  43036. propertyName = split[split.length - 1];
  43037. // Raw color.
  43038. if (type === TYPE_COLOR) {
  43039. if ('r' in targetValue[propertyName]) {
  43040. targetValue[propertyName].r = value.r;
  43041. targetValue[propertyName].g = value.g;
  43042. targetValue[propertyName].b = value.b;
  43043. } else {
  43044. targetValue[propertyName].x = value.r;
  43045. targetValue[propertyName].y = value.g;
  43046. targetValue[propertyName].z = value.b;
  43047. }
  43048. return;
  43049. }
  43050. targetValue[propertyName] = value;
  43051. }
  43052. function splitDot (path) {
  43053. if (path in splitCache) { return splitCache[path]; }
  43054. splitCache[path] = path.split('.');
  43055. return splitCache[path];
  43056. }
  43057. function isRawProperty (data) {
  43058. return data.isRawProperty || data.property.startsWith(STRING_COMPONENTS) ||
  43059. data.property.startsWith(STRING_OBJECT3D);
  43060. }
  43061. },{"../core/component":105,"../lib/three":154,"../utils":178,"animejs":2}],53:[function(_dereq_,module,exports){
  43062. var registerComponent = _dereq_('../core/component').registerComponent;
  43063. var THREE = _dereq_('../lib/three');
  43064. /**
  43065. * Camera component.
  43066. * Pairs along with camera system to handle tracking the active camera.
  43067. */
  43068. module.exports.Component = registerComponent('camera', {
  43069. schema: {
  43070. active: {default: true},
  43071. far: {default: 10000},
  43072. fov: {default: 80, min: 0},
  43073. near: {default: 0.005, min: 0},
  43074. spectator: {default: false},
  43075. zoom: {default: 1, min: 0}
  43076. },
  43077. /**
  43078. * Initialize three.js camera and add it to the entity.
  43079. * Add reference from scene to this entity as the camera.
  43080. */
  43081. init: function () {
  43082. var camera;
  43083. var el = this.el;
  43084. // Create camera.
  43085. camera = this.camera = new THREE.PerspectiveCamera();
  43086. el.setObject3D('camera', camera);
  43087. },
  43088. /**
  43089. * Update three.js camera.
  43090. */
  43091. update: function (oldData) {
  43092. var data = this.data;
  43093. var camera = this.camera;
  43094. // Update properties.
  43095. camera.aspect = data.aspect || (window.innerWidth / window.innerHeight);
  43096. camera.far = data.far;
  43097. camera.fov = data.fov;
  43098. camera.near = data.near;
  43099. camera.zoom = data.zoom;
  43100. camera.updateProjectionMatrix();
  43101. this.updateActiveCamera(oldData);
  43102. this.updateSpectatorCamera(oldData);
  43103. },
  43104. updateActiveCamera: function (oldData) {
  43105. var data = this.data;
  43106. var el = this.el;
  43107. var system = this.system;
  43108. // Active property did not change.
  43109. if (oldData && oldData.active === data.active || data.spectator) { return; }
  43110. // If `active` property changes, or first update, handle active camera with system.
  43111. if (data.active && system.activeCameraEl !== el) {
  43112. // Camera enabled. Set camera to this camera.
  43113. system.setActiveCamera(el);
  43114. } else if (!data.active && system.activeCameraEl === el) {
  43115. // Camera disabled. Set camera to another camera.
  43116. system.disableActiveCamera();
  43117. }
  43118. },
  43119. updateSpectatorCamera: function (oldData) {
  43120. var data = this.data;
  43121. var el = this.el;
  43122. var system = this.system;
  43123. // spectator property did not change.
  43124. if (oldData && oldData.spectator === data.spectator) { return; }
  43125. // If `spectator` property changes, or first update, handle spectator camera with system.
  43126. if (data.spectator && system.spectatorCameraEl !== el) {
  43127. // Camera enabled. Set camera to this camera.
  43128. system.setSpectatorCamera(el);
  43129. } else if (!data.spectator && system.spectatorCameraEl === el) {
  43130. // Camera disabled. Set camera to another camera.
  43131. system.disableSpectatorCamera();
  43132. }
  43133. },
  43134. /**
  43135. * Remove camera on remove (callback).
  43136. */
  43137. remove: function () {
  43138. this.el.removeObject3D('camera');
  43139. }
  43140. });
  43141. },{"../core/component":105,"../lib/three":154}],54:[function(_dereq_,module,exports){
  43142. var registerComponent = _dereq_('../core/component').registerComponent;
  43143. var THREE = _dereq_('../lib/three');
  43144. module.exports.Component = registerComponent('collada-model', {
  43145. schema: {type: 'asset'},
  43146. init: function () {
  43147. this.model = null;
  43148. this.loader = new THREE.ColladaLoader();
  43149. },
  43150. update: function () {
  43151. var self = this;
  43152. var el = this.el;
  43153. var src = this.data;
  43154. if (!src) { return; }
  43155. this.remove();
  43156. this.loader.load(src, function (colladaModel) {
  43157. self.model = colladaModel.scene;
  43158. el.setObject3D('mesh', self.model);
  43159. el.emit('model-loaded', {format: 'collada', model: self.model});
  43160. });
  43161. },
  43162. remove: function () {
  43163. if (!this.model) { return; }
  43164. this.el.removeObject3D('mesh');
  43165. }
  43166. });
  43167. },{"../core/component":105,"../lib/three":154}],55:[function(_dereq_,module,exports){
  43168. /* global THREE */
  43169. var registerComponent = _dereq_('../core/component').registerComponent;
  43170. var utils = _dereq_('../utils/');
  43171. var bind = utils.bind;
  43172. var EVENTS = {
  43173. CLICK: 'click',
  43174. FUSING: 'fusing',
  43175. MOUSEENTER: 'mouseenter',
  43176. MOUSEDOWN: 'mousedown',
  43177. MOUSELEAVE: 'mouseleave',
  43178. MOUSEUP: 'mouseup'
  43179. };
  43180. var STATES = {
  43181. FUSING: 'cursor-fusing',
  43182. HOVERING: 'cursor-hovering',
  43183. HOVERED: 'cursor-hovered'
  43184. };
  43185. var CANVAS_EVENTS = {
  43186. DOWN: ['mousedown', 'touchstart'],
  43187. UP: ['mouseup', 'touchend']
  43188. };
  43189. /**
  43190. * Cursor component. Applies the raycaster component specifically for starting the raycaster
  43191. * from the camera and pointing from camera's facing direction, and then only returning the
  43192. * closest intersection. Cursor can be fine-tuned by setting raycaster properties.
  43193. *
  43194. * @member {object} fuseTimeout - Timeout to trigger fuse-click.
  43195. * @member {Element} cursorDownEl - Entity that was last mousedowned during current click.
  43196. * @member {object} intersection - Attributes of the current intersection event, including
  43197. * 3D- and 2D-space coordinates. See: http://threejs.org/docs/api/core/Raycaster.html
  43198. * @member {Element} intersectedEl - Currently-intersected entity. Used to keep track to
  43199. * emit events when unintersecting.
  43200. */
  43201. module.exports.Component = registerComponent('cursor', {
  43202. dependencies: ['raycaster'],
  43203. schema: {
  43204. downEvents: {default: []},
  43205. fuse: {default: utils.device.isMobile()},
  43206. fuseTimeout: {default: 1500, min: 0},
  43207. upEvents: {default: []},
  43208. rayOrigin: {default: 'entity', oneOf: ['mouse', 'entity']}
  43209. },
  43210. init: function () {
  43211. var self = this;
  43212. this.fuseTimeout = undefined;
  43213. this.cursorDownEl = null;
  43214. this.intersectedEl = null;
  43215. this.canvasBounds = document.body.getBoundingClientRect();
  43216. // Debounce.
  43217. this.updateCanvasBounds = utils.debounce(function updateCanvasBounds () {
  43218. self.canvasBounds = self.el.sceneEl.canvas.getBoundingClientRect();
  43219. }, 500);
  43220. this.eventDetail = {};
  43221. this.intersectedEventDetail = {cursorEl: this.el};
  43222. // Bind methods.
  43223. this.onCursorDown = bind(this.onCursorDown, this);
  43224. this.onCursorUp = bind(this.onCursorUp, this);
  43225. this.onIntersection = bind(this.onIntersection, this);
  43226. this.onIntersectionCleared = bind(this.onIntersectionCleared, this);
  43227. this.onMouseMove = bind(this.onMouseMove, this);
  43228. },
  43229. update: function (oldData) {
  43230. if (this.data.rayOrigin === oldData.rayOrigin) { return; }
  43231. this.updateMouseEventListeners();
  43232. },
  43233. play: function () {
  43234. this.addEventListeners();
  43235. },
  43236. pause: function () {
  43237. this.removeEventListeners();
  43238. },
  43239. remove: function () {
  43240. var el = this.el;
  43241. el.removeState(STATES.HOVERING);
  43242. el.removeState(STATES.FUSING);
  43243. clearTimeout(this.fuseTimeout);
  43244. if (this.intersectedEl) { this.intersectedEl.removeState(STATES.HOVERED); }
  43245. this.removeEventListeners();
  43246. },
  43247. addEventListeners: function () {
  43248. var canvas;
  43249. var data = this.data;
  43250. var el = this.el;
  43251. var self = this;
  43252. function addCanvasListeners () {
  43253. canvas = el.sceneEl.canvas;
  43254. if (data.downEvents.length || data.upEvents.length) { return; }
  43255. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  43256. canvas.addEventListener(downEvent, self.onCursorDown);
  43257. });
  43258. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  43259. canvas.addEventListener(upEvent, self.onCursorUp);
  43260. });
  43261. }
  43262. canvas = el.sceneEl.canvas;
  43263. if (canvas) {
  43264. addCanvasListeners();
  43265. } else {
  43266. el.sceneEl.addEventListener('render-target-loaded', addCanvasListeners);
  43267. }
  43268. data.downEvents.forEach(function (downEvent) {
  43269. el.addEventListener(downEvent, self.onCursorDown);
  43270. });
  43271. data.upEvents.forEach(function (upEvent) {
  43272. el.addEventListener(upEvent, self.onCursorUp);
  43273. });
  43274. el.addEventListener('raycaster-intersection', this.onIntersection);
  43275. el.addEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  43276. el.sceneEl.addEventListener('rendererresize', this.updateCanvasBounds);
  43277. window.addEventListener('resize', this.updateCanvasBounds);
  43278. window.addEventListener('scroll', this.updateCanvasBounds);
  43279. this.updateMouseEventListeners();
  43280. },
  43281. removeEventListeners: function () {
  43282. var canvas;
  43283. var data = this.data;
  43284. var el = this.el;
  43285. var self = this;
  43286. canvas = el.sceneEl.canvas;
  43287. if (canvas && !data.downEvents.length && !data.upEvents.length) {
  43288. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  43289. canvas.removeEventListener(downEvent, self.onCursorDown);
  43290. });
  43291. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  43292. canvas.removeEventListener(upEvent, self.onCursorUp);
  43293. });
  43294. }
  43295. data.downEvents.forEach(function (downEvent) {
  43296. el.removeEventListener(downEvent, self.onCursorDown);
  43297. });
  43298. data.upEvents.forEach(function (upEvent) {
  43299. el.removeEventListener(upEvent, self.onCursorUp);
  43300. });
  43301. el.removeEventListener('raycaster-intersection', this.onIntersection);
  43302. el.removeEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  43303. canvas.removeEventListener('mousemove', this.onMouseMove);
  43304. canvas.removeEventListener('touchstart', this.onMouseMove);
  43305. canvas.removeEventListener('touchmove', this.onMouseMove);
  43306. el.sceneEl.removeEventListener('rendererresize', this.updateCanvasBounds);
  43307. window.removeEventListener('resize', this.updateCanvasBounds);
  43308. window.removeEventListener('scroll', this.updateCanvasBounds);
  43309. },
  43310. updateMouseEventListeners: function () {
  43311. var canvas;
  43312. var el = this.el;
  43313. canvas = el.sceneEl.canvas;
  43314. canvas.removeEventListener('mousemove', this.onMouseMove);
  43315. canvas.removeEventListener('touchmove', this.onMouseMove);
  43316. el.setAttribute('raycaster', 'useWorldCoordinates', false);
  43317. if (this.data.rayOrigin !== 'mouse') { return; }
  43318. canvas.addEventListener('mousemove', this.onMouseMove, false);
  43319. canvas.addEventListener('touchmove', this.onMouseMove, false);
  43320. el.setAttribute('raycaster', 'useWorldCoordinates', true);
  43321. this.updateCanvasBounds();
  43322. },
  43323. onMouseMove: (function () {
  43324. var direction = new THREE.Vector3();
  43325. var mouse = new THREE.Vector2();
  43326. var origin = new THREE.Vector3();
  43327. var rayCasterConfig = {origin: origin, direction: direction};
  43328. return function (evt) {
  43329. var bounds = this.canvasBounds;
  43330. var camera = this.el.sceneEl.camera;
  43331. var left;
  43332. var point;
  43333. var top;
  43334. camera.parent.updateMatrixWorld();
  43335. // Calculate mouse position based on the canvas element
  43336. if (evt.type === 'touchmove' || evt.type === 'touchstart') {
  43337. // Track the first touch for simplicity.
  43338. point = evt.touches.item(0);
  43339. } else {
  43340. point = evt;
  43341. }
  43342. left = point.clientX - bounds.left;
  43343. top = point.clientY - bounds.top;
  43344. mouse.x = (left / bounds.width) * 2 - 1;
  43345. mouse.y = -(top / bounds.height) * 2 + 1;
  43346. origin.setFromMatrixPosition(camera.matrixWorld);
  43347. direction.set(mouse.x, mouse.y, 0.5).unproject(camera).sub(origin).normalize();
  43348. this.el.setAttribute('raycaster', rayCasterConfig);
  43349. if (evt.type === 'touchmove') { evt.preventDefault(); }
  43350. };
  43351. })(),
  43352. /**
  43353. * Trigger mousedown and keep track of the mousedowned entity.
  43354. */
  43355. onCursorDown: function (evt) {
  43356. // Raycast again for touch.
  43357. if (this.data.rayOrigin === 'mouse' && evt.type === 'touchstart') {
  43358. this.onMouseMove(evt);
  43359. this.el.components.raycaster.checkIntersections();
  43360. evt.preventDefault();
  43361. }
  43362. this.twoWayEmit(EVENTS.MOUSEDOWN);
  43363. this.cursorDownEl = this.intersectedEl;
  43364. },
  43365. /**
  43366. * Trigger mouseup if:
  43367. * - Not fusing (mobile has no mouse).
  43368. * - Currently intersecting an entity.
  43369. * - Currently-intersected entity is the same as the one when mousedown was triggered,
  43370. * in case user mousedowned one entity, dragged to another, and mouseupped.
  43371. */
  43372. onCursorUp: function (evt) {
  43373. this.twoWayEmit(EVENTS.MOUSEUP);
  43374. // If intersected entity has changed since the cursorDown, still emit mouseUp on the
  43375. // previously cursorUp entity.
  43376. if (this.cursorDownEl && this.cursorDownEl !== this.intersectedEl) {
  43377. this.intersectedEventDetail.intersection = null;
  43378. this.cursorDownEl.emit(EVENTS.MOUSEUP, this.intersectedEventDetail);
  43379. }
  43380. if (!this.data.fuse && this.intersectedEl && this.cursorDownEl === this.intersectedEl) {
  43381. this.twoWayEmit(EVENTS.CLICK);
  43382. }
  43383. this.cursorDownEl = null;
  43384. if (evt.type === 'touchend') { evt.preventDefault(); }
  43385. },
  43386. /**
  43387. * Handle intersection.
  43388. */
  43389. onIntersection: function (evt) {
  43390. var currentIntersection;
  43391. var cursorEl = this.el;
  43392. var index;
  43393. var intersectedEl;
  43394. var intersection;
  43395. // Select closest object, excluding the cursor.
  43396. index = evt.detail.els[0] === cursorEl ? 1 : 0;
  43397. intersection = evt.detail.intersections[index];
  43398. intersectedEl = evt.detail.els[index];
  43399. // If cursor is the only intersected object, ignore the event.
  43400. if (!intersectedEl) { return; }
  43401. // Already intersecting this entity.
  43402. if (this.intersectedEl === intersectedEl) { return; }
  43403. // Ignore events further away than active intersection.
  43404. if (this.intersectedEl) {
  43405. currentIntersection = this.el.components.raycaster.getIntersection(this.intersectedEl);
  43406. if (currentIntersection && currentIntersection.distance <= intersection.distance) { return; }
  43407. }
  43408. // Unset current intersection.
  43409. this.clearCurrentIntersection(true);
  43410. this.setIntersection(intersectedEl, intersection);
  43411. },
  43412. /**
  43413. * Handle intersection cleared.
  43414. */
  43415. onIntersectionCleared: function (evt) {
  43416. var clearedEls = evt.detail.clearedEls;
  43417. // Check if the current intersection has ended
  43418. if (clearedEls.indexOf(this.intersectedEl) === -1) { return; }
  43419. this.clearCurrentIntersection();
  43420. },
  43421. setIntersection: function (intersectedEl, intersection) {
  43422. var cursorEl = this.el;
  43423. var data = this.data;
  43424. var self = this;
  43425. // Already intersecting.
  43426. if (this.intersectedEl === intersectedEl) { return; }
  43427. // Set new intersection.
  43428. this.intersectedEl = intersectedEl;
  43429. // Hovering.
  43430. cursorEl.addState(STATES.HOVERING);
  43431. intersectedEl.addState(STATES.HOVERED);
  43432. this.twoWayEmit(EVENTS.MOUSEENTER);
  43433. // Begin fuse if necessary.
  43434. if (data.fuseTimeout === 0 || !data.fuse) { return; }
  43435. cursorEl.addState(STATES.FUSING);
  43436. this.twoWayEmit(EVENTS.FUSING);
  43437. this.fuseTimeout = setTimeout(function fuse () {
  43438. cursorEl.removeState(STATES.FUSING);
  43439. self.twoWayEmit(EVENTS.CLICK);
  43440. }, data.fuseTimeout);
  43441. },
  43442. clearCurrentIntersection: function (ignoreRemaining) {
  43443. var index;
  43444. var intersection;
  43445. var intersections;
  43446. var cursorEl = this.el;
  43447. // Nothing to be cleared.
  43448. if (!this.intersectedEl) { return; }
  43449. // No longer hovering (or fusing).
  43450. this.intersectedEl.removeState(STATES.HOVERED);
  43451. cursorEl.removeState(STATES.HOVERING);
  43452. cursorEl.removeState(STATES.FUSING);
  43453. this.twoWayEmit(EVENTS.MOUSELEAVE);
  43454. // Unset intersected entity (after emitting the event).
  43455. this.intersectedEl = null;
  43456. // Clear fuseTimeout.
  43457. clearTimeout(this.fuseTimeout);
  43458. // Set intersection to another raycasted element if any.
  43459. if (ignoreRemaining === true) { return; }
  43460. intersections = this.el.components.raycaster.intersections;
  43461. if (intersections.length === 0) { return; }
  43462. // Exclude the cursor.
  43463. index = intersections[0].object.el === cursorEl ? 1 : 0;
  43464. intersection = intersections[index];
  43465. if (!intersection) { return; }
  43466. this.setIntersection(intersection.object.el, intersection);
  43467. },
  43468. /**
  43469. * Helper to emit on both the cursor and the intersected entity (if exists).
  43470. */
  43471. twoWayEmit: function (evtName) {
  43472. var el = this.el;
  43473. var intersectedEl = this.intersectedEl;
  43474. var intersection;
  43475. intersection = this.el.components.raycaster.getIntersection(intersectedEl);
  43476. this.eventDetail.intersectedEl = intersectedEl;
  43477. this.eventDetail.intersection = intersection;
  43478. el.emit(evtName, this.eventDetail);
  43479. if (!intersectedEl) { return; }
  43480. this.intersectedEventDetail.intersection = intersection;
  43481. intersectedEl.emit(evtName, this.intersectedEventDetail);
  43482. }
  43483. });
  43484. },{"../core/component":105,"../utils/":178}],56:[function(_dereq_,module,exports){
  43485. var registerComponent = _dereq_('../core/component').registerComponent;
  43486. var bind = _dereq_('../utils/bind');
  43487. var checkControllerPresentAndSetup = _dereq_('../utils/tracked-controls').checkControllerPresentAndSetup;
  43488. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  43489. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  43490. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  43491. var DAYDREAM_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/google/';
  43492. var DAYDREAM_CONTROLLER_MODEL_OBJ_URL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.obj';
  43493. var DAYDREAM_CONTROLLER_MODEL_OBJ_MTL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.mtl';
  43494. var GAMEPAD_ID_PREFIX = 'Daydream Controller';
  43495. /**
  43496. * Daydream controls.
  43497. * Interface with Daydream controller and map Gamepad events to
  43498. * controller buttons: trackpad, menu, system
  43499. * Load a controller model and highlight the pressed buttons.
  43500. */
  43501. module.exports.Component = registerComponent('daydream-controls', {
  43502. schema: {
  43503. hand: {default: ''}, // This informs the degenerate arm model.
  43504. buttonColor: {type: 'color', default: '#000000'},
  43505. buttonTouchedColor: {type: 'color', default: '#777777'},
  43506. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  43507. model: {default: true},
  43508. orientationOffset: {type: 'vec3'},
  43509. armModel: {default: true}
  43510. },
  43511. /**
  43512. * Button IDs:
  43513. * 0 - trackpad
  43514. * 1 - menu (never dispatched on this layer)
  43515. * 2 - system (never dispatched on this layer)
  43516. */
  43517. mapping: {
  43518. axes: {trackpad: [0, 1]},
  43519. buttons: ['trackpad', 'menu', 'system']
  43520. },
  43521. bindMethods: function () {
  43522. this.onModelLoaded = bind(this.onModelLoaded, this);
  43523. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  43524. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  43525. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  43526. this.onAxisMoved = bind(this.onAxisMoved, this);
  43527. },
  43528. init: function () {
  43529. var self = this;
  43530. this.animationActive = 'pointing';
  43531. this.onButtonChanged = bind(this.onButtonChanged, this);
  43532. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  43533. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  43534. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  43535. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  43536. this.onAxisMoved = bind(this.onAxisMoved, this);
  43537. this.controllerPresent = false;
  43538. this.lastControllerCheck = 0;
  43539. this.bindMethods();
  43540. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // To allow mock.
  43541. this.emitIfAxesChanged = emitIfAxesChanged; // To allow mock.
  43542. },
  43543. addEventListeners: function () {
  43544. var el = this.el;
  43545. el.addEventListener('buttonchanged', this.onButtonChanged);
  43546. el.addEventListener('buttondown', this.onButtonDown);
  43547. el.addEventListener('buttonup', this.onButtonUp);
  43548. el.addEventListener('touchstart', this.onButtonTouchStart);
  43549. el.addEventListener('touchend', this.onButtonTouchEnd);
  43550. el.addEventListener('model-loaded', this.onModelLoaded);
  43551. el.addEventListener('axismove', this.onAxisMoved);
  43552. this.controllerEventsActive = true;
  43553. },
  43554. removeEventListeners: function () {
  43555. var el = this.el;
  43556. el.removeEventListener('buttonchanged', this.onButtonChanged);
  43557. el.removeEventListener('buttondown', this.onButtonDown);
  43558. el.removeEventListener('buttonup', this.onButtonUp);
  43559. el.removeEventListener('touchstart', this.onButtonTouchStart);
  43560. el.removeEventListener('touchend', this.onButtonTouchEnd);
  43561. el.removeEventListener('model-loaded', this.onModelLoaded);
  43562. el.removeEventListener('axismove', this.onAxisMoved);
  43563. this.controllerEventsActive = false;
  43564. },
  43565. checkIfControllerPresent: function () {
  43566. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {hand: this.data.hand});
  43567. },
  43568. play: function () {
  43569. this.checkIfControllerPresent();
  43570. this.addControllersUpdateListener();
  43571. },
  43572. pause: function () {
  43573. this.removeEventListeners();
  43574. this.removeControllersUpdateListener();
  43575. },
  43576. injectTrackedControls: function () {
  43577. var el = this.el;
  43578. var data = this.data;
  43579. el.setAttribute('tracked-controls', {
  43580. armModel: data.armModel,
  43581. hand: data.hand,
  43582. idPrefix: GAMEPAD_ID_PREFIX,
  43583. orientationOffset: data.orientationOffset
  43584. });
  43585. if (!this.data.model) { return; }
  43586. this.el.setAttribute('obj-model', {
  43587. obj: DAYDREAM_CONTROLLER_MODEL_OBJ_URL,
  43588. mtl: DAYDREAM_CONTROLLER_MODEL_OBJ_MTL
  43589. });
  43590. },
  43591. addControllersUpdateListener: function () {
  43592. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  43593. },
  43594. removeControllersUpdateListener: function () {
  43595. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  43596. },
  43597. onControllersUpdate: function () {
  43598. this.checkIfControllerPresent();
  43599. },
  43600. onModelLoaded: function (evt) {
  43601. var controllerObject3D = evt.detail.model;
  43602. var buttonMeshes;
  43603. if (!this.data.model) { return; }
  43604. buttonMeshes = this.buttonMeshes = {};
  43605. buttonMeshes.menu = controllerObject3D.getObjectByName('AppButton_AppButton_Cylinder.004');
  43606. buttonMeshes.system = controllerObject3D.getObjectByName('HomeButton_HomeButton_Cylinder.005');
  43607. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad_TouchPad_Cylinder.003');
  43608. // Offset pivot point.
  43609. controllerObject3D.position.set(0, 0, -0.04);
  43610. },
  43611. onAxisMoved: function (evt) {
  43612. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  43613. },
  43614. onButtonChanged: function (evt) {
  43615. var button = this.mapping.buttons[evt.detail.id];
  43616. if (!button) return;
  43617. // Pass along changed event with button state, using button mapping for convenience.
  43618. this.el.emit(button + 'changed', evt.detail.state);
  43619. },
  43620. updateModel: function (buttonName, evtName) {
  43621. if (!this.data.model) { return; }
  43622. this.updateButtonModel(buttonName, evtName);
  43623. },
  43624. updateButtonModel: function (buttonName, state) {
  43625. var buttonMeshes = this.buttonMeshes;
  43626. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  43627. var color;
  43628. switch (state) {
  43629. case 'down':
  43630. color = this.data.buttonHighlightColor;
  43631. break;
  43632. case 'touchstart':
  43633. color = this.data.buttonTouchedColor;
  43634. break;
  43635. default:
  43636. color = this.data.buttonColor;
  43637. }
  43638. buttonMeshes[buttonName].material.color.set(color);
  43639. }
  43640. });
  43641. },{"../core/component":105,"../utils/bind":172,"../utils/tracked-controls":185}],57:[function(_dereq_,module,exports){
  43642. var registerComponent = _dereq_('../core/component').registerComponent;
  43643. var bind = _dereq_('../utils/bind');
  43644. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  43645. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  43646. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  43647. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  43648. var GEARVR_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/samsung/';
  43649. var GEARVR_CONTROLLER_MODEL_OBJ_URL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.obj';
  43650. var GEARVR_CONTROLLER_MODEL_OBJ_MTL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.mtl';
  43651. var GAMEPAD_ID_PREFIX = 'Gear VR';
  43652. /**
  43653. * Gear VR controls.
  43654. * Interface with Gear VR controller and map Gamepad events to
  43655. * controller buttons: trackpad, trigger
  43656. * Load a controller model and highlight the pressed buttons.
  43657. */
  43658. module.exports.Component = registerComponent('gearvr-controls', {
  43659. schema: {
  43660. hand: {default: ''}, // This informs the degenerate arm model.
  43661. buttonColor: {type: 'color', default: '#000000'},
  43662. buttonTouchedColor: {type: 'color', default: '#777777'},
  43663. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  43664. model: {default: true},
  43665. orientationOffset: {type: 'vec3'},
  43666. armModel: {default: true}
  43667. },
  43668. /**
  43669. * Button IDs:
  43670. * 0 - trackpad
  43671. * 1 - trigger
  43672. */
  43673. mapping: {
  43674. axes: {trackpad: [0, 1]},
  43675. buttons: ['trackpad', 'trigger']
  43676. },
  43677. bindMethods: function () {
  43678. this.onModelLoaded = bind(this.onModelLoaded, this);
  43679. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  43680. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  43681. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  43682. this.onAxisMoved = bind(this.onAxisMoved, this);
  43683. },
  43684. init: function () {
  43685. var self = this;
  43686. this.animationActive = 'pointing';
  43687. this.onButtonChanged = bind(this.onButtonChanged, this);
  43688. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  43689. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  43690. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  43691. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  43692. this.onAxisMoved = bind(this.onAxisMoved, this);
  43693. this.controllerPresent = false;
  43694. this.lastControllerCheck = 0;
  43695. this.bindMethods();
  43696. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // To allow mock.
  43697. this.emitIfAxesChanged = emitIfAxesChanged; // To allow mock.
  43698. },
  43699. addEventListeners: function () {
  43700. var el = this.el;
  43701. el.addEventListener('buttonchanged', this.onButtonChanged);
  43702. el.addEventListener('buttondown', this.onButtonDown);
  43703. el.addEventListener('buttonup', this.onButtonUp);
  43704. el.addEventListener('touchstart', this.onButtonTouchStart);
  43705. el.addEventListener('touchend', this.onButtonTouchEnd);
  43706. el.addEventListener('model-loaded', this.onModelLoaded);
  43707. el.addEventListener('axismove', this.onAxisMoved);
  43708. this.controllerEventsActive = true;
  43709. },
  43710. removeEventListeners: function () {
  43711. var el = this.el;
  43712. el.removeEventListener('buttonchanged', this.onButtonChanged);
  43713. el.removeEventListener('buttondown', this.onButtonDown);
  43714. el.removeEventListener('buttonup', this.onButtonUp);
  43715. el.removeEventListener('touchstart', this.onButtonTouchStart);
  43716. el.removeEventListener('touchend', this.onButtonTouchEnd);
  43717. el.removeEventListener('model-loaded', this.onModelLoaded);
  43718. el.removeEventListener('axismove', this.onAxisMoved);
  43719. this.controllerEventsActive = false;
  43720. },
  43721. checkIfControllerPresent: function () {
  43722. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  43723. this.data.hand ? {hand: this.data.hand} : {});
  43724. },
  43725. play: function () {
  43726. this.checkIfControllerPresent();
  43727. this.addControllersUpdateListener();
  43728. },
  43729. pause: function () {
  43730. this.removeEventListeners();
  43731. this.removeControllersUpdateListener();
  43732. },
  43733. injectTrackedControls: function () {
  43734. var el = this.el;
  43735. var data = this.data;
  43736. el.setAttribute('tracked-controls', {
  43737. armModel: data.armModel,
  43738. idPrefix: GAMEPAD_ID_PREFIX,
  43739. orientationOffset: data.orientationOffset
  43740. });
  43741. if (!this.data.model) { return; }
  43742. this.el.setAttribute('obj-model', {
  43743. obj: GEARVR_CONTROLLER_MODEL_OBJ_URL,
  43744. mtl: GEARVR_CONTROLLER_MODEL_OBJ_MTL
  43745. });
  43746. },
  43747. addControllersUpdateListener: function () {
  43748. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  43749. },
  43750. removeControllersUpdateListener: function () {
  43751. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  43752. },
  43753. onControllersUpdate: function () {
  43754. this.checkIfControllerPresent();
  43755. },
  43756. // No need for onButtonChanged, since Gear VR controller has no analog buttons.
  43757. onModelLoaded: function (evt) {
  43758. var controllerObject3D = evt.detail.model;
  43759. var buttonMeshes;
  43760. if (!this.data.model) { return; }
  43761. buttonMeshes = this.buttonMeshes = {};
  43762. buttonMeshes.trigger = controllerObject3D.children[2];
  43763. buttonMeshes.trackpad = controllerObject3D.children[1];
  43764. },
  43765. onButtonChanged: function (evt) {
  43766. var button = this.mapping.buttons[evt.detail.id];
  43767. if (!button) return;
  43768. // Pass along changed event with button state, using button mapping for convenience.
  43769. this.el.emit(button + 'changed', evt.detail.state);
  43770. },
  43771. onAxisMoved: function (evt) {
  43772. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  43773. },
  43774. updateModel: function (buttonName, evtName) {
  43775. if (!this.data.model) { return; }
  43776. this.updateButtonModel(buttonName, evtName);
  43777. },
  43778. updateButtonModel: function (buttonName, state) {
  43779. var buttonMeshes = this.buttonMeshes;
  43780. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  43781. var color;
  43782. switch (state) {
  43783. case 'down':
  43784. color = this.data.buttonHighlightColor;
  43785. break;
  43786. case 'touchstart':
  43787. color = this.data.buttonTouchedColor;
  43788. break;
  43789. default:
  43790. color = this.data.buttonColor;
  43791. }
  43792. buttonMeshes[buttonName].material.color.set(color);
  43793. }
  43794. });
  43795. },{"../core/component":105,"../utils/bind":172,"../utils/tracked-controls":185}],58:[function(_dereq_,module,exports){
  43796. var geometries = _dereq_('../core/geometry').geometries;
  43797. var geometryNames = _dereq_('../core/geometry').geometryNames;
  43798. var registerComponent = _dereq_('../core/component').registerComponent;
  43799. var THREE = _dereq_('../lib/three');
  43800. var dummyGeometry = new THREE.Geometry();
  43801. /**
  43802. * Geometry component. Combined with material component to make a mesh in 3D object.
  43803. * Extended with registered geometries.
  43804. */
  43805. module.exports.Component = registerComponent('geometry', {
  43806. schema: {
  43807. buffer: {default: true},
  43808. primitive: {default: 'box', oneOf: geometryNames, schemaChange: true},
  43809. skipCache: {default: false}
  43810. },
  43811. init: function () {
  43812. this.geometry = null;
  43813. },
  43814. /**
  43815. * Talk to geometry system to get or create geometry.
  43816. */
  43817. update: function (previousData) {
  43818. var data = this.data;
  43819. var el = this.el;
  43820. var mesh;
  43821. var system = this.system;
  43822. // Dispose old geometry if we created one.
  43823. if (this.geometry) {
  43824. system.unuseGeometry(previousData);
  43825. this.geometry = null;
  43826. }
  43827. // Create new geometry.
  43828. this.geometry = system.getOrCreateGeometry(data);
  43829. // Set on mesh. If mesh does not exist, create it.
  43830. mesh = el.getObject3D('mesh');
  43831. if (mesh) {
  43832. mesh.geometry = this.geometry;
  43833. } else {
  43834. mesh = new THREE.Mesh();
  43835. mesh.geometry = this.geometry;
  43836. el.setObject3D('mesh', mesh);
  43837. }
  43838. },
  43839. /**
  43840. * Tell geometry system that entity is no longer using the geometry.
  43841. * Unset the geometry on the mesh
  43842. */
  43843. remove: function () {
  43844. this.system.unuseGeometry(this.data);
  43845. this.el.getObject3D('mesh').geometry = dummyGeometry;
  43846. this.geometry = null;
  43847. },
  43848. /**
  43849. * Update geometry component schema based on geometry type.
  43850. */
  43851. updateSchema: function (data) {
  43852. var currentGeometryType = this.oldData && this.oldData.primitive;
  43853. var newGeometryType = data.primitive;
  43854. var schema = geometries[newGeometryType] && geometries[newGeometryType].schema;
  43855. // Geometry has no schema.
  43856. if (!schema) { throw new Error('Unknown geometry schema `' + newGeometryType + '`'); }
  43857. // Nothing has changed.
  43858. if (currentGeometryType && currentGeometryType === newGeometryType) { return; }
  43859. this.extendSchema(schema);
  43860. }
  43861. });
  43862. },{"../core/component":105,"../core/geometry":106,"../lib/three":154}],59:[function(_dereq_,module,exports){
  43863. var registerComponent = _dereq_('../core/component').registerComponent;
  43864. var THREE = _dereq_('../lib/three');
  43865. var utils = _dereq_('../utils/');
  43866. var warn = utils.debug('components:gltf-model:warn');
  43867. /**
  43868. * glTF model loader.
  43869. */
  43870. module.exports.Component = registerComponent('gltf-model', {
  43871. schema: {type: 'model'},
  43872. init: function () {
  43873. var dracoLoader = this.system.getDRACOLoader();
  43874. this.model = null;
  43875. this.loader = new THREE.GLTFLoader();
  43876. if (dracoLoader) {
  43877. this.loader.setDRACOLoader(dracoLoader);
  43878. }
  43879. },
  43880. update: function () {
  43881. var self = this;
  43882. var el = this.el;
  43883. var src = this.data;
  43884. if (!src) { return; }
  43885. this.remove();
  43886. this.loader.load(src, function gltfLoaded (gltfModel) {
  43887. self.model = gltfModel.scene || gltfModel.scenes[0];
  43888. self.model.animations = gltfModel.animations;
  43889. el.setObject3D('mesh', self.model);
  43890. el.emit('model-loaded', {format: 'gltf', model: self.model});
  43891. }, undefined /* onProgress */, function gltfFailed (error) {
  43892. var message = (error && error.message) ? error.message : 'Failed to load glTF model';
  43893. warn(message);
  43894. el.emit('model-error', {format: 'gltf', src: src});
  43895. });
  43896. },
  43897. remove: function () {
  43898. if (!this.model) { return; }
  43899. this.el.removeObject3D('mesh');
  43900. }
  43901. });
  43902. },{"../core/component":105,"../lib/three":154,"../utils/":178}],60:[function(_dereq_,module,exports){
  43903. /* global THREE */
  43904. var registerComponent = _dereq_('../core/component').registerComponent;
  43905. // Found at https://github.com/aframevr/assets.
  43906. var MODEL_URLS = {
  43907. left: 'https://cdn.aframe.io/controllers/oculus-hands/v2/leftHand.json',
  43908. right: 'https://cdn.aframe.io/controllers/oculus-hands/v2/rightHand.json'
  43909. };
  43910. // Poses.
  43911. var ANIMATIONS = {
  43912. open: 'Open',
  43913. // point: grip active, trackpad surface active, trigger inactive.
  43914. point: 'Point',
  43915. // pointThumb: grip active, trigger inactive, trackpad surface inactive.
  43916. pointThumb: 'Point + Thumb',
  43917. // fist: grip active, trigger active, trackpad surface active.
  43918. fist: 'Fist',
  43919. // hold: trigger active, grip inactive.
  43920. hold: 'Hold',
  43921. // thumbUp: grip active, trigger active, trackpad surface inactive.
  43922. thumbUp: 'Thumb Up'
  43923. };
  43924. // Map animation to public events for the API.
  43925. var EVENTS = {};
  43926. EVENTS[ANIMATIONS.fist] = 'grip';
  43927. EVENTS[ANIMATIONS.thumbUp] = 'pistol';
  43928. EVENTS[ANIMATIONS.point] = 'pointing';
  43929. EVENTS[ANIMATIONS.thumb] = 'thumb';
  43930. /**
  43931. * Hand controls component that abstracts 6DoF controls:
  43932. * oculus-touch-controls, vive-controls, windows-motion-controls.
  43933. *
  43934. * Originally meant to be a sample implementation of applications-specific controls that
  43935. * abstracts multiple types of controllers.
  43936. *
  43937. * Auto-detect appropriate controller.
  43938. * Handle common events coming from the detected vendor-specific controls.
  43939. * Translate button events to semantic hand-related event names:
  43940. * (gripclose, gripopen, thumbup, thumbdown, pointup, pointdown)
  43941. * Load hand model with gestures that are applied based on the button pressed.
  43942. *
  43943. * @property {string} Hand mapping (`left`, `right`).
  43944. */
  43945. module.exports.Component = registerComponent('hand-controls', {
  43946. schema: {default: 'left'},
  43947. init: function () {
  43948. var self = this;
  43949. var el = this.el;
  43950. // Current pose.
  43951. this.gesture = ANIMATIONS.open;
  43952. // Active buttons populated by events provided by the attached controls.
  43953. this.pressedButtons = {};
  43954. this.touchedButtons = {};
  43955. this.loader = new THREE.ObjectLoader();
  43956. this.loader.setCrossOrigin('anonymous');
  43957. this.onGripDown = function () { self.handleButton('grip', 'down'); };
  43958. this.onGripUp = function () { self.handleButton('grip', 'up'); };
  43959. this.onTrackpadDown = function () { self.handleButton('trackpad', 'down'); };
  43960. this.onTrackpadUp = function () { self.handleButton('trackpad', 'up'); };
  43961. this.onTrackpadTouchStart = function () { self.handleButton('trackpad', 'touchstart'); };
  43962. this.onTrackpadTouchEnd = function () { self.handleButton('trackpad', 'touchend'); };
  43963. this.onTriggerDown = function () { self.handleButton('trigger', 'down'); };
  43964. this.onTriggerUp = function () { self.handleButton('trigger', 'up'); };
  43965. this.onTriggerTouchStart = function () { self.handleButton('trigger', 'touchstart'); };
  43966. this.onTriggerTouchEnd = function () { self.handleButton('trigger', 'touchend'); };
  43967. this.onGripTouchStart = function () { self.handleButton('grip', 'touchstart'); };
  43968. this.onGripTouchEnd = function () { self.handleButton('grip', 'touchend'); };
  43969. this.onThumbstickDown = function () { self.handleButton('thumbstick', 'down'); };
  43970. this.onThumbstickUp = function () { self.handleButton('thumbstick', 'up'); };
  43971. this.onAorXTouchStart = function () { self.handleButton('AorX', 'touchstart'); };
  43972. this.onAorXTouchEnd = function () { self.handleButton('AorX', 'touchend'); };
  43973. this.onBorYTouchStart = function () { self.handleButton('BorY', 'touchstart'); };
  43974. this.onBorYTouchEnd = function () { self.handleButton('BorY', 'touchend'); };
  43975. this.onSurfaceTouchStart = function () { self.handleButton('surface', 'touchstart'); };
  43976. this.onSurfaceTouchEnd = function () { self.handleButton('surface', 'touchend'); };
  43977. el.addEventListener('controllerconnected', this.onControllerConnected);
  43978. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  43979. // Hidden by default.
  43980. el.object3D.visible = false;
  43981. },
  43982. play: function () {
  43983. this.addEventListeners();
  43984. },
  43985. pause: function () {
  43986. this.removeEventListeners();
  43987. },
  43988. tick: function (time, delta) {
  43989. var mesh = this.el.getObject3D('mesh');
  43990. if (!mesh || !mesh.mixer) { return; }
  43991. mesh.mixer.update(delta / 1000);
  43992. },
  43993. addEventListeners: function () {
  43994. var el = this.el;
  43995. el.addEventListener('gripdown', this.onGripDown);
  43996. el.addEventListener('gripup', this.onGripUp);
  43997. el.addEventListener('trackpaddown', this.onTrackpadDown);
  43998. el.addEventListener('trackpadup', this.onTrackpadUp);
  43999. el.addEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  44000. el.addEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  44001. el.addEventListener('triggerdown', this.onTriggerDown);
  44002. el.addEventListener('triggerup', this.onTriggerUp);
  44003. el.addEventListener('triggertouchstart', this.onTriggerTouchStart);
  44004. el.addEventListener('triggertouchend', this.onTriggerTouchEnd);
  44005. el.addEventListener('griptouchstart', this.onGripTouchStart);
  44006. el.addEventListener('griptouchend', this.onGripTouchEnd);
  44007. el.addEventListener('thumbstickdown', this.onThumbstickDown);
  44008. el.addEventListener('thumbstickup', this.onThumbstickUp);
  44009. el.addEventListener('abuttontouchstart', this.onAorXTouchStart);
  44010. el.addEventListener('abuttontouchend', this.onAorXTouchEnd);
  44011. el.addEventListener('bbuttontouchstart', this.onBorYTouchStart);
  44012. el.addEventListener('bbuttontouchend', this.onBorYTouchEnd);
  44013. el.addEventListener('xbuttontouchstart', this.onAorXTouchStart);
  44014. el.addEventListener('xbuttontouchend', this.onAorXTouchEnd);
  44015. el.addEventListener('ybuttontouchstart', this.onBorYTouchStart);
  44016. el.addEventListener('ybuttontouchend', this.onBorYTouchEnd);
  44017. el.addEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  44018. el.addEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  44019. },
  44020. removeEventListeners: function () {
  44021. var el = this.el;
  44022. el.removeEventListener('gripdown', this.onGripDown);
  44023. el.removeEventListener('gripup', this.onGripUp);
  44024. el.removeEventListener('trackpaddown', this.onTrackpadDown);
  44025. el.removeEventListener('trackpadup', this.onTrackpadUp);
  44026. el.removeEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  44027. el.removeEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  44028. el.removeEventListener('triggerdown', this.onTriggerDown);
  44029. el.removeEventListener('triggerup', this.onTriggerUp);
  44030. el.removeEventListener('triggertouchstart', this.onTriggerTouchStart);
  44031. el.removeEventListener('triggertouchend', this.onTriggerTouchEnd);
  44032. el.removeEventListener('griptouchstart', this.onGripTouchStart);
  44033. el.removeEventListener('griptouchend', this.onGripTouchEnd);
  44034. el.removeEventListener('thumbstickdown', this.onThumbstickDown);
  44035. el.removeEventListener('thumbstickup', this.onThumbstickUp);
  44036. el.removeEventListener('abuttontouchstart', this.onAorXTouchStart);
  44037. el.removeEventListener('abuttontouchend', this.onAorXTouchEnd);
  44038. el.removeEventListener('bbuttontouchstart', this.onBorYTouchStart);
  44039. el.removeEventListener('bbuttontouchend', this.onBorYTouchEnd);
  44040. el.removeEventListener('xbuttontouchstart', this.onAorXTouchStart);
  44041. el.removeEventListener('xbuttontouchend', this.onAorXTouchEnd);
  44042. el.removeEventListener('ybuttontouchstart', this.onBorYTouchStart);
  44043. el.removeEventListener('ybuttontouchend', this.onBorYTouchEnd);
  44044. el.removeEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  44045. el.removeEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  44046. },
  44047. /**
  44048. * Update handler. More like the `init` handler since the only property is the hand, and
  44049. * that won't be changing much.
  44050. */
  44051. update: function (previousHand) {
  44052. var controlConfiguration;
  44053. var el = this.el;
  44054. var hand = this.data;
  44055. // Get common configuration to abstract different vendor controls.
  44056. controlConfiguration = {
  44057. hand: hand,
  44058. model: false,
  44059. orientationOffset: {x: 0, y: 0, z: hand === 'left' ? 90 : -90}
  44060. };
  44061. // Set model.
  44062. if (hand !== previousHand) {
  44063. this.loader.load(MODEL_URLS[hand], function (scene) {
  44064. var mesh = scene.getObjectByName('Hand');
  44065. mesh.material.skinning = true;
  44066. mesh.mixer = new THREE.AnimationMixer(mesh);
  44067. el.setObject3D('mesh', mesh);
  44068. mesh.position.set(0, 0, 0);
  44069. mesh.rotation.set(0, 0, 0);
  44070. el.setAttribute('vive-controls', controlConfiguration);
  44071. el.setAttribute('oculus-touch-controls', controlConfiguration);
  44072. el.setAttribute('windows-motion-controls', controlConfiguration);
  44073. });
  44074. }
  44075. },
  44076. remove: function () {
  44077. this.el.removeObject3D('mesh');
  44078. },
  44079. /**
  44080. * Play model animation, based on which button was pressed and which kind of event.
  44081. *
  44082. * 1. Process buttons.
  44083. * 2. Determine gesture (this.determineGesture()).
  44084. * 3. Animation gesture (this.animationGesture()).
  44085. * 4. Emit gesture events (this.emitGestureEvents()).
  44086. *
  44087. * @param {string} button - Name of the button.
  44088. * @param {string} evt - Type of event for the button (i.e., down/up/touchstart/touchend).
  44089. */
  44090. handleButton: function (button, evt) {
  44091. var lastGesture;
  44092. var isPressed = evt === 'down';
  44093. var isTouched = evt === 'touchstart';
  44094. // Update objects.
  44095. if (evt.indexOf('touch') === 0) {
  44096. // Update touch object.
  44097. if (isTouched === this.touchedButtons[button]) { return; }
  44098. this.touchedButtons[button] = isTouched;
  44099. } else {
  44100. // Update button object.
  44101. if (isPressed === this.pressedButtons[button]) { return; }
  44102. this.pressedButtons[button] = isPressed;
  44103. }
  44104. // Determine the gesture.
  44105. lastGesture = this.gesture;
  44106. this.gesture = this.determineGesture();
  44107. // Same gesture.
  44108. if (this.gesture === lastGesture) { return; }
  44109. // Animate gesture.
  44110. this.animateGesture(this.gesture, lastGesture);
  44111. // Emit events.
  44112. this.emitGestureEvents(this.gesture, lastGesture);
  44113. },
  44114. /**
  44115. * Determine which pose hand should be in considering active and touched buttons.
  44116. */
  44117. determineGesture: function () {
  44118. var gesture;
  44119. var isGripActive = this.pressedButtons['grip'];
  44120. var isSurfaceActive = this.pressedButtons['surface'] || this.touchedButtons['surface'];
  44121. var isTrackpadActive = this.pressedButtons['trackpad'] || this.touchedButtons['trackpad'];
  44122. var isTriggerActive = this.pressedButtons['trigger'] || this.touchedButtons['trigger'];
  44123. var isABXYActive = this.touchedButtons['AorX'] || this.touchedButtons['BorY'];
  44124. var isVive = isViveController(this.el.components['tracked-controls']);
  44125. // Works well with Oculus Touch and Windows Motion Controls, but Vive needs tweaks.
  44126. if (isGripActive) {
  44127. if (isVive) {
  44128. gesture = ANIMATIONS.fist;
  44129. } else
  44130. if (isSurfaceActive || isABXYActive || isTrackpadActive) {
  44131. gesture = isTriggerActive ? ANIMATIONS.fist : ANIMATIONS.point;
  44132. } else {
  44133. gesture = isTriggerActive ? ANIMATIONS.thumbUp : ANIMATIONS.pointThumb;
  44134. }
  44135. } else {
  44136. if (isTriggerActive) {
  44137. gesture = !isVive ? ANIMATIONS.hold : ANIMATIONS.fist;
  44138. } else if (isVive && isTrackpadActive) {
  44139. gesture = ANIMATIONS.point;
  44140. }
  44141. }
  44142. return gesture;
  44143. },
  44144. /**
  44145. * Play gesture animation.
  44146. *
  44147. * @param {string} gesture - Which pose to animate to. If absent, then animate to open.
  44148. * @param {string} lastGesture - Previous gesture, to reverse back to open if needed.
  44149. */
  44150. animateGesture: function (gesture, lastGesture) {
  44151. if (gesture) {
  44152. this.playAnimation(gesture || ANIMATIONS.open, lastGesture, false);
  44153. return;
  44154. }
  44155. // If no gesture, then reverse the current gesture back to open pose.
  44156. this.playAnimation(lastGesture, lastGesture, true);
  44157. },
  44158. /**
  44159. * Emit `hand-controls`-specific events.
  44160. */
  44161. emitGestureEvents: function (gesture, lastGesture) {
  44162. var el = this.el;
  44163. var eventName;
  44164. if (lastGesture === gesture) { return; }
  44165. // Emit event for lastGesture not inactive.
  44166. eventName = getGestureEventName(lastGesture, false);
  44167. if (eventName) { el.emit(eventName); }
  44168. // Emit event for current gesture now active.
  44169. eventName = getGestureEventName(gesture, true);
  44170. if (eventName) { el.emit(eventName); }
  44171. },
  44172. /**
  44173. * Play hand animation based on button state.
  44174. *
  44175. * @param {string} gesture - Name of the animation as specified by the model.
  44176. * @param {string} lastGesture - Previous pose.
  44177. * @param {boolean} reverse - Whether animation should play in reverse.
  44178. */
  44179. playAnimation: function (gesture, lastGesture, reverse) {
  44180. var fromAction;
  44181. var mesh = this.el.getObject3D('mesh');
  44182. var toAction;
  44183. if (!mesh) { return; }
  44184. // Grab clip action.
  44185. toAction = mesh.mixer.clipAction(gesture);
  44186. toAction.clampWhenFinished = true;
  44187. toAction.loop = THREE.LoopRepeat;
  44188. toAction.repetitions = 0;
  44189. toAction.timeScale = reverse ? -1 : 1;
  44190. toAction.weight = 1;
  44191. // No gesture to gesture or gesture to no gesture.
  44192. if (!lastGesture || gesture === lastGesture) {
  44193. // Stop all current animations.
  44194. mesh.mixer.stopAllAction();
  44195. // Play animation.
  44196. toAction.play();
  44197. return;
  44198. }
  44199. // Animate or crossfade from gesture to gesture.
  44200. fromAction = mesh.mixer.clipAction(lastGesture);
  44201. mesh.mixer.stopAllAction();
  44202. fromAction.weight = 0.15;
  44203. fromAction.play();
  44204. toAction.play();
  44205. fromAction.crossFadeTo(toAction, 0.15, true);
  44206. }
  44207. });
  44208. /**
  44209. * Suffix gestures based on toggle state (e.g., open/close, up/down, start/end).
  44210. *
  44211. * @param {string} gesture
  44212. * @param {boolean} active
  44213. */
  44214. function getGestureEventName (gesture, active) {
  44215. var eventName;
  44216. if (!gesture) { return; }
  44217. eventName = EVENTS[gesture];
  44218. if (eventName === 'grip') {
  44219. return eventName + (active ? 'close' : 'open');
  44220. }
  44221. if (eventName === 'point' || eventName === 'thumb') {
  44222. return eventName + (active ? 'up' : 'down');
  44223. }
  44224. if (eventName === 'pointing' || eventName === 'pistol') {
  44225. return eventName + (active ? 'start' : 'end');
  44226. }
  44227. return;
  44228. }
  44229. function isViveController (trackedControls) {
  44230. var controllerId = trackedControls && trackedControls.controller &&
  44231. trackedControls.controller.id;
  44232. return controllerId && controllerId.indexOf('OpenVR ') === 0;
  44233. }
  44234. },{"../core/component":105}],61:[function(_dereq_,module,exports){
  44235. _dereq_('./animation');
  44236. _dereq_('./camera');
  44237. _dereq_('./collada-model');
  44238. _dereq_('./cursor');
  44239. _dereq_('./daydream-controls');
  44240. _dereq_('./gearvr-controls');
  44241. _dereq_('./geometry');
  44242. _dereq_('./gltf-model');
  44243. _dereq_('./hand-controls');
  44244. _dereq_('./laser-controls');
  44245. _dereq_('./light');
  44246. _dereq_('./line');
  44247. _dereq_('./link');
  44248. _dereq_('./look-controls');
  44249. _dereq_('./material');
  44250. _dereq_('./obj-model');
  44251. _dereq_('./oculus-go-controls');
  44252. _dereq_('./oculus-touch-controls');
  44253. _dereq_('./position');
  44254. _dereq_('./raycaster');
  44255. _dereq_('./rotation');
  44256. _dereq_('./scale');
  44257. _dereq_('./shadow');
  44258. _dereq_('./sound');
  44259. _dereq_('./text');
  44260. _dereq_('./tracked-controls');
  44261. _dereq_('./tracked-controls-webvr');
  44262. _dereq_('./tracked-controls-webxr');
  44263. _dereq_('./visible');
  44264. _dereq_('./vive-controls');
  44265. _dereq_('./vive-focus-controls');
  44266. _dereq_('./wasd-controls');
  44267. _dereq_('./windows-motion-controls');
  44268. _dereq_('./scene/background');
  44269. _dereq_('./scene/debug');
  44270. _dereq_('./scene/embedded');
  44271. _dereq_('./scene/inspector');
  44272. _dereq_('./scene/fog');
  44273. _dereq_('./scene/keyboard-shortcuts');
  44274. _dereq_('./scene/pool');
  44275. _dereq_('./scene/renderer');
  44276. _dereq_('./scene/screenshot');
  44277. _dereq_('./scene/stats');
  44278. _dereq_('./scene/vr-mode-ui');
  44279. },{"./animation":52,"./camera":53,"./collada-model":54,"./cursor":55,"./daydream-controls":56,"./gearvr-controls":57,"./geometry":58,"./gltf-model":59,"./hand-controls":60,"./laser-controls":62,"./light":63,"./line":64,"./link":65,"./look-controls":66,"./material":67,"./obj-model":68,"./oculus-go-controls":69,"./oculus-touch-controls":70,"./position":71,"./raycaster":72,"./rotation":73,"./scale":74,"./scene/background":75,"./scene/debug":76,"./scene/embedded":77,"./scene/fog":78,"./scene/inspector":79,"./scene/keyboard-shortcuts":80,"./scene/pool":81,"./scene/renderer":82,"./scene/screenshot":83,"./scene/stats":84,"./scene/vr-mode-ui":85,"./shadow":86,"./sound":87,"./text":88,"./tracked-controls":91,"./tracked-controls-webvr":89,"./tracked-controls-webxr":90,"./visible":92,"./vive-controls":93,"./vive-focus-controls":94,"./wasd-controls":95,"./windows-motion-controls":96}],62:[function(_dereq_,module,exports){
  44280. var registerComponent = _dereq_('../core/component').registerComponent;
  44281. var utils = _dereq_('../utils/');
  44282. registerComponent('laser-controls', {
  44283. schema: {
  44284. hand: {default: 'right'},
  44285. model: {default: true},
  44286. defaultModelColor: {type: 'color', default: 'grey'}
  44287. },
  44288. init: function () {
  44289. var config = this.config;
  44290. var data = this.data;
  44291. var el = this.el;
  44292. var self = this;
  44293. var modelEnabled = this.data.model && !this.el.sceneEl.hasWebXR;
  44294. var controlsConfiguration = {hand: data.hand, model: modelEnabled};
  44295. // Set all controller models.
  44296. el.setAttribute('daydream-controls', controlsConfiguration);
  44297. el.setAttribute('gearvr-controls', controlsConfiguration);
  44298. el.setAttribute('oculus-go-controls', controlsConfiguration);
  44299. el.setAttribute('oculus-touch-controls', controlsConfiguration);
  44300. el.setAttribute('vive-controls', controlsConfiguration);
  44301. el.setAttribute('vive-focus-controls', controlsConfiguration);
  44302. el.setAttribute('windows-motion-controls', controlsConfiguration);
  44303. // WebXR doesn't allow to discriminate between controllers, a default model is used.
  44304. if (this.data.model && this.el.sceneEl.hasWebXR) { this.initDefaultModel(); }
  44305. // Wait for controller to connect, or have a valid pointing pose, before creating ray
  44306. el.addEventListener('controllerconnected', createRay);
  44307. el.addEventListener('controllerdisconnected', hideRay);
  44308. el.addEventListener('controllermodelready', function (evt) {
  44309. createRay(evt);
  44310. self.modelReady = true;
  44311. });
  44312. function createRay (evt) {
  44313. var controllerConfig = config[evt.detail.name];
  44314. if (!controllerConfig) { return; }
  44315. // Show the line unless a particular config opts to hide it, until a controllermodelready
  44316. // event comes through.
  44317. var raycasterConfig = utils.extend({
  44318. showLine: true
  44319. }, controllerConfig.raycaster || {});
  44320. // The controllermodelready event contains a rayOrigin that takes into account
  44321. // offsets specific to the loaded model.
  44322. if (evt.detail.rayOrigin) {
  44323. raycasterConfig.origin = evt.detail.rayOrigin.origin;
  44324. raycasterConfig.direction = evt.detail.rayOrigin.direction;
  44325. raycasterConfig.showLine = true;
  44326. }
  44327. // Only apply a default raycaster if it does not yet exist. This prevents it overwriting
  44328. // config applied from a controllermodelready event.
  44329. if (evt.detail.rayOrigin || !self.modelReady) {
  44330. el.setAttribute('raycaster', raycasterConfig);
  44331. } else {
  44332. el.setAttribute('raycaster', 'showLine', true);
  44333. }
  44334. el.setAttribute('cursor', utils.extend({
  44335. fuse: false
  44336. }, controllerConfig.cursor));
  44337. }
  44338. function hideRay () {
  44339. el.setAttribute('raycaster', 'showLine', false);
  44340. }
  44341. },
  44342. config: {
  44343. 'daydream-controls': {
  44344. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  44345. },
  44346. 'gearvr-controls': {
  44347. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  44348. raycaster: {origin: {x: 0, y: 0.0005, z: 0}}
  44349. },
  44350. 'oculus-go-controls': {
  44351. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  44352. raycaster: {origin: {x: 0, y: 0.0005, z: 0}}
  44353. },
  44354. 'oculus-touch-controls': {
  44355. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  44356. raycaster: {origin: {x: 0, y: 0, z: 0}}
  44357. },
  44358. 'vive-controls': {
  44359. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  44360. },
  44361. 'vive-focus-controls': {
  44362. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  44363. },
  44364. 'windows-motion-controls': {
  44365. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  44366. raycaster: {showLine: false}
  44367. }
  44368. },
  44369. initDefaultModel: function () {
  44370. var modelEl = this.modelEl = document.createElement('a-entity');
  44371. modelEl.setAttribute('geometry', {
  44372. primitive: 'sphere',
  44373. radius: 0.03
  44374. });
  44375. modelEl.setAttribute('material', {color: this.data.color});
  44376. this.el.appendChild(modelEl);
  44377. }
  44378. });
  44379. },{"../core/component":105,"../utils/":178}],63:[function(_dereq_,module,exports){
  44380. var bind = _dereq_('../utils/bind');
  44381. var diff = _dereq_('../utils').diff;
  44382. var debug = _dereq_('../utils/debug');
  44383. var registerComponent = _dereq_('../core/component').registerComponent;
  44384. var THREE = _dereq_('../lib/three');
  44385. var degToRad = THREE.Math.degToRad;
  44386. var warn = debug('components:light:warn');
  44387. /**
  44388. * Light component.
  44389. */
  44390. module.exports.Component = registerComponent('light', {
  44391. schema: {
  44392. angle: {default: 60, if: {type: ['spot']}},
  44393. color: {type: 'color'},
  44394. groundColor: {type: 'color', if: {type: ['hemisphere']}},
  44395. decay: {default: 1, if: {type: ['point', 'spot']}},
  44396. distance: {default: 0.0, min: 0, if: {type: ['point', 'spot']}},
  44397. intensity: {default: 1.0, min: 0, if: {type: ['ambient', 'directional', 'hemisphere', 'point', 'spot']}},
  44398. penumbra: {default: 0, min: 0, max: 1, if: {type: ['spot']}},
  44399. type: {
  44400. default: 'directional',
  44401. oneOf: ['ambient', 'directional', 'hemisphere', 'point', 'spot'],
  44402. schemaChange: true
  44403. },
  44404. target: {type: 'selector', if: {type: ['spot', 'directional']}},
  44405. // Shadows.
  44406. castShadow: {default: false, if: {type: ['point', 'spot', 'directional']}},
  44407. shadowBias: {default: 0, if: {castShadow: true}},
  44408. shadowCameraFar: {default: 500, if: {castShadow: true}},
  44409. shadowCameraFov: {default: 90, if: {castShadow: true}},
  44410. shadowCameraNear: {default: 0.5, if: {castShadow: true}},
  44411. shadowCameraTop: {default: 5, if: {castShadow: true}},
  44412. shadowCameraRight: {default: 5, if: {castShadow: true}},
  44413. shadowCameraBottom: {default: -5, if: {castShadow: true}},
  44414. shadowCameraLeft: {default: -5, if: {castShadow: true}},
  44415. shadowCameraVisible: {default: false, if: {castShadow: true}},
  44416. shadowMapHeight: {default: 512, if: {castShadow: true}},
  44417. shadowMapWidth: {default: 512, if: {castShadow: true}},
  44418. shadowRadius: {default: 1, if: {castShadow: true}}
  44419. },
  44420. /**
  44421. * Notifies scene a light has been added to remove default lighting.
  44422. */
  44423. init: function () {
  44424. var el = this.el;
  44425. this.light = null;
  44426. this.defaultTarget = null;
  44427. this.system.registerLight(el);
  44428. },
  44429. /**
  44430. * (Re)create or update light.
  44431. */
  44432. update: function (oldData) {
  44433. var data = this.data;
  44434. var diffData = diff(data, oldData);
  44435. var light = this.light;
  44436. var self = this;
  44437. // Existing light.
  44438. if (light && !('type' in diffData)) {
  44439. var shadowsLoaded = false;
  44440. // Light type has not changed. Update light.
  44441. Object.keys(diffData).forEach(function (key) {
  44442. var value = data[key];
  44443. switch (key) {
  44444. case 'color': {
  44445. light.color.set(value);
  44446. break;
  44447. }
  44448. case 'groundColor': {
  44449. light.groundColor.set(value);
  44450. break;
  44451. }
  44452. case 'angle': {
  44453. light.angle = degToRad(value);
  44454. break;
  44455. }
  44456. case 'target': {
  44457. // Reset target if selector is null.
  44458. if (value === null) {
  44459. if (data.type === 'spot' || data.type === 'directional') {
  44460. light.target = self.defaultTarget;
  44461. }
  44462. } else {
  44463. // Target specified, set target to entity's `object3D` when it is loaded.
  44464. if (value.hasLoaded) {
  44465. self.onSetTarget(value, light);
  44466. } else {
  44467. value.addEventListener('loaded', bind(self.onSetTarget, self, value, light));
  44468. }
  44469. }
  44470. break;
  44471. }
  44472. case 'castShadow':
  44473. case 'shadowBias':
  44474. case 'shadowCameraFar':
  44475. case 'shadowCameraFov':
  44476. case 'shadowCameraNear':
  44477. case 'shadowCameraTop':
  44478. case 'shadowCameraRight':
  44479. case 'shadowCameraBottom':
  44480. case 'shadowCameraLeft':
  44481. case 'shadowCameraVisible':
  44482. case 'shadowMapHeight':
  44483. case 'shadowMapWidth':
  44484. case 'shadowRadius':
  44485. if (!shadowsLoaded) {
  44486. self.updateShadow();
  44487. shadowsLoaded = true;
  44488. }
  44489. break;
  44490. default: {
  44491. light[key] = value;
  44492. }
  44493. }
  44494. });
  44495. return;
  44496. }
  44497. // No light yet or light type has changed. Create and add light.
  44498. this.setLight(this.data);
  44499. this.updateShadow();
  44500. },
  44501. setLight: function (data) {
  44502. var el = this.el;
  44503. var newLight = this.getLight(data);
  44504. if (newLight) {
  44505. if (this.light) {
  44506. el.removeObject3D('light');
  44507. }
  44508. this.light = newLight;
  44509. this.light.el = el;
  44510. el.setObject3D('light', this.light);
  44511. // HACK solution for issue #1624
  44512. if (data.type === 'spot' || data.type === 'directional' || data.type === 'hemisphere') {
  44513. el.getObject3D('light').translateY(-1);
  44514. }
  44515. // set and position default lighttarget as a child to enable spotlight orientation
  44516. if (data.type === 'spot') {
  44517. el.setObject3D('light-target', this.defaultTarget);
  44518. el.getObject3D('light-target').position.set(0, 0, -1);
  44519. }
  44520. }
  44521. },
  44522. /**
  44523. * Updates shadow-related properties on the current light.
  44524. */
  44525. updateShadow: function () {
  44526. var el = this.el;
  44527. var data = this.data;
  44528. var light = this.light;
  44529. light.castShadow = data.castShadow;
  44530. // Shadow camera helper.
  44531. var cameraHelper = el.getObject3D('cameraHelper');
  44532. if (data.shadowCameraVisible && !cameraHelper) {
  44533. el.setObject3D('cameraHelper', new THREE.CameraHelper(light.shadow.camera));
  44534. } else if (!data.shadowCameraVisible && cameraHelper) {
  44535. el.removeObject3D('cameraHelper');
  44536. }
  44537. if (!data.castShadow) { return light; }
  44538. // Shadow appearance.
  44539. light.shadow.bias = data.shadowBias;
  44540. light.shadow.radius = data.shadowRadius;
  44541. light.shadow.mapSize.height = data.shadowMapHeight;
  44542. light.shadow.mapSize.width = data.shadowMapWidth;
  44543. // Shadow camera.
  44544. light.shadow.camera.near = data.shadowCameraNear;
  44545. light.shadow.camera.far = data.shadowCameraFar;
  44546. if (light.shadow.camera instanceof THREE.OrthographicCamera) {
  44547. light.shadow.camera.top = data.shadowCameraTop;
  44548. light.shadow.camera.right = data.shadowCameraRight;
  44549. light.shadow.camera.bottom = data.shadowCameraBottom;
  44550. light.shadow.camera.left = data.shadowCameraLeft;
  44551. } else {
  44552. light.shadow.camera.fov = data.shadowCameraFov;
  44553. }
  44554. light.shadow.camera.updateProjectionMatrix();
  44555. if (cameraHelper) { cameraHelper.update(); }
  44556. },
  44557. /**
  44558. * Creates a new three.js light object given data object defining the light.
  44559. *
  44560. * @param {object} data
  44561. */
  44562. getLight: function (data) {
  44563. var angle = data.angle;
  44564. var color = new THREE.Color(data.color).getHex();
  44565. var decay = data.decay;
  44566. var distance = data.distance;
  44567. var groundColor = new THREE.Color(data.groundColor).getHex();
  44568. var intensity = data.intensity;
  44569. var type = data.type;
  44570. var target = data.target;
  44571. var light = null;
  44572. switch (type.toLowerCase()) {
  44573. case 'ambient': {
  44574. return new THREE.AmbientLight(color, intensity);
  44575. }
  44576. case 'directional': {
  44577. light = new THREE.DirectionalLight(color, intensity);
  44578. this.defaultTarget = light.target;
  44579. if (target) {
  44580. if (target.hasLoaded) {
  44581. this.onSetTarget(target, light);
  44582. } else {
  44583. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  44584. }
  44585. }
  44586. return light;
  44587. }
  44588. case 'hemisphere': {
  44589. return new THREE.HemisphereLight(color, groundColor, intensity);
  44590. }
  44591. case 'point': {
  44592. return new THREE.PointLight(color, intensity, distance, decay);
  44593. }
  44594. case 'spot': {
  44595. light = new THREE.SpotLight(color, intensity, distance, degToRad(angle), data.penumbra, decay);
  44596. this.defaultTarget = light.target;
  44597. if (target) {
  44598. if (target.hasLoaded) {
  44599. this.onSetTarget(target, light);
  44600. } else {
  44601. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  44602. }
  44603. }
  44604. return light;
  44605. }
  44606. default: {
  44607. warn('%s is not a valid light type. ' +
  44608. 'Choose from ambient, directional, hemisphere, point, spot.', type);
  44609. }
  44610. }
  44611. },
  44612. onSetTarget: function (targetEl, light) {
  44613. light.target = targetEl.object3D;
  44614. },
  44615. /**
  44616. * Remove light on remove (callback).
  44617. */
  44618. remove: function () {
  44619. var el = this.el;
  44620. el.removeObject3D('light');
  44621. if (el.getObject3D('cameraHelper')) {
  44622. el.removeObject3D('cameraHelper');
  44623. }
  44624. }
  44625. });
  44626. },{"../core/component":105,"../lib/three":154,"../utils":178,"../utils/bind":172,"../utils/debug":174}],64:[function(_dereq_,module,exports){
  44627. /* global THREE */
  44628. var registerComponent = _dereq_('../core/component').registerComponent;
  44629. module.exports.Component = registerComponent('line', {
  44630. schema: {
  44631. start: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  44632. end: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  44633. color: {type: 'color', default: '#74BEC1'},
  44634. opacity: {type: 'number', default: 1},
  44635. visible: {default: true}
  44636. },
  44637. multiple: true,
  44638. init: function () {
  44639. var data = this.data;
  44640. var geometry;
  44641. var material;
  44642. material = this.material = new THREE.LineBasicMaterial({
  44643. color: data.color,
  44644. opacity: data.opacity,
  44645. transparent: data.opacity < 1,
  44646. visible: data.visible
  44647. });
  44648. geometry = this.geometry = new THREE.BufferGeometry();
  44649. geometry.addAttribute('position', new THREE.BufferAttribute(new Float32Array(2 * 3), 3));
  44650. this.line = new THREE.Line(geometry, material);
  44651. this.el.setObject3D(this.attrName, this.line);
  44652. },
  44653. update: function (oldData) {
  44654. var data = this.data;
  44655. var geometry = this.geometry;
  44656. var geoNeedsUpdate = false;
  44657. var material = this.material;
  44658. var positionArray = geometry.attributes.position.array;
  44659. // Update geometry.
  44660. if (!isEqualVec3(data.start, oldData.start)) {
  44661. positionArray[0] = data.start.x;
  44662. positionArray[1] = data.start.y;
  44663. positionArray[2] = data.start.z;
  44664. geoNeedsUpdate = true;
  44665. }
  44666. if (!isEqualVec3(data.end, oldData.end)) {
  44667. positionArray[3] = data.end.x;
  44668. positionArray[4] = data.end.y;
  44669. positionArray[5] = data.end.z;
  44670. geoNeedsUpdate = true;
  44671. }
  44672. if (geoNeedsUpdate) {
  44673. geometry.attributes.position.needsUpdate = true;
  44674. geometry.computeBoundingSphere();
  44675. }
  44676. material.color.setStyle(data.color);
  44677. material.opacity = data.opacity;
  44678. material.transparent = data.opacity < 1;
  44679. material.visible = data.visible;
  44680. },
  44681. remove: function () {
  44682. this.el.removeObject3D('line', this.line);
  44683. }
  44684. });
  44685. function isEqualVec3 (a, b) {
  44686. if (!a || !b) { return false; }
  44687. return (a.x === b.x && a.y === b.y && a.z === b.z);
  44688. }
  44689. },{"../core/component":105}],65:[function(_dereq_,module,exports){
  44690. var registerComponent = _dereq_('../core/component').registerComponent;
  44691. var registerShader = _dereq_('../core/shader').registerShader;
  44692. var THREE = _dereq_('../lib/three');
  44693. /**
  44694. * Link component. Connect experiences and traverse between them in VR
  44695. *
  44696. * @member {object} hiddenEls - Store the hidden elements during peek mode.
  44697. */
  44698. module.exports.Component = registerComponent('link', {
  44699. schema: {
  44700. backgroundColor: {default: 'red', type: 'color'},
  44701. borderColor: {default: 'white', type: 'color'},
  44702. highlighted: {default: false},
  44703. highlightedColor: {default: '#24CAFF', type: 'color'},
  44704. href: {default: ''},
  44705. image: {type: 'asset'},
  44706. on: {default: 'click'},
  44707. peekMode: {default: false},
  44708. title: {default: ''},
  44709. titleColor: {default: 'white', type: 'color'},
  44710. visualAspectEnabled: {default: false}
  44711. },
  44712. init: function () {
  44713. this.navigate = this.navigate.bind(this);
  44714. this.previousQuaternion = undefined;
  44715. this.quaternionClone = new THREE.Quaternion();
  44716. // Store hidden elements during peek mode so we can show them again later.
  44717. this.hiddenEls = [];
  44718. },
  44719. update: function (oldData) {
  44720. var data = this.data;
  44721. var el = this.el;
  44722. var backgroundColor;
  44723. var strokeColor;
  44724. if (!data.visualAspectEnabled) { return; }
  44725. this.initVisualAspect();
  44726. backgroundColor = data.highlighted ? data.highlightedColor : data.backgroundColor;
  44727. strokeColor = data.highlighted ? data.highlightedColor : data.borderColor;
  44728. el.setAttribute('material', 'backgroundColor', backgroundColor);
  44729. el.setAttribute('material', 'strokeColor', strokeColor);
  44730. if (data.on !== oldData.on) { this.updateEventListener(); }
  44731. if (oldData.peekMode !== undefined &&
  44732. data.peekMode !== oldData.peekMode) { this.updatePeekMode(); }
  44733. if (!data.image || oldData.image === data.image) { return; }
  44734. el.setAttribute('material', 'pano',
  44735. typeof data.image === 'string' ? data.image : data.image.src);
  44736. },
  44737. /*
  44738. * Toggle all elements and full 360 preview of the linked page.
  44739. */
  44740. updatePeekMode: function () {
  44741. var el = this.el;
  44742. var sphereEl = this.sphereEl;
  44743. if (this.data.peekMode) {
  44744. this.hideAll();
  44745. el.getObject3D('mesh').visible = false;
  44746. sphereEl.setAttribute('visible', true);
  44747. } else {
  44748. this.showAll();
  44749. el.getObject3D('mesh').visible = true;
  44750. sphereEl.setAttribute('visible', false);
  44751. }
  44752. },
  44753. play: function () {
  44754. this.updateEventListener();
  44755. },
  44756. pause: function () {
  44757. this.removeEventListener();
  44758. },
  44759. updateEventListener: function () {
  44760. var el = this.el;
  44761. if (!el.isPlaying) { return; }
  44762. this.removeEventListener();
  44763. el.addEventListener(this.data.on, this.navigate);
  44764. },
  44765. removeEventListener: function () {
  44766. var on = this.data.on;
  44767. if (!on) { return; }
  44768. this.el.removeEventListener(on, this.navigate);
  44769. },
  44770. initVisualAspect: function () {
  44771. var el = this.el;
  44772. var semiSphereEl;
  44773. var sphereEl;
  44774. var textEl;
  44775. if (!this.data.visualAspectEnabled || this.visualAspectInitialized) { return; }
  44776. textEl = this.textEl = this.textEl || document.createElement('a-entity');
  44777. sphereEl = this.sphereEl = this.sphereEl || document.createElement('a-entity');
  44778. semiSphereEl = this.semiSphereEl = this.semiSphereEl || document.createElement('a-entity');
  44779. // Set portal.
  44780. el.setAttribute('geometry', {primitive: 'circle', radius: 1.0, segments: 64});
  44781. el.setAttribute('material', {shader: 'portal', pano: this.data.image, side: 'double'});
  44782. // Set text that displays the link title and URL.
  44783. textEl.setAttribute('text', {
  44784. color: this.data.titleColor,
  44785. align: 'center',
  44786. font: 'kelsonsans',
  44787. value: this.data.title || this.data.href,
  44788. width: 4
  44789. });
  44790. textEl.setAttribute('position', '0 1.5 0');
  44791. el.appendChild(textEl);
  44792. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  44793. semiSphereEl.setAttribute('geometry', {
  44794. primitive: 'sphere',
  44795. radius: 1.0,
  44796. phiStart: 0,
  44797. segmentsWidth: 64,
  44798. segmentsHeight: 64,
  44799. phiLength: 180,
  44800. thetaStart: 0,
  44801. thetaLength: 360
  44802. });
  44803. semiSphereEl.setAttribute('material', {
  44804. shader: 'portal',
  44805. borderEnabled: 0.0,
  44806. pano: this.data.image,
  44807. side: 'back'
  44808. });
  44809. semiSphereEl.setAttribute('rotation', '0 180 0');
  44810. semiSphereEl.setAttribute('position', '0 0 0');
  44811. semiSphereEl.setAttribute('visible', false);
  44812. el.appendChild(semiSphereEl);
  44813. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  44814. sphereEl.setAttribute('geometry', {
  44815. primitive: 'sphere',
  44816. radius: 10,
  44817. segmentsWidth: 64,
  44818. segmentsHeight: 64
  44819. });
  44820. sphereEl.setAttribute('material', {
  44821. shader: 'portal',
  44822. borderEnabled: 0.0,
  44823. pano: this.data.image,
  44824. side: 'back'
  44825. });
  44826. sphereEl.setAttribute('visible', false);
  44827. el.appendChild(sphereEl);
  44828. this.visualAspectInitialized = true;
  44829. },
  44830. navigate: function () {
  44831. window.location = this.data.href;
  44832. },
  44833. /**
  44834. * 1. Swap plane that represents portal with sphere with a hole when the camera is close
  44835. * so user can peek inside portal. Sphere is rendered on oposite side of portal
  44836. * from where user enters.
  44837. * 2. Place the url/title above or inside portal depending on distance to camera.
  44838. * 3. Face portal to camera when far away from user.
  44839. */
  44840. tick: (function () {
  44841. var cameraWorldPosition = new THREE.Vector3();
  44842. var elWorldPosition = new THREE.Vector3();
  44843. var quaternion = new THREE.Quaternion();
  44844. var scale = new THREE.Vector3();
  44845. return function () {
  44846. var el = this.el;
  44847. var object3D = el.object3D;
  44848. var camera = el.sceneEl.camera;
  44849. var cameraPortalOrientation;
  44850. var distance;
  44851. var textEl = this.textEl;
  44852. if (!this.data.visualAspectEnabled) { return; }
  44853. // Update matrices
  44854. object3D.updateMatrixWorld();
  44855. camera.parent.updateMatrixWorld();
  44856. camera.updateMatrixWorld();
  44857. object3D.matrix.decompose(elWorldPosition, quaternion, scale);
  44858. elWorldPosition.setFromMatrixPosition(object3D.matrixWorld);
  44859. cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);
  44860. distance = elWorldPosition.distanceTo(cameraWorldPosition);
  44861. if (distance > 20) {
  44862. // Store original orientation to be restored when the portal stops facing the camera.
  44863. if (!this.previousQuaternion) {
  44864. this.quaternionClone.copy(quaternion);
  44865. this.previousQuaternion = this.quaternionClone;
  44866. }
  44867. // If the portal is far away from the user, face portal to camera.
  44868. object3D.lookAt(cameraWorldPosition);
  44869. } else {
  44870. // When portal is close to the user/camera.
  44871. cameraPortalOrientation = this.calculateCameraPortalOrientation();
  44872. // If user gets very close to portal, replace with holed sphere they can peek in.
  44873. if (distance < 0.5) {
  44874. // Configure text size and sphere orientation depending side user approaches portal.
  44875. if (this.semiSphereEl.getAttribute('visible') === true) { return; }
  44876. textEl.setAttribute('text', 'width', 1.5);
  44877. if (cameraPortalOrientation <= 0.0) {
  44878. textEl.setAttribute('position', '0 0 0.75');
  44879. textEl.setAttribute('rotation', '0 180 0');
  44880. this.semiSphereEl.setAttribute('rotation', '0 0 0');
  44881. } else {
  44882. textEl.setAttribute('position', '0 0 -0.75');
  44883. textEl.setAttribute('rotation', '0 0 0');
  44884. this.semiSphereEl.setAttribute('rotation', '0 180 0');
  44885. }
  44886. el.getObject3D('mesh').visible = false;
  44887. this.semiSphereEl.setAttribute('visible', true);
  44888. this.peekCameraPortalOrientation = cameraPortalOrientation;
  44889. } else {
  44890. // Calculate wich side the camera is approaching the camera (back / front).
  44891. // Adjust text orientation based on camera position.
  44892. if (cameraPortalOrientation <= 0.0) {
  44893. textEl.setAttribute('rotation', '0 180 0');
  44894. } else {
  44895. textEl.setAttribute('rotation', '0 0 0');
  44896. }
  44897. textEl.setAttribute('text', 'width', 5);
  44898. textEl.setAttribute('position', '0 1.5 0');
  44899. el.getObject3D('mesh').visible = true;
  44900. this.semiSphereEl.setAttribute('visible', false);
  44901. this.peekCameraPortalOrientation = undefined;
  44902. }
  44903. if (this.previousQuaternion) {
  44904. object3D.quaternion.copy(this.previousQuaternion);
  44905. this.previousQuaternion = undefined;
  44906. }
  44907. }
  44908. };
  44909. })(),
  44910. hideAll: function () {
  44911. var el = this.el;
  44912. var hiddenEls = this.hiddenEls;
  44913. var self = this;
  44914. if (hiddenEls.length > 0) { return; }
  44915. el.sceneEl.object3D.traverse(function (object) {
  44916. if (object && object.el && object.el.hasAttribute('link-controls')) { return; }
  44917. if (!object.el || object === el.sceneEl.object3D || object.el === el ||
  44918. object.el === self.sphereEl || object.el === el.sceneEl.cameraEl ||
  44919. object.el.getAttribute('visible') === false || object.el === self.textEl ||
  44920. object.el === self.semiSphereEl) {
  44921. return;
  44922. }
  44923. object.el.setAttribute('visible', false);
  44924. hiddenEls.push(object.el);
  44925. });
  44926. },
  44927. showAll: function () {
  44928. this.hiddenEls.forEach(function (el) { el.setAttribute('visible', true); });
  44929. this.hiddenEls = [];
  44930. },
  44931. /**
  44932. * Calculate whether the camera faces the front or back face of the portal.
  44933. * @returns {number} > 0 if camera faces front of portal, < 0 if it faces back of portal.
  44934. */
  44935. calculateCameraPortalOrientation: (function () {
  44936. var mat4 = new THREE.Matrix4();
  44937. var cameraPosition = new THREE.Vector3();
  44938. var portalNormal = new THREE.Vector3(0, 0, 1);
  44939. var portalPosition = new THREE.Vector3(0, 0, 0);
  44940. return function () {
  44941. var el = this.el;
  44942. var camera = el.sceneEl.camera;
  44943. // Reset tmp variables.
  44944. cameraPosition.set(0, 0, 0);
  44945. portalNormal.set(0, 0, 1);
  44946. portalPosition.set(0, 0, 0);
  44947. // Apply portal orientation to the normal.
  44948. el.object3D.matrixWorld.extractRotation(mat4);
  44949. portalNormal.applyMatrix4(mat4);
  44950. // Calculate portal world position.
  44951. el.object3D.updateMatrixWorld();
  44952. el.object3D.localToWorld(portalPosition);
  44953. // Calculate camera world position.
  44954. camera.parent.parent.updateMatrixWorld();
  44955. camera.parent.updateMatrixWorld();
  44956. camera.updateMatrixWorld();
  44957. camera.localToWorld(cameraPosition);
  44958. // Calculate vector from portal to camera.
  44959. // (portal) -------> (camera)
  44960. cameraPosition.sub(portalPosition).normalize();
  44961. portalNormal.normalize();
  44962. // Side where camera approaches portal is given by sign of dot product of portal normal
  44963. // and portal to camera vectors.
  44964. return Math.sign(portalNormal.dot(cameraPosition));
  44965. };
  44966. })(),
  44967. remove: function () {
  44968. this.removeEventListener();
  44969. }
  44970. });
  44971. /* eslint-disable */
  44972. registerShader('portal', {
  44973. schema: {
  44974. borderEnabled: {default: 1.0, type: 'int', is: 'uniform'},
  44975. backgroundColor: {default: 'red', type: 'color', is: 'uniform'},
  44976. pano: {type: 'map', is: 'uniform'},
  44977. strokeColor: {default: 'white', type: 'color', is: 'uniform'}
  44978. },
  44979. vertexShader: [
  44980. 'vec3 portalPosition;',
  44981. 'varying vec3 vWorldPosition;',
  44982. 'varying float vDistanceToCenter;',
  44983. 'varying float vDistance;',
  44984. 'void main() {',
  44985. 'vDistanceToCenter = clamp(length(position - vec3(0.0, 0.0, 0.0)), 0.0, 1.0);',
  44986. 'portalPosition = (modelMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;',
  44987. 'vDistance = length(portalPosition - cameraPosition);',
  44988. 'vWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz;',
  44989. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  44990. '}'
  44991. ].join('\n'),
  44992. fragmentShader: [
  44993. '#define RECIPROCAL_PI2 0.15915494',
  44994. 'uniform sampler2D pano;',
  44995. 'uniform vec3 strokeColor;',
  44996. 'uniform vec3 backgroundColor;',
  44997. 'uniform float borderEnabled;',
  44998. 'varying float vDistanceToCenter;',
  44999. 'varying float vDistance;',
  45000. 'varying vec3 vWorldPosition;',
  45001. 'void main() {',
  45002. 'vec3 direction = normalize(vWorldPosition - cameraPosition);',
  45003. 'vec2 sampleUV;',
  45004. 'float borderThickness = clamp(exp(-vDistance / 50.0), 0.6, 0.95);',
  45005. 'sampleUV.y = saturate(direction.y * 0.5 + 0.5);',
  45006. 'sampleUV.x = atan(direction.z, -direction.x) * -RECIPROCAL_PI2 + 0.5;',
  45007. 'if (vDistanceToCenter > borderThickness && borderEnabled == 1.0) {',
  45008. 'gl_FragColor = vec4(strokeColor, 1.0);',
  45009. '} else {',
  45010. 'gl_FragColor = mix(texture2D(pano, sampleUV), vec4(backgroundColor, 1.0), clamp(pow((vDistance / 15.0), 2.0), 0.0, 1.0));',
  45011. '}',
  45012. '}'
  45013. ].join('\n')
  45014. });
  45015. /* eslint-enable */
  45016. },{"../core/component":105,"../core/shader":115,"../lib/three":154}],66:[function(_dereq_,module,exports){
  45017. var registerComponent = _dereq_('../core/component').registerComponent;
  45018. var THREE = _dereq_('../lib/three');
  45019. var utils = _dereq_('../utils/');
  45020. var bind = utils.bind;
  45021. var PolyfillControls = _dereq_('../utils').device.PolyfillControls;
  45022. // To avoid recalculation at every mouse movement tick
  45023. var PI_2 = Math.PI / 2;
  45024. /**
  45025. * look-controls. Update entity pose, factoring mouse, touch, and WebVR API data.
  45026. */
  45027. module.exports.Component = registerComponent('look-controls', {
  45028. dependencies: ['position', 'rotation'],
  45029. schema: {
  45030. enabled: {default: true},
  45031. hmdEnabled: {default: true},
  45032. pointerLockEnabled: {default: false},
  45033. reverseMouseDrag: {default: false},
  45034. reverseTouchDrag: {default: false},
  45035. touchEnabled: {default: true}
  45036. },
  45037. init: function () {
  45038. this.previousHMDPosition = new THREE.Vector3();
  45039. this.hmdQuaternion = new THREE.Quaternion();
  45040. this.hmdEuler = new THREE.Euler();
  45041. this.position = new THREE.Vector3();
  45042. // To save / restore camera pose
  45043. this.savedRotation = new THREE.Vector3();
  45044. this.savedPosition = new THREE.Vector3();
  45045. this.polyfillObject = new THREE.Object3D();
  45046. this.polyfillControls = new PolyfillControls(this.polyfillObject);
  45047. this.rotation = {};
  45048. this.deltaRotation = {};
  45049. this.savedPose = null;
  45050. this.pointerLocked = false;
  45051. this.setupMouseControls();
  45052. this.bindMethods();
  45053. this.el.object3D.matrixAutoUpdate = false;
  45054. this.savedPose = {
  45055. position: new THREE.Vector3(),
  45056. rotation: new THREE.Euler()
  45057. };
  45058. // Call enter VR handler if the scene has entered VR before the event listeners attached.
  45059. if (this.el.sceneEl.is('vr-mode')) { this.onEnterVR(); }
  45060. },
  45061. update: function (oldData) {
  45062. var data = this.data;
  45063. // Disable grab cursor classes if no longer enabled.
  45064. if (data.enabled !== oldData.enabled) {
  45065. this.updateGrabCursor(data.enabled);
  45066. }
  45067. // Reset pitch and yaw if disabling HMD.
  45068. if (oldData && !data.hmdEnabled && !oldData.hmdEnabled) {
  45069. this.pitchObject.rotation.set(0, 0, 0);
  45070. this.yawObject.rotation.set(0, 0, 0);
  45071. }
  45072. if (oldData && !data.pointerLockEnabled !== oldData.pointerLockEnabled) {
  45073. this.removeEventListeners();
  45074. this.addEventListeners();
  45075. if (this.pointerLocked) { document.exitPointerLock(); }
  45076. }
  45077. },
  45078. tick: function (t) {
  45079. var data = this.data;
  45080. if (!data.enabled) { return; }
  45081. this.updateOrientation();
  45082. },
  45083. play: function () {
  45084. this.addEventListeners();
  45085. },
  45086. pause: function () {
  45087. this.removeEventListeners();
  45088. },
  45089. remove: function () {
  45090. this.removeEventListeners();
  45091. },
  45092. bindMethods: function () {
  45093. this.onMouseDown = bind(this.onMouseDown, this);
  45094. this.onMouseMove = bind(this.onMouseMove, this);
  45095. this.onMouseUp = bind(this.onMouseUp, this);
  45096. this.onTouchStart = bind(this.onTouchStart, this);
  45097. this.onTouchMove = bind(this.onTouchMove, this);
  45098. this.onTouchEnd = bind(this.onTouchEnd, this);
  45099. this.onEnterVR = bind(this.onEnterVR, this);
  45100. this.onExitVR = bind(this.onExitVR, this);
  45101. this.onPointerLockChange = bind(this.onPointerLockChange, this);
  45102. this.onPointerLockError = bind(this.onPointerLockError, this);
  45103. },
  45104. /**
  45105. * Set up states and Object3Ds needed to store rotation data.
  45106. */
  45107. setupMouseControls: function () {
  45108. this.mouseDown = false;
  45109. this.pitchObject = new THREE.Object3D();
  45110. this.yawObject = new THREE.Object3D();
  45111. this.yawObject.position.y = 10;
  45112. this.yawObject.add(this.pitchObject);
  45113. },
  45114. /**
  45115. * Add mouse and touch event listeners to canvas.
  45116. */
  45117. addEventListeners: function () {
  45118. var sceneEl = this.el.sceneEl;
  45119. var canvasEl = sceneEl.canvas;
  45120. // Wait for canvas to load.
  45121. if (!canvasEl) {
  45122. sceneEl.addEventListener('render-target-loaded', bind(this.addEventListeners, this));
  45123. return;
  45124. }
  45125. // Mouse events.
  45126. canvasEl.addEventListener('mousedown', this.onMouseDown, false);
  45127. window.addEventListener('mousemove', this.onMouseMove, false);
  45128. window.addEventListener('mouseup', this.onMouseUp, false);
  45129. // Touch events.
  45130. canvasEl.addEventListener('touchstart', this.onTouchStart);
  45131. window.addEventListener('touchmove', this.onTouchMove);
  45132. window.addEventListener('touchend', this.onTouchEnd);
  45133. // sceneEl events.
  45134. sceneEl.addEventListener('enter-vr', this.onEnterVR);
  45135. sceneEl.addEventListener('exit-vr', this.onExitVR);
  45136. // Pointer Lock events.
  45137. if (this.data.pointerLockEnabled) {
  45138. document.addEventListener('pointerlockchange', this.onPointerLockChange, false);
  45139. document.addEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  45140. document.addEventListener('pointerlockerror', this.onPointerLockError, false);
  45141. }
  45142. },
  45143. /**
  45144. * Remove mouse and touch event listeners from canvas.
  45145. */
  45146. removeEventListeners: function () {
  45147. var sceneEl = this.el.sceneEl;
  45148. var canvasEl = sceneEl && sceneEl.canvas;
  45149. if (!canvasEl) { return; }
  45150. // Mouse events.
  45151. canvasEl.removeEventListener('mousedown', this.onMouseDown);
  45152. window.removeEventListener('mousemove', this.onMouseMove);
  45153. window.removeEventListener('mouseup', this.onMouseUp);
  45154. // Touch events.
  45155. canvasEl.removeEventListener('touchstart', this.onTouchStart);
  45156. window.removeEventListener('touchmove', this.onTouchMove);
  45157. window.removeEventListener('touchend', this.onTouchEnd);
  45158. // sceneEl events.
  45159. sceneEl.removeEventListener('enter-vr', this.onEnterVR);
  45160. sceneEl.removeEventListener('exit-vr', this.onExitVR);
  45161. // Pointer Lock events.
  45162. document.removeEventListener('pointerlockchange', this.onPointerLockChange, false);
  45163. document.removeEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  45164. document.removeEventListener('pointerlockerror', this.onPointerLockError, false);
  45165. },
  45166. /**
  45167. * Update orientation for mobile, mouse drag, and headset.
  45168. * Mouse-drag only enabled if HMD is not active.
  45169. */
  45170. updateOrientation: (function () {
  45171. var poseMatrix = new THREE.Matrix4();
  45172. return function () {
  45173. var hmdEuler = this.hmdEuler;
  45174. var object3D = this.el.object3D;
  45175. var pitchObject = this.pitchObject;
  45176. var yawObject = this.yawObject;
  45177. var pose;
  45178. var sceneEl = this.el.sceneEl;
  45179. // WebXR API updates applies headset pose to the object3D matrixWorld internally.
  45180. // Reflect values back on position, rotation, scale so setAttribute returns expected values.
  45181. if (sceneEl.is('vr-mode') && sceneEl.hasWebXR) {
  45182. pose = sceneEl.renderer.vr.getCameraPose();
  45183. if (pose) {
  45184. poseMatrix.elements = pose.poseModelMatrix;
  45185. poseMatrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  45186. }
  45187. } else {
  45188. object3D.updateMatrix();
  45189. }
  45190. // In VR mode, THREE is in charge of updating the camera rotation.
  45191. if (sceneEl.is('vr-mode') && sceneEl.checkHeadsetConnected()) { return; }
  45192. // Calculate polyfilled HMD quaternion.
  45193. this.polyfillControls.update();
  45194. hmdEuler.setFromQuaternion(this.polyfillObject.quaternion, 'YXZ');
  45195. // On mobile, do camera rotation with touch events and sensors.
  45196. object3D.rotation.x = hmdEuler.x + pitchObject.rotation.x;
  45197. object3D.rotation.y = hmdEuler.y + yawObject.rotation.y;
  45198. };
  45199. })(),
  45200. /**
  45201. * Translate mouse drag into rotation.
  45202. *
  45203. * Dragging up and down rotates the camera around the X-axis (yaw).
  45204. * Dragging left and right rotates the camera around the Y-axis (pitch).
  45205. */
  45206. onMouseMove: function (event) {
  45207. var direction;
  45208. var movementX;
  45209. var movementY;
  45210. var pitchObject = this.pitchObject;
  45211. var previousMouseEvent = this.previousMouseEvent;
  45212. var yawObject = this.yawObject;
  45213. // Not dragging or not enabled.
  45214. if (!this.data.enabled || (!this.mouseDown && !this.pointerLocked)) { return; }
  45215. // Calculate delta.
  45216. if (this.pointerLocked) {
  45217. movementX = event.movementX || event.mozMovementX || 0;
  45218. movementY = event.movementY || event.mozMovementY || 0;
  45219. } else {
  45220. movementX = event.screenX - previousMouseEvent.screenX;
  45221. movementY = event.screenY - previousMouseEvent.screenY;
  45222. }
  45223. this.previousMouseEvent = event;
  45224. // Calculate rotation.
  45225. direction = this.data.reverseMouseDrag ? 1 : -1;
  45226. yawObject.rotation.y += movementX * 0.002 * direction;
  45227. pitchObject.rotation.x += movementY * 0.002 * direction;
  45228. pitchObject.rotation.x = Math.max(-PI_2, Math.min(PI_2, pitchObject.rotation.x));
  45229. },
  45230. /**
  45231. * Register mouse down to detect mouse drag.
  45232. */
  45233. onMouseDown: function (evt) {
  45234. if (!this.data.enabled) { return; }
  45235. // Handle only primary button.
  45236. if (evt.button !== 0) { return; }
  45237. var sceneEl = this.el.sceneEl;
  45238. var canvasEl = sceneEl && sceneEl.canvas;
  45239. this.mouseDown = true;
  45240. this.previousMouseEvent = evt;
  45241. this.showGrabbingCursor();
  45242. if (this.data.pointerLockEnabled && !this.pointerLocked) {
  45243. if (canvasEl.requestPointerLock) {
  45244. canvasEl.requestPointerLock();
  45245. } else if (canvasEl.mozRequestPointerLock) {
  45246. canvasEl.mozRequestPointerLock();
  45247. }
  45248. }
  45249. },
  45250. /**
  45251. * Shows grabbing cursor on scene
  45252. */
  45253. showGrabbingCursor: function () {
  45254. this.el.sceneEl.canvas.style.cursor = 'grabbing';
  45255. },
  45256. /**
  45257. * Hides grabbing cursor on scene
  45258. */
  45259. hideGrabbingCursor: function () {
  45260. this.el.sceneEl.canvas.style.cursor = '';
  45261. },
  45262. /**
  45263. * Register mouse up to detect release of mouse drag.
  45264. */
  45265. onMouseUp: function () {
  45266. this.mouseDown = false;
  45267. this.hideGrabbingCursor();
  45268. },
  45269. /**
  45270. * Register touch down to detect touch drag.
  45271. */
  45272. onTouchStart: function (evt) {
  45273. if (evt.touches.length !== 1 || !this.data.touchEnabled) { return; }
  45274. this.touchStart = {
  45275. x: evt.touches[0].pageX,
  45276. y: evt.touches[0].pageY
  45277. };
  45278. this.touchStarted = true;
  45279. },
  45280. /**
  45281. * Translate touch move to Y-axis rotation.
  45282. */
  45283. onTouchMove: function (evt) {
  45284. var direction;
  45285. var canvas = this.el.sceneEl.canvas;
  45286. var deltaY;
  45287. var yawObject = this.yawObject;
  45288. if (!this.touchStarted || !this.data.touchEnabled) { return; }
  45289. deltaY = 2 * Math.PI * (evt.touches[0].pageX - this.touchStart.x) / canvas.clientWidth;
  45290. direction = this.data.reverseTouchDrag ? 1 : -1;
  45291. // Limit touch orientaion to to yaw (y axis).
  45292. yawObject.rotation.y -= deltaY * 0.5 * direction;
  45293. this.touchStart = {
  45294. x: evt.touches[0].pageX,
  45295. y: evt.touches[0].pageY
  45296. };
  45297. },
  45298. /**
  45299. * Register touch end to detect release of touch drag.
  45300. */
  45301. onTouchEnd: function () {
  45302. this.touchStarted = false;
  45303. },
  45304. /**
  45305. * Save pose.
  45306. */
  45307. onEnterVR: function () {
  45308. this.saveCameraPose();
  45309. this.el.object3D.position.set(0, 0, 0);
  45310. this.el.object3D.updateMatrix();
  45311. },
  45312. /**
  45313. * Restore the pose.
  45314. */
  45315. onExitVR: function () {
  45316. this.restoreCameraPose();
  45317. this.previousHMDPosition.set(0, 0, 0);
  45318. },
  45319. /**
  45320. * Update Pointer Lock state.
  45321. */
  45322. onPointerLockChange: function () {
  45323. this.pointerLocked = !!(document.pointerLockElement || document.mozPointerLockElement);
  45324. },
  45325. /**
  45326. * Recover from Pointer Lock error.
  45327. */
  45328. onPointerLockError: function () {
  45329. this.pointerLocked = false;
  45330. },
  45331. /**
  45332. * Toggle the feature of showing/hiding the grab cursor.
  45333. */
  45334. updateGrabCursor: function (enabled) {
  45335. var sceneEl = this.el.sceneEl;
  45336. function enableGrabCursor () { sceneEl.canvas.classList.add('a-grab-cursor'); }
  45337. function disableGrabCursor () { sceneEl.canvas.classList.remove('a-grab-cursor'); }
  45338. if (!sceneEl.canvas) {
  45339. if (enabled) {
  45340. sceneEl.addEventListener('render-target-loaded', enableGrabCursor);
  45341. } else {
  45342. sceneEl.addEventListener('render-target-loaded', disableGrabCursor);
  45343. }
  45344. return;
  45345. }
  45346. if (enabled) {
  45347. enableGrabCursor();
  45348. return;
  45349. }
  45350. disableGrabCursor();
  45351. },
  45352. /**
  45353. * Save camera pose before entering VR to restore later if exiting.
  45354. */
  45355. saveCameraPose: function () {
  45356. var el = this.el;
  45357. this.savedPose.position.copy(el.object3D.position);
  45358. this.savedPose.rotation.copy(el.object3D.rotation);
  45359. this.hasSavedPose = true;
  45360. },
  45361. /**
  45362. * Reset camera pose to before entering VR.
  45363. */
  45364. restoreCameraPose: function () {
  45365. var el = this.el;
  45366. var savedPose = this.savedPose;
  45367. if (!this.hasSavedPose) { return; }
  45368. // Reset camera orientation.
  45369. el.object3D.position.copy(savedPose.position);
  45370. el.object3D.rotation.copy(savedPose.rotation);
  45371. this.hasSavedPose = false;
  45372. }
  45373. });
  45374. },{"../core/component":105,"../lib/three":154,"../utils":178,"../utils/":178}],67:[function(_dereq_,module,exports){
  45375. /* global Promise */
  45376. var utils = _dereq_('../utils/');
  45377. var component = _dereq_('../core/component');
  45378. var THREE = _dereq_('../lib/three');
  45379. var shader = _dereq_('../core/shader');
  45380. var error = utils.debug('components:material:error');
  45381. var registerComponent = component.registerComponent;
  45382. var shaders = shader.shaders;
  45383. var shaderNames = shader.shaderNames;
  45384. /**
  45385. * Material component.
  45386. *
  45387. * @member {object} shader - Determines how material is shaded. Defaults to `standard`,
  45388. * three.js's implementation of PBR. Another standard shading model is `flat` which
  45389. * uses MeshBasicMaterial.
  45390. */
  45391. module.exports.Component = registerComponent('material', {
  45392. schema: {
  45393. alphaTest: {default: 0.0, min: 0.0, max: 1.0},
  45394. depthTest: {default: true},
  45395. depthWrite: {default: true},
  45396. flatShading: {default: false},
  45397. npot: {default: false},
  45398. offset: {type: 'vec2', default: {x: 0, y: 0}},
  45399. opacity: {default: 1.0, min: 0.0, max: 1.0},
  45400. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  45401. shader: {default: 'standard', oneOf: shaderNames, schemaChange: true},
  45402. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  45403. transparent: {default: false},
  45404. vertexColors: {type: 'string', default: 'none', oneOf: ['face', 'vertex']},
  45405. visible: {default: true},
  45406. blending: {default: 'normal', oneOf: ['none', 'normal', 'additive', 'subtractive', 'multiply']}
  45407. },
  45408. init: function () {
  45409. this.material = null;
  45410. },
  45411. /**
  45412. * Update or create material.
  45413. *
  45414. * @param {object|null} oldData
  45415. */
  45416. update: function (oldData) {
  45417. var data = this.data;
  45418. if (!this.shader || data.shader !== oldData.shader) {
  45419. this.updateShader(data.shader);
  45420. }
  45421. this.shader.update(this.data);
  45422. this.updateMaterial(oldData);
  45423. },
  45424. updateSchema: function (data) {
  45425. var currentShader;
  45426. var newShader;
  45427. var schema;
  45428. var shader;
  45429. newShader = data && data.shader;
  45430. currentShader = this.oldData && this.oldData.shader;
  45431. shader = newShader || currentShader;
  45432. schema = shaders[shader] && shaders[shader].schema;
  45433. if (!schema) { error('Unknown shader schema ' + shader); }
  45434. if (currentShader && newShader === currentShader) { return; }
  45435. this.extendSchema(schema);
  45436. this.updateBehavior();
  45437. },
  45438. updateBehavior: function () {
  45439. var key;
  45440. var sceneEl = this.el.sceneEl;
  45441. var schema = this.schema;
  45442. var self = this;
  45443. var tickProperties;
  45444. function tickTime (time, delta) {
  45445. var key;
  45446. for (key in tickProperties) {
  45447. tickProperties[key] = time;
  45448. }
  45449. self.shader.update(tickProperties);
  45450. }
  45451. this.tick = undefined;
  45452. tickProperties = {};
  45453. for (key in schema) {
  45454. if (schema[key].type === 'time') {
  45455. this.tick = tickTime;
  45456. tickProperties[key] = true;
  45457. }
  45458. }
  45459. if (!sceneEl) { return; }
  45460. if (this.tick) {
  45461. sceneEl.addBehavior(this);
  45462. } else {
  45463. sceneEl.removeBehavior(this);
  45464. }
  45465. },
  45466. updateShader: function (shaderName) {
  45467. var data = this.data;
  45468. var Shader = shaders[shaderName] && shaders[shaderName].Shader;
  45469. var shaderInstance;
  45470. if (!Shader) { throw new Error('Unknown shader ' + shaderName); }
  45471. // Get material from A-Frame shader.
  45472. shaderInstance = this.shader = new Shader();
  45473. shaderInstance.el = this.el;
  45474. shaderInstance.init(data);
  45475. this.setMaterial(shaderInstance.material);
  45476. this.updateSchema(data);
  45477. },
  45478. /**
  45479. * Set and update base material properties.
  45480. * Set `needsUpdate` when needed.
  45481. */
  45482. updateMaterial: function (oldData) {
  45483. var data = this.data;
  45484. var material = this.material;
  45485. var oldDataHasKeys;
  45486. // Base material properties.
  45487. material.alphaTest = data.alphaTest;
  45488. material.depthTest = data.depthTest !== false;
  45489. material.depthWrite = data.depthWrite !== false;
  45490. material.opacity = data.opacity;
  45491. material.flatShading = data.flatShading;
  45492. material.side = parseSide(data.side);
  45493. material.transparent = data.transparent !== false || data.opacity < 1.0;
  45494. material.vertexColors = parseVertexColors(data.vertexColors);
  45495. material.visible = data.visible;
  45496. material.blending = parseBlending(data.blending);
  45497. // Check if material needs update.
  45498. for (oldDataHasKeys in oldData) { break; }
  45499. if (oldDataHasKeys &&
  45500. (oldData.alphaTest !== data.alphaTest ||
  45501. oldData.side !== data.side ||
  45502. oldData.vertexColors !== data.vertexColors)) {
  45503. material.needsUpdate = true;
  45504. }
  45505. },
  45506. /**
  45507. * Remove material on remove (callback).
  45508. * Dispose of it from memory and unsubscribe from scene updates.
  45509. */
  45510. remove: function () {
  45511. var defaultMaterial = new THREE.MeshBasicMaterial();
  45512. var material = this.material;
  45513. var object3D = this.el.getObject3D('mesh');
  45514. if (object3D) { object3D.material = defaultMaterial; }
  45515. disposeMaterial(material, this.system);
  45516. },
  45517. /**
  45518. * (Re)create new material. Has side-effects of setting `this.material` and updating
  45519. * material registration in scene.
  45520. *
  45521. * @param {object} data - Material component data.
  45522. * @param {object} type - Material type to create.
  45523. * @returns {object} Material.
  45524. */
  45525. setMaterial: function (material) {
  45526. var el = this.el;
  45527. var mesh;
  45528. var system = this.system;
  45529. if (this.material) { disposeMaterial(this.material, system); }
  45530. this.material = material;
  45531. system.registerMaterial(material);
  45532. // Set on mesh. If mesh does not exist, wait for it.
  45533. mesh = el.getObject3D('mesh');
  45534. if (mesh) {
  45535. mesh.material = material;
  45536. } else {
  45537. el.addEventListener('object3dset', function waitForMesh (evt) {
  45538. if (evt.detail.type !== 'mesh' || evt.target !== el) { return; }
  45539. el.getObject3D('mesh').material = material;
  45540. el.removeEventListener('object3dset', waitForMesh);
  45541. });
  45542. }
  45543. }
  45544. });
  45545. /**
  45546. * Return a three.js constant determining which material face sides to render
  45547. * based on the side parameter (passed as a component property).
  45548. *
  45549. * @param {string} [side=front] - `front`, `back`, or `double`.
  45550. * @returns {number} THREE.FrontSide, THREE.BackSide, or THREE.DoubleSide.
  45551. */
  45552. function parseSide (side) {
  45553. switch (side) {
  45554. case 'back': {
  45555. return THREE.BackSide;
  45556. }
  45557. case 'double': {
  45558. return THREE.DoubleSide;
  45559. }
  45560. default: {
  45561. // Including case `front`.
  45562. return THREE.FrontSide;
  45563. }
  45564. }
  45565. }
  45566. /**
  45567. * Return a three.js constant determining vertex coloring.
  45568. */
  45569. function parseVertexColors (coloring) {
  45570. switch (coloring) {
  45571. case 'face': {
  45572. return THREE.FaceColors;
  45573. }
  45574. case 'vertex': {
  45575. return THREE.VertexColors;
  45576. }
  45577. default: {
  45578. return THREE.NoColors;
  45579. }
  45580. }
  45581. }
  45582. /**
  45583. * Return a three.js constant determining blending
  45584. *
  45585. * @param {string} [blending=normal]
  45586. * - `none`, additive`, `subtractive`,`multiply` or `normal`.
  45587. * @returns {number}
  45588. */
  45589. function parseBlending (blending) {
  45590. switch (blending) {
  45591. case 'none': {
  45592. return THREE.NoBlending;
  45593. }
  45594. case 'additive': {
  45595. return THREE.AdditiveBlending;
  45596. }
  45597. case 'subtractive': {
  45598. return THREE.SubtractiveBlending;
  45599. }
  45600. case 'multiply': {
  45601. return THREE.MultiplyBlending;
  45602. }
  45603. default: {
  45604. return THREE.NormalBlending;
  45605. }
  45606. }
  45607. }
  45608. /**
  45609. * Dispose of material from memory and unsubscribe material from scene updates like fog.
  45610. */
  45611. function disposeMaterial (material, system) {
  45612. material.dispose();
  45613. system.unregisterMaterial(material);
  45614. }
  45615. },{"../core/component":105,"../core/shader":115,"../lib/three":154,"../utils/":178}],68:[function(_dereq_,module,exports){
  45616. var debug = _dereq_('../utils/debug');
  45617. var registerComponent = _dereq_('../core/component').registerComponent;
  45618. var THREE = _dereq_('../lib/three');
  45619. var warn = debug('components:obj-model:warn');
  45620. module.exports.Component = registerComponent('obj-model', {
  45621. schema: {
  45622. mtl: {type: 'model'},
  45623. obj: {type: 'model'}
  45624. },
  45625. init: function () {
  45626. this.model = null;
  45627. this.objLoader = new THREE.OBJLoader();
  45628. this.mtlLoader = new THREE.MTLLoader(this.objLoader.manager);
  45629. // Allow cross-origin images to be loaded.
  45630. this.mtlLoader.crossOrigin = '';
  45631. },
  45632. update: function () {
  45633. var data = this.data;
  45634. if (!data.obj) { return; }
  45635. this.resetMesh();
  45636. this.loadObj(data.obj, data.mtl);
  45637. },
  45638. remove: function () {
  45639. if (!this.model) { return; }
  45640. this.resetMesh();
  45641. },
  45642. resetMesh: function () {
  45643. this.el.removeObject3D('mesh');
  45644. },
  45645. loadObj: function (objUrl, mtlUrl) {
  45646. var self = this;
  45647. var el = this.el;
  45648. var mtlLoader = this.mtlLoader;
  45649. var objLoader = this.objLoader;
  45650. if (mtlUrl) {
  45651. // .OBJ with an .MTL.
  45652. if (el.hasAttribute('material')) {
  45653. warn('Material component properties are ignored when a .MTL is provided');
  45654. }
  45655. mtlLoader.setTexturePath(mtlUrl.substr(0, mtlUrl.lastIndexOf('/') + 1));
  45656. mtlLoader.load(mtlUrl, function (materials) {
  45657. materials.preload();
  45658. objLoader.setMaterials(materials);
  45659. objLoader.load(objUrl, function (objModel) {
  45660. self.model = objModel;
  45661. el.setObject3D('mesh', objModel);
  45662. el.emit('model-loaded', {format: 'obj', model: objModel});
  45663. });
  45664. });
  45665. return;
  45666. }
  45667. // .OBJ only.
  45668. objLoader.load(objUrl, function loadObjOnly (objModel) {
  45669. // Apply material.
  45670. var material = el.components.material;
  45671. if (material) {
  45672. objModel.traverse(function (child) {
  45673. if (child instanceof THREE.Mesh) {
  45674. child.material = material.material;
  45675. }
  45676. });
  45677. }
  45678. self.model = objModel;
  45679. el.setObject3D('mesh', objModel);
  45680. el.emit('model-loaded', {format: 'obj', model: objModel});
  45681. });
  45682. }
  45683. });
  45684. },{"../core/component":105,"../lib/three":154,"../utils/debug":174}],69:[function(_dereq_,module,exports){
  45685. var registerComponent = _dereq_('../core/component').registerComponent;
  45686. var bind = _dereq_('../utils/bind');
  45687. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  45688. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  45689. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  45690. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  45691. var GAMEPAD_ID_PREFIX = 'Oculus Go';
  45692. var OCULUS_GO_CONTROLLER_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus/go/oculus-go-controller.gltf';
  45693. /**
  45694. * Oculus Go controls.
  45695. * Interface with Oculus Go controller and map Gamepad events to
  45696. * controller buttons: trackpad, trigger
  45697. * Load a controller model and highlight the pressed buttons.
  45698. */
  45699. module.exports.Component = registerComponent('oculus-go-controls', {
  45700. schema: {
  45701. hand: {default: ''}, // This informs the degenerate arm model.
  45702. buttonColor: {type: 'color', default: '#FFFFFF'},
  45703. buttonTouchedColor: {type: 'color', default: '#BBBBBB'},
  45704. buttonHighlightColor: {type: 'color', default: '#7A7A7A'},
  45705. model: {default: true},
  45706. rotationOffset: {default: 0},
  45707. armModel: {default: true}
  45708. },
  45709. /**
  45710. * Button IDs:
  45711. * 0 - trackpad
  45712. * 1 - trigger
  45713. */
  45714. mapping: {
  45715. axes: {trackpad: [0, 1]},
  45716. buttons: ['trackpad', 'trigger']
  45717. },
  45718. bindMethods: function () {
  45719. this.onModelLoaded = bind(this.onModelLoaded, this);
  45720. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  45721. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  45722. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  45723. this.onAxisMoved = bind(this.onAxisMoved, this);
  45724. },
  45725. init: function () {
  45726. var self = this;
  45727. this.animationActive = 'pointing';
  45728. this.onButtonChanged = bind(this.onButtonChanged, this);
  45729. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  45730. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  45731. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  45732. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  45733. this.onAxisMoved = bind(this.onAxisMoved, this);
  45734. this.controllerPresent = false;
  45735. this.lastControllerCheck = 0;
  45736. this.bindMethods();
  45737. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // To allow mock.
  45738. this.emitIfAxesChanged = emitIfAxesChanged; // To allow mock.
  45739. },
  45740. addEventListeners: function () {
  45741. var el = this.el;
  45742. el.addEventListener('buttonchanged', this.onButtonChanged);
  45743. el.addEventListener('buttondown', this.onButtonDown);
  45744. el.addEventListener('buttonup', this.onButtonUp);
  45745. el.addEventListener('touchstart', this.onButtonTouchStart);
  45746. el.addEventListener('touchend', this.onButtonTouchEnd);
  45747. el.addEventListener('model-loaded', this.onModelLoaded);
  45748. el.addEventListener('axismove', this.onAxisMoved);
  45749. this.controllerEventsActive = true;
  45750. },
  45751. removeEventListeners: function () {
  45752. var el = this.el;
  45753. el.removeEventListener('buttonchanged', this.onButtonChanged);
  45754. el.removeEventListener('buttondown', this.onButtonDown);
  45755. el.removeEventListener('buttonup', this.onButtonUp);
  45756. el.removeEventListener('touchstart', this.onButtonTouchStart);
  45757. el.removeEventListener('touchend', this.onButtonTouchEnd);
  45758. el.removeEventListener('model-loaded', this.onModelLoaded);
  45759. el.removeEventListener('axismove', this.onAxisMoved);
  45760. this.controllerEventsActive = false;
  45761. },
  45762. checkIfControllerPresent: function () {
  45763. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  45764. this.data.hand ? {hand: this.data.hand} : {});
  45765. },
  45766. play: function () {
  45767. this.checkIfControllerPresent();
  45768. this.addControllersUpdateListener();
  45769. },
  45770. pause: function () {
  45771. this.removeEventListeners();
  45772. this.removeControllersUpdateListener();
  45773. },
  45774. injectTrackedControls: function () {
  45775. var el = this.el;
  45776. var data = this.data;
  45777. el.setAttribute('tracked-controls', {
  45778. armModel: data.armModel,
  45779. idPrefix: GAMEPAD_ID_PREFIX,
  45780. rotationOffset: data.rotationOffset
  45781. });
  45782. if (!this.data.model) { return; }
  45783. this.el.setAttribute('gltf-model', OCULUS_GO_CONTROLLER_MODEL_URL);
  45784. },
  45785. addControllersUpdateListener: function () {
  45786. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  45787. },
  45788. removeControllersUpdateListener: function () {
  45789. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  45790. },
  45791. onControllersUpdate: function () {
  45792. this.checkIfControllerPresent();
  45793. },
  45794. // No need for onButtonChanged, since Oculus Go controller has no analog buttons.
  45795. onModelLoaded: function (evt) {
  45796. var controllerObject3D = evt.detail.model;
  45797. var buttonMeshes;
  45798. if (!this.data.model) { return; }
  45799. buttonMeshes = this.buttonMeshes = {};
  45800. buttonMeshes.trigger = controllerObject3D.getObjectByName('oculus_go_button_trigger');
  45801. buttonMeshes.trackpad = controllerObject3D.getObjectByName('oculus_go_touchpad');
  45802. },
  45803. onButtonChanged: function (evt) {
  45804. var button = this.mapping.buttons[evt.detail.id];
  45805. if (!button) return;
  45806. // Pass along changed event with button state, using button mapping for convenience.
  45807. this.el.emit(button + 'changed', evt.detail.state);
  45808. },
  45809. onAxisMoved: function (evt) {
  45810. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  45811. },
  45812. updateModel: function (buttonName, evtName) {
  45813. if (!this.data.model) { return; }
  45814. this.updateButtonModel(buttonName, evtName);
  45815. },
  45816. updateButtonModel: function (buttonName, state) {
  45817. var buttonMeshes = this.buttonMeshes;
  45818. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  45819. var color;
  45820. switch (state) {
  45821. case 'down':
  45822. color = this.data.buttonHighlightColor;
  45823. break;
  45824. case 'touchstart':
  45825. color = this.data.buttonTouchedColor;
  45826. break;
  45827. default:
  45828. color = this.data.buttonColor;
  45829. }
  45830. buttonMeshes[buttonName].material.color.set(color);
  45831. }
  45832. });
  45833. },{"../core/component":105,"../utils/bind":172,"../utils/tracked-controls":185}],70:[function(_dereq_,module,exports){
  45834. var bind = _dereq_('../utils/bind');
  45835. var registerComponent = _dereq_('../core/component').registerComponent;
  45836. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  45837. var THREE = _dereq_('../lib/three');
  45838. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  45839. var TOUCH_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/oculus/oculus-touch-controller-';
  45840. var TOUCH_CONTROLLER_MODEL_URL = {
  45841. left: TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.gltf',
  45842. right: TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.gltf'
  45843. };
  45844. var GAMEPAD_ID_PREFIX = 'Oculus Touch';
  45845. var DEFAULT_MODEL_PIVOT_OFFSET = new THREE.Vector3(0, 0, -0.053);
  45846. var RAY_ORIGIN = {
  45847. left: {origin: {x: 0.008, y: -0.004, z: 0}, direction: {x: 0, y: -0.8, z: -1}},
  45848. right: {origin: {x: -0.008, y: -0.004, z: 0}, direction: {x: 0, y: -0.8, z: -1}}
  45849. };
  45850. /**
  45851. * Oculus Touch controls.
  45852. * Interface with Oculus Touch controllers and map Gamepad events to
  45853. * controller buttons: thumbstick, trigger, grip, xbutton, ybutton, surface
  45854. * Load a controller model and highlight the pressed buttons.
  45855. */
  45856. module.exports.Component = registerComponent('oculus-touch-controls', {
  45857. schema: {
  45858. hand: {default: 'left'},
  45859. buttonColor: {type: 'color', default: '#999'}, // Off-white.
  45860. buttonTouchColor: {type: 'color', default: '#8AB'},
  45861. buttonHighlightColor: {type: 'color', default: '#2DF'}, // Light blue.
  45862. model: {default: true},
  45863. orientationOffset: {type: 'vec3', default: {x: 43, y: 0, z: 0}}
  45864. },
  45865. /**
  45866. * Button IDs:
  45867. * 0 - thumbstick (which has separate axismove / thumbstickmoved events)
  45868. * 1 - trigger (with analog value, which goes up to 1)
  45869. * 2 - grip (with analog value, which goes up to 1)
  45870. * 3 - X (left) or A (right)
  45871. * 4 - Y (left) or B (right)
  45872. * 5 - surface (touch only)
  45873. */
  45874. mapping: {
  45875. left: {
  45876. axes: {thumbstick: [0, 1]},
  45877. buttons: ['thumbstick', 'trigger', 'grip', 'xbutton', 'ybutton', 'surface']
  45878. },
  45879. right: {
  45880. axes: {thumbstick: [0, 1]},
  45881. buttons: ['thumbstick', 'trigger', 'grip', 'abutton', 'bbutton', 'surface']
  45882. }
  45883. },
  45884. bindMethods: function () {
  45885. this.onModelLoaded = bind(this.onModelLoaded, this);
  45886. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  45887. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  45888. this.onAxisMoved = bind(this.onAxisMoved, this);
  45889. },
  45890. init: function () {
  45891. var self = this;
  45892. this.onButtonChanged = bind(this.onButtonChanged, this);
  45893. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self, self.data.hand); };
  45894. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self, self.data.hand); };
  45895. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self, self.data.hand); };
  45896. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self, self.data.hand); };
  45897. this.controllerPresent = false;
  45898. this.lastControllerCheck = 0;
  45899. this.previousButtonValues = {};
  45900. this.bindMethods();
  45901. // Allow mock.
  45902. this.emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  45903. this.checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  45904. },
  45905. addEventListeners: function () {
  45906. var el = this.el;
  45907. el.addEventListener('buttonchanged', this.onButtonChanged);
  45908. el.addEventListener('buttondown', this.onButtonDown);
  45909. el.addEventListener('buttonup', this.onButtonUp);
  45910. el.addEventListener('touchstart', this.onButtonTouchStart);
  45911. el.addEventListener('touchend', this.onButtonTouchEnd);
  45912. el.addEventListener('axismove', this.onAxisMoved);
  45913. el.addEventListener('model-loaded', this.onModelLoaded);
  45914. this.controllerEventsActive = true;
  45915. },
  45916. removeEventListeners: function () {
  45917. var el = this.el;
  45918. el.removeEventListener('buttonchanged', this.onButtonChanged);
  45919. el.removeEventListener('buttondown', this.onButtonDown);
  45920. el.removeEventListener('buttonup', this.onButtonUp);
  45921. el.removeEventListener('touchstart', this.onButtonTouchStart);
  45922. el.removeEventListener('touchend', this.onButtonTouchEnd);
  45923. el.removeEventListener('axismove', this.onAxisMoved);
  45924. el.removeEventListener('model-loaded', this.onModelLoaded);
  45925. this.controllerEventsActive = false;
  45926. },
  45927. checkIfControllerPresent: function () {
  45928. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  45929. hand: this.data.hand
  45930. });
  45931. },
  45932. play: function () {
  45933. this.checkIfControllerPresent();
  45934. this.addControllersUpdateListener();
  45935. },
  45936. pause: function () {
  45937. this.removeEventListeners();
  45938. this.removeControllersUpdateListener();
  45939. },
  45940. loadModel: function () {
  45941. var data = this.data;
  45942. if (!data.model) { return; }
  45943. this.el.setAttribute('gltf-model', 'url(' + TOUCH_CONTROLLER_MODEL_URL[data.hand] + ')');
  45944. },
  45945. injectTrackedControls: function () {
  45946. var data = this.data;
  45947. this.el.setAttribute('tracked-controls', {
  45948. id: data.hand === 'right' ? 'Oculus Touch (Right)' : 'Oculus Touch (Left)',
  45949. controller: 0,
  45950. hand: data.hand,
  45951. orientationOffset: data.orientationOffset
  45952. });
  45953. this.loadModel();
  45954. },
  45955. addControllersUpdateListener: function () {
  45956. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  45957. },
  45958. removeControllersUpdateListener: function () {
  45959. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  45960. },
  45961. onControllersUpdate: function () {
  45962. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  45963. this.checkIfControllerPresent();
  45964. },
  45965. onButtonChanged: function (evt) {
  45966. var button = this.mapping[this.data.hand].buttons[evt.detail.id];
  45967. var buttonMeshes = this.buttonMeshes;
  45968. var analogValue;
  45969. if (!button) { return; }
  45970. if (button === 'trigger' || button === 'grip') { analogValue = evt.detail.state.value; }
  45971. // Update trigger and/or grip meshes, if any.
  45972. if (buttonMeshes) {
  45973. if (button === 'trigger' && buttonMeshes.trigger) {
  45974. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 24);
  45975. }
  45976. if (button === 'grip' && buttonMeshes.grip) {
  45977. buttonMeshes.grip.rotation.y = (this.data.hand === 'left' ? -1 : 1) * analogValue * (Math.PI / 60);
  45978. }
  45979. }
  45980. // Pass along changed event with button state, using the buttom mapping for convenience.
  45981. this.el.emit(button + 'changed', evt.detail.state);
  45982. },
  45983. onModelLoaded: function (evt) {
  45984. var controllerObject3D = evt.detail.model;
  45985. var buttonMeshes;
  45986. if (!this.data.model) { return; }
  45987. var leftHand = this.data.hand === 'left';
  45988. buttonMeshes = this.buttonMeshes = {};
  45989. buttonMeshes.grip = controllerObject3D.getObjectByName(leftHand ? 'buttonHand_oculus-touch-controller-left.004' : 'buttonHand_oculus-touch-controller-right.005');
  45990. buttonMeshes.thumbstick = controllerObject3D.getObjectByName(leftHand ? 'stick_oculus-touch-controller-left.007' : 'stick_oculus-touch-controller-right.004');
  45991. buttonMeshes.trigger = controllerObject3D.getObjectByName(leftHand ? 'buttonTrigger_oculus-touch-controller-left.005' : 'buttonTrigger_oculus-touch-controller-right.006');
  45992. buttonMeshes.xbutton = controllerObject3D.getObjectByName('buttonX_oculus-touch-controller-left.002');
  45993. buttonMeshes.abutton = controllerObject3D.getObjectByName('buttonA_oculus-touch-controller-right.002');
  45994. buttonMeshes.ybutton = controllerObject3D.getObjectByName('buttonY_oculus-touch-controller-left.001');
  45995. buttonMeshes.bbutton = controllerObject3D.getObjectByName('buttonB_oculus-touch-controller-right.003');
  45996. // Offset pivot point
  45997. controllerObject3D.position.copy(DEFAULT_MODEL_PIVOT_OFFSET);
  45998. this.el.emit('controllermodelready', {
  45999. name: 'oculus-touch-controls',
  46000. model: this.data.model,
  46001. rayOrigin: RAY_ORIGIN[this.data.hand]
  46002. });
  46003. },
  46004. onAxisMoved: function (evt) {
  46005. this.emitIfAxesChanged(this, this.mapping[this.data.hand].axes, evt);
  46006. },
  46007. updateModel: function (buttonName, evtName) {
  46008. if (!this.data.model) { return; }
  46009. this.updateButtonModel(buttonName, evtName);
  46010. },
  46011. updateButtonModel: function (buttonName, state) {
  46012. var color = (state === 'up' || state === 'touchend') ? this.data.buttonColor : state === 'touchstart' ? this.data.buttonTouchColor : this.data.buttonHighlightColor;
  46013. var buttonMeshes = this.buttonMeshes;
  46014. if (!this.data.model) { return; }
  46015. if (buttonMeshes && buttonMeshes[buttonName]) {
  46016. buttonMeshes[buttonName].material.color.set(color);
  46017. }
  46018. }
  46019. });
  46020. },{"../core/component":105,"../lib/three":154,"../utils/bind":172,"../utils/tracked-controls":185}],71:[function(_dereq_,module,exports){
  46021. var registerComponent = _dereq_('../core/component').registerComponent;
  46022. module.exports.Component = registerComponent('position', {
  46023. schema: {type: 'vec3'},
  46024. update: function () {
  46025. var object3D = this.el.object3D;
  46026. var data = this.data;
  46027. object3D.position.set(data.x, data.y, data.z);
  46028. },
  46029. remove: function () {
  46030. // Pretty much for mixins.
  46031. this.el.object3D.position.set(0, 0, 0);
  46032. }
  46033. });
  46034. },{"../core/component":105}],72:[function(_dereq_,module,exports){
  46035. /* global MutationObserver */
  46036. var registerComponent = _dereq_('../core/component').registerComponent;
  46037. var THREE = _dereq_('../lib/three');
  46038. var utils = _dereq_('../utils/');
  46039. var warn = utils.debug('components:raycaster:warn');
  46040. // Defines selectors that should be 'safe' for the MutationObserver used to
  46041. // refresh the whitelist. Matches classnames, IDs, and presence of attributes.
  46042. // Selectors for the value of an attribute, like [position=0 2 0], cannot be
  46043. // reliably detected and are therefore disallowed.
  46044. var OBSERVER_SELECTOR_RE = /^[\w\s-.,[\]#]*$/;
  46045. // Configuration for the MutationObserver used to refresh the whitelist.
  46046. // Listens for addition/removal of elements and attributes within the scene.
  46047. var OBSERVER_CONFIG = {
  46048. childList: true,
  46049. attributes: true,
  46050. subtree: true
  46051. };
  46052. var EVENTS = {
  46053. INTERSECT: 'raycaster-intersected',
  46054. INTERSECTION: 'raycaster-intersection',
  46055. INTERSECT_CLEAR: 'raycaster-intersected-cleared',
  46056. INTERSECTION_CLEAR: 'raycaster-intersection-cleared'
  46057. };
  46058. /**
  46059. * Raycaster component.
  46060. *
  46061. * Pass options to three.js Raycaster including which objects to test.
  46062. * Poll for intersections.
  46063. * Emit event on origin entity and on target entity on intersect.
  46064. *
  46065. * @member {array} intersectedEls - List of currently intersected entities.
  46066. * @member {array} objects - Cached list of meshes to intersect.
  46067. * @member {number} prevCheckTime - Previous time intersection was checked. To help interval.
  46068. * @member {object} raycaster - three.js Raycaster.
  46069. */
  46070. module.exports.Component = registerComponent('raycaster', {
  46071. schema: {
  46072. autoRefresh: {default: true},
  46073. direction: {type: 'vec3', default: {x: 0, y: 0, z: -1}},
  46074. enabled: {default: true},
  46075. far: {default: 1000},
  46076. interval: {default: 0},
  46077. near: {default: 0},
  46078. objects: {default: ''},
  46079. origin: {type: 'vec3'},
  46080. recursive: {default: true},
  46081. showLine: {default: false},
  46082. useWorldCoordinates: {default: false}
  46083. },
  46084. multiple: true,
  46085. init: function () {
  46086. this.clearedIntersectedEls = [];
  46087. this.unitLineEndVec3 = new THREE.Vector3();
  46088. this.intersectedEls = [];
  46089. this.intersections = [];
  46090. this.newIntersectedEls = [];
  46091. this.newIntersections = [];
  46092. this.objects = [];
  46093. this.prevCheckTime = undefined;
  46094. this.prevIntersectedEls = [];
  46095. this.rawIntersections = [];
  46096. this.raycaster = new THREE.Raycaster();
  46097. this.updateOriginDirection();
  46098. this.setDirty = this.setDirty.bind(this);
  46099. this.updateLine = this.updateLine.bind(this);
  46100. this.observer = new MutationObserver(this.setDirty);
  46101. this.dirty = true;
  46102. this.lineEndVec3 = new THREE.Vector3();
  46103. this.otherLineEndVec3 = new THREE.Vector3();
  46104. this.lineData = {end: this.lineEndVec3};
  46105. this.getIntersection = this.getIntersection.bind(this);
  46106. this.intersectedDetail = {el: this.el, getIntersection: this.getIntersection};
  46107. this.intersectedClearedDetail = {el: this.el};
  46108. this.intersectionClearedDetail = {clearedEls: this.clearedIntersectedEls};
  46109. this.intersectionDetail = {};
  46110. },
  46111. /**
  46112. * Create or update raycaster object.
  46113. */
  46114. update: function (oldData) {
  46115. var data = this.data;
  46116. var el = this.el;
  46117. var raycaster = this.raycaster;
  46118. // Set raycaster properties.
  46119. raycaster.far = data.far;
  46120. raycaster.near = data.near;
  46121. // Draw line.
  46122. if (data.showLine &&
  46123. (data.far !== oldData.far || data.origin !== oldData.origin ||
  46124. data.direction !== oldData.direction || !oldData.showLine)) {
  46125. // Calculate unit vector for line direction. Can be multiplied via scalar to performantly
  46126. // adjust line length.
  46127. this.unitLineEndVec3.copy(data.origin).add(data.direction).normalize();
  46128. this.drawLine();
  46129. }
  46130. if (!data.showLine && oldData.showLine) {
  46131. el.removeAttribute('line');
  46132. }
  46133. if (data.objects !== oldData.objects && !OBSERVER_SELECTOR_RE.test(data.objects)) {
  46134. warn('[raycaster] Selector "' + data.objects +
  46135. '" may not update automatically with DOM changes.');
  46136. }
  46137. if (!data.objects) {
  46138. warn('[raycaster] For performance, please define raycaster.objects when using ' +
  46139. 'raycaster or cursor components to whitelist which entities to intersect with. ' +
  46140. 'e.g., raycaster="objects: [data-raycastable]".');
  46141. }
  46142. if (data.autoRefresh !== oldData.autoRefresh && el.isPlaying) {
  46143. data.autoRefresh
  46144. ? this.addEventListeners()
  46145. : this.removeEventListeners();
  46146. }
  46147. if (oldData.enabled && !data.enabled) { this.clearAllIntersections(); }
  46148. this.setDirty();
  46149. },
  46150. play: function () {
  46151. this.addEventListeners();
  46152. },
  46153. pause: function () {
  46154. this.removeEventListeners();
  46155. },
  46156. remove: function () {
  46157. if (this.data.showLine) {
  46158. this.el.removeAttribute('line');
  46159. }
  46160. this.clearAllIntersections();
  46161. },
  46162. addEventListeners: function () {
  46163. if (!this.data.autoRefresh) { return; }
  46164. this.observer.observe(this.el.sceneEl, OBSERVER_CONFIG);
  46165. this.el.sceneEl.addEventListener('object3dset', this.setDirty);
  46166. this.el.sceneEl.addEventListener('object3dremove', this.setDirty);
  46167. },
  46168. removeEventListeners: function () {
  46169. this.observer.disconnect();
  46170. this.el.sceneEl.removeEventListener('object3dset', this.setDirty);
  46171. this.el.sceneEl.removeEventListener('object3dremove', this.setDirty);
  46172. },
  46173. /**
  46174. * Mark the object list as dirty, to be refreshed before next raycast.
  46175. */
  46176. setDirty: function () {
  46177. this.dirty = true;
  46178. },
  46179. /**
  46180. * Update list of objects to test for intersection.
  46181. */
  46182. refreshObjects: function () {
  46183. var data = this.data;
  46184. var els;
  46185. // If objects not defined, intersect with everything.
  46186. els = data.objects
  46187. ? this.el.sceneEl.querySelectorAll(data.objects)
  46188. : this.el.sceneEl.querySelectorAll('*');
  46189. this.objects = this.flattenObject3DMaps(els);
  46190. this.dirty = false;
  46191. },
  46192. /**
  46193. * Check for intersections and cleared intersections on an interval.
  46194. */
  46195. tick: function (time) {
  46196. var data = this.data;
  46197. var prevCheckTime = this.prevCheckTime;
  46198. if (!data.enabled) { return; }
  46199. // Only check for intersection if interval time has passed.
  46200. if (prevCheckTime && (time - prevCheckTime < data.interval)) { return; }
  46201. // Update check time.
  46202. this.prevCheckTime = time;
  46203. this.checkIntersections();
  46204. },
  46205. /**
  46206. * Raycast for intersections and emit events for current and cleared inersections.
  46207. */
  46208. checkIntersections: function () {
  46209. var clearedIntersectedEls = this.clearedIntersectedEls;
  46210. var el = this.el;
  46211. var data = this.data;
  46212. var i;
  46213. var intersectedEls = this.intersectedEls;
  46214. var intersection;
  46215. var intersections = this.intersections;
  46216. var newIntersectedEls = this.newIntersectedEls;
  46217. var newIntersections = this.newIntersections;
  46218. var prevIntersectedEls = this.prevIntersectedEls;
  46219. var rawIntersections = this.rawIntersections;
  46220. // Refresh the object whitelist if needed.
  46221. if (this.dirty) { this.refreshObjects(); }
  46222. // Store old previously intersected entities.
  46223. copyArray(this.prevIntersectedEls, this.intersectedEls);
  46224. // Raycast.
  46225. this.updateOriginDirection();
  46226. rawIntersections.length = 0;
  46227. this.raycaster.intersectObjects(this.objects, data.recursive, rawIntersections);
  46228. // Only keep intersections against objects that have a reference to an entity.
  46229. intersections.length = 0;
  46230. intersectedEls.length = 0;
  46231. for (i = 0; i < rawIntersections.length; i++) {
  46232. intersection = rawIntersections[i];
  46233. // Don't intersect with own line.
  46234. if (data.showLine && intersection.object === el.getObject3D('line')) {
  46235. continue;
  46236. }
  46237. if (intersection.object.el) {
  46238. intersections.push(intersection);
  46239. intersectedEls.push(intersection.object.el);
  46240. }
  46241. }
  46242. // Get newly intersected entities.
  46243. newIntersections.length = 0;
  46244. newIntersectedEls.length = 0;
  46245. for (i = 0; i < intersections.length; i++) {
  46246. if (prevIntersectedEls.indexOf(intersections[i].object.el) === -1) {
  46247. newIntersections.push(intersections[i]);
  46248. newIntersectedEls.push(intersections[i].object.el);
  46249. }
  46250. }
  46251. // Emit intersection cleared on both entities per formerly intersected entity.
  46252. clearedIntersectedEls.length = 0;
  46253. for (i = 0; i < prevIntersectedEls.length; i++) {
  46254. if (intersectedEls.indexOf(prevIntersectedEls[i]) !== -1) { continue; }
  46255. prevIntersectedEls[i].emit(EVENTS.INTERSECT_CLEAR,
  46256. this.intersectedClearedDetail);
  46257. clearedIntersectedEls.push(prevIntersectedEls[i]);
  46258. }
  46259. if (clearedIntersectedEls.length) {
  46260. el.emit(EVENTS.INTERSECTION_CLEAR, this.intersectionClearedDetail);
  46261. }
  46262. // Emit intersected on intersected entity per intersected entity.
  46263. for (i = 0; i < newIntersectedEls.length; i++) {
  46264. newIntersectedEls[i].emit(EVENTS.INTERSECT, this.intersectedDetail);
  46265. }
  46266. // Emit all intersections at once on raycasting entity.
  46267. if (newIntersections.length) {
  46268. this.intersectionDetail.els = newIntersectedEls;
  46269. this.intersectionDetail.intersections = newIntersections;
  46270. el.emit(EVENTS.INTERSECTION, this.intersectionDetail);
  46271. }
  46272. // Update line length.
  46273. setTimeout(this.updateLine);
  46274. },
  46275. updateLine: function () {
  46276. var el = this.el;
  46277. var intersections = this.intersections;
  46278. var lineLength;
  46279. if (this.data.showLine) {
  46280. if (intersections.length) {
  46281. if (intersections[0].object.el === el && intersections[1]) {
  46282. lineLength = intersections[1].distance;
  46283. } else {
  46284. lineLength = intersections[0].distance;
  46285. }
  46286. }
  46287. this.drawLine(lineLength);
  46288. }
  46289. },
  46290. /**
  46291. * Return the most recent intersection details for a given entity, if any.
  46292. * @param {AEntity} el
  46293. * @return {Object}
  46294. */
  46295. getIntersection: function (el) {
  46296. var i;
  46297. var intersection;
  46298. for (i = 0; i < this.intersections.length; i++) {
  46299. intersection = this.intersections[i];
  46300. if (intersection.object.el === el) { return intersection; }
  46301. }
  46302. return null;
  46303. },
  46304. /**
  46305. * Update origin and direction of raycaster using entity transforms and supplied origin or
  46306. * direction offsets.
  46307. */
  46308. updateOriginDirection: (function () {
  46309. var direction = new THREE.Vector3();
  46310. var originVec3 = new THREE.Vector3();
  46311. // Closure to make quaternion/vector3 objects private.
  46312. return function updateOriginDirection () {
  46313. var el = this.el;
  46314. var data = this.data;
  46315. if (data.useWorldCoordinates) {
  46316. this.raycaster.set(data.origin, data.direction);
  46317. return;
  46318. }
  46319. // Grab the position and rotation. (As a side effect, this updates el.object3D.matrixWorld.)
  46320. el.object3D.getWorldPosition(originVec3);
  46321. // If non-zero origin, translate the origin into world space.
  46322. if (data.origin.x !== 0 || data.origin.y !== 0 || data.origin.z !== 0) {
  46323. originVec3 = el.object3D.localToWorld(originVec3.copy(data.origin));
  46324. }
  46325. // three.js raycaster direction is relative to 0, 0, 0 NOT the origin / offset we
  46326. // provide. Apply the offset to the direction, then rotation from the object,
  46327. // and normalize.
  46328. direction.copy(data.direction).transformDirection(el.object3D.matrixWorld).normalize();
  46329. // Apply offset and direction, in world coordinates.
  46330. this.raycaster.set(originVec3, direction);
  46331. };
  46332. })(),
  46333. /**
  46334. * Create or update line to give raycaster visual representation.
  46335. * Customize the line through through line component.
  46336. * We draw the line in the raycaster component to customize the line to the
  46337. * raycaster's origin, direction, and far.
  46338. *
  46339. * Unlike the raycaster, we create the line as a child of the object. The line will
  46340. * be affected by the transforms of the objects, so we don't have to calculate transforms
  46341. * like we do with the raycaster.
  46342. *
  46343. * @param {number} length - Length of line. Pass in to shorten the line to the intersection
  46344. * point. If not provided, length will default to the max length, `raycaster.far`.
  46345. */
  46346. drawLine: function (length) {
  46347. var data = this.data;
  46348. var el = this.el;
  46349. var endVec3;
  46350. // Switch each time vector so line update triggered and to avoid unnecessary vector clone.
  46351. endVec3 = this.lineData.end === this.lineEndVec3
  46352. ? this.otherLineEndVec3
  46353. : this.lineEndVec3;
  46354. // Treat Infinity as 1000m for the line.
  46355. if (length === undefined) {
  46356. length = data.far === Infinity ? 1000 : data.far;
  46357. }
  46358. // Update the length of the line if given. `unitLineEndVec3` is the direction
  46359. // given by data.direction, then we apply a scalar to give it a length.
  46360. this.lineData.start = data.origin;
  46361. this.lineData.end = endVec3.copy(this.unitLineEndVec3).multiplyScalar(length);
  46362. el.setAttribute('line', this.lineData);
  46363. },
  46364. /**
  46365. * Return A-Frame attachments of each element's object3D group (e.g., mesh).
  46366. * Children are flattened by one level, removing the THREE.Group wrapper,
  46367. * so that non-recursive raycasting remains useful.
  46368. *
  46369. * Only push children defined as component attachemnts (e.g., setObject3D),
  46370. * NOT actual children in the scene graph hierarchy.
  46371. *
  46372. * @param {Array<Element>} els
  46373. * @return {Array<THREE.Object3D>}
  46374. */
  46375. flattenObject3DMaps: function (els) {
  46376. var key;
  46377. var i;
  46378. var objects = this.objects;
  46379. // Push meshes and other attachments onto list of objects to intersect.
  46380. objects.length = 0;
  46381. for (i = 0; i < els.length; i++) {
  46382. if (els[i].isEntity && els[i].object3D) {
  46383. for (key in els[i].object3DMap) {
  46384. objects.push(els[i].getObject3D(key));
  46385. }
  46386. }
  46387. }
  46388. return objects;
  46389. },
  46390. clearAllIntersections: function () {
  46391. var i;
  46392. for (i = 0; i < this.intersectedEls.length; i++) {
  46393. this.intersectedEls[i].emit(EVENTS.INTERSECT_CLEAR,
  46394. this.intersectedClearedDetail);
  46395. }
  46396. copyArray(this.clearedIntersectedEls, this.intersectedEls);
  46397. this.intersectedEls.length = 0;
  46398. this.intersections.length = 0;
  46399. this.el.emit(EVENTS.INTERSECTION_CLEAR, this.intersectionClearedDetail);
  46400. }
  46401. });
  46402. /**
  46403. * Copy contents of one array to another without allocating new array.
  46404. */
  46405. function copyArray (a, b) {
  46406. var i;
  46407. a.length = b.length;
  46408. for (i = 0; i < b.length; i++) {
  46409. a[i] = b[i];
  46410. }
  46411. }
  46412. },{"../core/component":105,"../lib/three":154,"../utils/":178}],73:[function(_dereq_,module,exports){
  46413. var degToRad = _dereq_('../lib/three').Math.degToRad;
  46414. var registerComponent = _dereq_('../core/component').registerComponent;
  46415. module.exports.Component = registerComponent('rotation', {
  46416. schema: {type: 'vec3'},
  46417. /**
  46418. * Updates object3D rotation.
  46419. */
  46420. update: function () {
  46421. var data = this.data;
  46422. var object3D = this.el.object3D;
  46423. object3D.rotation.set(degToRad(data.x), degToRad(data.y), degToRad(data.z));
  46424. object3D.rotation.order = 'YXZ';
  46425. },
  46426. remove: function () {
  46427. // Pretty much for mixins.
  46428. this.el.object3D.rotation.set(0, 0, 0);
  46429. }
  46430. });
  46431. },{"../core/component":105,"../lib/three":154}],74:[function(_dereq_,module,exports){
  46432. var registerComponent = _dereq_('../core/component').registerComponent;
  46433. // Avoids triggering a zero-determinant which makes object3D matrix non-invertible.
  46434. var zeroScale = 0.00001;
  46435. module.exports.Component = registerComponent('scale', {
  46436. schema: {
  46437. type: 'vec3',
  46438. default: {x: 1, y: 1, z: 1}
  46439. },
  46440. update: function () {
  46441. var data = this.data;
  46442. var object3D = this.el.object3D;
  46443. var x = data.x === 0 ? zeroScale : data.x;
  46444. var y = data.y === 0 ? zeroScale : data.y;
  46445. var z = data.z === 0 ? zeroScale : data.z;
  46446. object3D.scale.set(x, y, z);
  46447. },
  46448. remove: function () {
  46449. // Pretty much for mixins.
  46450. this.el.object3D.scale.set(1, 1, 1);
  46451. }
  46452. });
  46453. },{"../core/component":105}],75:[function(_dereq_,module,exports){
  46454. /* global THREE */
  46455. var register = _dereq_('../../core/component').registerComponent;
  46456. module.exports.Component = register('background', {
  46457. schema: {
  46458. color: {type: 'color', default: 'black'},
  46459. transparent: {default: false}
  46460. },
  46461. update: function () {
  46462. var data = this.data;
  46463. var object3D = this.el.object3D;
  46464. if (data.transparent) {
  46465. object3D.background = null;
  46466. return;
  46467. }
  46468. object3D.background = new THREE.Color(data.color);
  46469. }
  46470. });
  46471. },{"../../core/component":105}],76:[function(_dereq_,module,exports){
  46472. var register = _dereq_('../../core/component').registerComponent;
  46473. module.exports.Component = register('debug', {
  46474. schema: {default: true}
  46475. });
  46476. },{"../../core/component":105}],77:[function(_dereq_,module,exports){
  46477. var registerComponent = _dereq_('../../core/component').registerComponent;
  46478. /**
  46479. * Component to embed an a-frame scene within the layout of a 2D page.
  46480. */
  46481. module.exports.Component = registerComponent('embedded', {
  46482. dependencies: ['vr-mode-ui'],
  46483. schema: {default: true},
  46484. update: function () {
  46485. var sceneEl = this.el;
  46486. var enterVREl = sceneEl.querySelector('.a-enter-vr');
  46487. if (this.data === true) {
  46488. if (enterVREl) { enterVREl.classList.add('embedded'); }
  46489. sceneEl.removeFullScreenStyles();
  46490. } else {
  46491. if (enterVREl) { enterVREl.classList.remove('embedded'); }
  46492. sceneEl.addFullScreenStyles();
  46493. }
  46494. }
  46495. });
  46496. },{"../../core/component":105}],78:[function(_dereq_,module,exports){
  46497. var register = _dereq_('../../core/component').registerComponent;
  46498. var THREE = _dereq_('../../lib/three');
  46499. var debug = _dereq_('../../utils/debug');
  46500. var warn = debug('components:fog:warn');
  46501. /**
  46502. * Fog component.
  46503. * Applies only to the scene entity.
  46504. */
  46505. module.exports.Component = register('fog', {
  46506. schema: {
  46507. color: {type: 'color', default: '#000'},
  46508. density: {default: 0.00025},
  46509. far: {default: 1000, min: 0},
  46510. near: {default: 1, min: 0},
  46511. type: {default: 'linear', oneOf: ['linear', 'exponential']}
  46512. },
  46513. update: function () {
  46514. var data = this.data;
  46515. var el = this.el;
  46516. var fog = this.el.object3D.fog;
  46517. if (!el.isScene) {
  46518. warn('Fog component can only be applied to <a-scene>');
  46519. return;
  46520. }
  46521. // (Re)create fog if fog doesn't exist or fog type changed.
  46522. if (!fog || data.type !== fog.name) {
  46523. el.object3D.fog = getFog(data);
  46524. el.systems.material.updateMaterials();
  46525. return;
  46526. }
  46527. // Fog data changed. Update fog.
  46528. Object.keys(this.schema).forEach(function (key) {
  46529. var value = data[key];
  46530. if (key === 'color') { value = new THREE.Color(value); }
  46531. fog[key] = value;
  46532. });
  46533. },
  46534. /**
  46535. * Remove fog on remove (callback).
  46536. */
  46537. remove: function () {
  46538. var fog = this.el.object3D.fog;
  46539. if (!fog) { return; }
  46540. fog.far = 0;
  46541. fog.near = 0.1;
  46542. }
  46543. });
  46544. /**
  46545. * Creates a fog object. Sets fog.name to be able to detect fog type changes.
  46546. *
  46547. * @param {object} data - Fog data.
  46548. * @returns {object} fog
  46549. */
  46550. function getFog (data) {
  46551. var fog;
  46552. if (data.type === 'exponential') {
  46553. fog = new THREE.FogExp2(data.color, data.density);
  46554. } else {
  46555. fog = new THREE.Fog(data.color, data.near, data.far);
  46556. }
  46557. fog.name = data.type;
  46558. return fog;
  46559. }
  46560. },{"../../core/component":105,"../../lib/three":154,"../../utils/debug":174}],79:[function(_dereq_,module,exports){
  46561. (function (process){
  46562. /* global AFRAME */
  46563. var AFRAME_INJECTED = _dereq_('../../constants').AFRAME_INJECTED;
  46564. var pkg = _dereq_('../../../package');
  46565. var registerComponent = _dereq_('../../core/component').registerComponent;
  46566. var utils = _dereq_('../../utils/');
  46567. /**
  46568. * 0.4.2 to 0.4.x
  46569. * Will need to update this when A-Frame goes to 1.x.x.
  46570. */
  46571. function getFuzzyPatchVersion (version) {
  46572. var split = version.split('.');
  46573. split[2] = 'x';
  46574. return split.join('.');
  46575. }
  46576. var INSPECTOR_DEV_URL = 'https://aframe.io/aframe-inspector/dist/aframe-inspector.js';
  46577. var INSPECTOR_RELEASE_URL = 'https://unpkg.com/aframe-inspector@' + getFuzzyPatchVersion(pkg.version) + '/dist/aframe-inspector.min.js';
  46578. var INSPECTOR_URL = process.env.INSPECTOR_VERSION === 'dev' ? INSPECTOR_DEV_URL : INSPECTOR_RELEASE_URL;
  46579. var LOADING_MESSAGE = 'Loading Inspector';
  46580. var LOADING_ERROR_MESSAGE = 'Error loading Inspector';
  46581. module.exports.Component = registerComponent('inspector', {
  46582. schema: {
  46583. url: {default: INSPECTOR_URL}
  46584. },
  46585. init: function () {
  46586. this.firstPlay = true;
  46587. this.onKeydown = this.onKeydown.bind(this);
  46588. this.onMessage = this.onMessage.bind(this);
  46589. this.initOverlay();
  46590. window.addEventListener('keydown', this.onKeydown);
  46591. window.addEventListener('message', this.onMessage);
  46592. },
  46593. play: function () {
  46594. var urlParam;
  46595. if (!this.firstPlay) { return; }
  46596. urlParam = utils.getUrlParameter('inspector');
  46597. if (urlParam !== 'false' && !!urlParam) {
  46598. this.openInspector();
  46599. this.firstPlay = false;
  46600. }
  46601. },
  46602. initOverlay: function () {
  46603. var dotsHTML = '<span class="dots"><span>.</span><span>.</span><span>.</span></span>';
  46604. this.loadingMessageEl = document.createElement('div');
  46605. this.loadingMessageEl.classList.add('a-inspector-loader');
  46606. this.loadingMessageEl.innerHTML = LOADING_MESSAGE + dotsHTML;
  46607. },
  46608. remove: function () {
  46609. this.removeEventListeners();
  46610. },
  46611. /**
  46612. * <ctrl> + <alt> + i keyboard shortcut.
  46613. */
  46614. onKeydown: function (evt) {
  46615. var shortcutPressed = evt.keyCode === 73 && evt.ctrlKey && evt.altKey;
  46616. if (!shortcutPressed) { return; }
  46617. this.openInspector();
  46618. },
  46619. showLoader: function () {
  46620. document.body.appendChild(this.loadingMessageEl);
  46621. },
  46622. hideLoader: function () {
  46623. document.body.removeChild(this.loadingMessageEl);
  46624. },
  46625. /**
  46626. * postMessage. aframe.io uses this to create a button on examples to open Inspector.
  46627. */
  46628. onMessage: function (evt) {
  46629. if (evt.data === 'INJECT_AFRAME_INSPECTOR') { this.openInspector(); }
  46630. },
  46631. openInspector: function (focusEl) {
  46632. var self = this;
  46633. var script;
  46634. // Already injected. Open.
  46635. if (AFRAME.INSPECTOR || AFRAME.inspectorInjected) {
  46636. AFRAME.INSPECTOR.open(focusEl);
  46637. return;
  46638. }
  46639. this.showLoader();
  46640. // Inject.
  46641. script = document.createElement('script');
  46642. script.src = this.data.url;
  46643. script.setAttribute('data-name', 'aframe-inspector');
  46644. script.setAttribute(AFRAME_INJECTED, '');
  46645. script.onload = function () {
  46646. AFRAME.INSPECTOR.open(focusEl);
  46647. self.hideLoader();
  46648. self.removeEventListeners();
  46649. };
  46650. script.onerror = function () {
  46651. self.loadingMessageEl.innerHTML = LOADING_ERROR_MESSAGE;
  46652. };
  46653. document.head.appendChild(script);
  46654. AFRAME.inspectorInjected = true;
  46655. },
  46656. removeEventListeners: function () {
  46657. window.removeEventListener('keydown', this.onKeydown);
  46658. window.removeEventListener('message', this.onMessage);
  46659. }
  46660. });
  46661. }).call(this,_dereq_('_process'))
  46662. },{"../../../package":51,"../../constants":97,"../../core/component":105,"../../utils/":178,"_process":32}],80:[function(_dereq_,module,exports){
  46663. var registerComponent = _dereq_('../../core/component').registerComponent;
  46664. var shouldCaptureKeyEvent = _dereq_('../../utils/').shouldCaptureKeyEvent;
  46665. module.exports.Component = registerComponent('keyboard-shortcuts', {
  46666. schema: {
  46667. enterVR: {default: true},
  46668. exitVR: {default: true}
  46669. },
  46670. init: function () {
  46671. this.onKeyup = this.onKeyup.bind(this);
  46672. },
  46673. update: function (oldData) {
  46674. var data = this.data;
  46675. this.enterVREnabled = data.enterVR;
  46676. },
  46677. play: function () {
  46678. window.addEventListener('keyup', this.onKeyup, false);
  46679. },
  46680. pause: function () {
  46681. window.removeEventListener('keyup', this.onKeyup);
  46682. },
  46683. onKeyup: function (evt) {
  46684. var scene = this.el;
  46685. if (!shouldCaptureKeyEvent(evt)) { return; }
  46686. if (this.enterVREnabled && evt.keyCode === 70) { // f.
  46687. scene.enterVR();
  46688. }
  46689. if (this.enterVREnabled && evt.keyCode === 27) { // escape.
  46690. scene.exitVR();
  46691. }
  46692. }
  46693. });
  46694. },{"../../core/component":105,"../../utils/":178}],81:[function(_dereq_,module,exports){
  46695. var debug = _dereq_('../../utils/debug');
  46696. var registerComponent = _dereq_('../../core/component').registerComponent;
  46697. var warn = debug('components:pool:warn');
  46698. /**
  46699. * Pool component to reuse entities.
  46700. * Avoids creating and destroying the same kind of entities.
  46701. * Helps reduce GC pauses. For example in a game to reuse enemies entities.
  46702. *
  46703. * @member {array} availableEls - Available entities in the pool.
  46704. * @member {array} usedEls - Entities of the pool in use.
  46705. */
  46706. module.exports.Component = registerComponent('pool', {
  46707. schema: {
  46708. container: {default: ''},
  46709. mixin: {default: ''},
  46710. size: {default: 0},
  46711. dynamic: {default: false}
  46712. },
  46713. multiple: true,
  46714. initPool: function () {
  46715. var i;
  46716. this.availableEls = [];
  46717. this.usedEls = [];
  46718. if (!this.data.mixin) {
  46719. warn('No mixin provided for pool component.');
  46720. }
  46721. if (this.data.container) {
  46722. this.container = document.querySelector(this.data.container);
  46723. if (!this.container) {
  46724. warn('Container ' + this.data.container + ' not found.');
  46725. }
  46726. }
  46727. this.container = this.container || this.el;
  46728. for (i = 0; i < this.data.size; ++i) {
  46729. this.createEntity();
  46730. }
  46731. },
  46732. update: function (oldData) {
  46733. var data = this.data;
  46734. if (oldData.mixin !== data.mixin || oldData.size !== data.size) {
  46735. this.initPool();
  46736. }
  46737. },
  46738. /**
  46739. * Add a new entity to the list of available entities.
  46740. */
  46741. createEntity: function () {
  46742. var el;
  46743. el = document.createElement('a-entity');
  46744. el.play = this.wrapPlay(el.play);
  46745. el.setAttribute('mixin', this.data.mixin);
  46746. el.object3D.visible = false;
  46747. el.pause();
  46748. this.container.appendChild(el);
  46749. this.availableEls.push(el);
  46750. },
  46751. /**
  46752. * Play wrapper for pooled entities. When pausing and playing a scene, don't want to play
  46753. * entities that are not in use.
  46754. */
  46755. wrapPlay: function (playMethod) {
  46756. var usedEls = this.usedEls;
  46757. return function () {
  46758. if (usedEls.indexOf(this) === -1) { return; }
  46759. playMethod.call(this);
  46760. };
  46761. },
  46762. /**
  46763. * Used to request one of the available entities of the pool.
  46764. */
  46765. requestEntity: function () {
  46766. var el;
  46767. if (this.availableEls.length === 0) {
  46768. if (this.data.dynamic === false) {
  46769. warn('Requested entity from empty pool: ' + this.attrName);
  46770. return;
  46771. } else {
  46772. warn('Requested entity from empty pool. This pool is dynamic and will resize ' +
  46773. 'automatically. You might want to increase its initial size: ' + this.attrName);
  46774. }
  46775. this.createEntity();
  46776. }
  46777. el = this.availableEls.shift();
  46778. this.usedEls.push(el);
  46779. el.object3D.visible = true;
  46780. return el;
  46781. },
  46782. /**
  46783. * Used to return a used entity to the pool.
  46784. */
  46785. returnEntity: function (el) {
  46786. var index = this.usedEls.indexOf(el);
  46787. if (index === -1) {
  46788. warn('The returned entity was not previously pooled from ' + this.attrName);
  46789. return;
  46790. }
  46791. this.usedEls.splice(index, 1);
  46792. this.availableEls.push(el);
  46793. el.object3D.visible = false;
  46794. el.pause();
  46795. return el;
  46796. }
  46797. });
  46798. },{"../../core/component":105,"../../utils/debug":174}],82:[function(_dereq_,module,exports){
  46799. var register = _dereq_('../../core/component').registerComponent;
  46800. var debug = _dereq_('../../utils/debug');
  46801. var warn = debug('components:renderer:warn');
  46802. /**
  46803. * Determines state of various renderer properties.
  46804. *
  46805. * NOTE: Because the `renderer` component is not added to the scene
  46806. * automatically, changing default values here has no effect unless
  46807. * the same changes are included in `a-scene.js`.
  46808. */
  46809. module.exports.Component = register('renderer', {
  46810. schema: {
  46811. antialias: {default: 'auto', oneOf: ['true', 'false', 'auto']},
  46812. logarithmicDepthBuffer: {default: 'auto', oneOf: ['true', 'false', 'auto']},
  46813. maxCanvasWidth: {default: 1920},
  46814. maxCanvasHeight: {default: 1920},
  46815. gammaOutput: {default: false},
  46816. physicallyCorrectLights: {default: false},
  46817. sortObjects: {default: false}
  46818. },
  46819. init: function () {
  46820. var el = this.el;
  46821. if (!el.isScene) {
  46822. warn('Renderer component can only be applied to <a-scene>');
  46823. }
  46824. // TODO: Uncomment these lines and deprecate 'antialias' for v0.9.0.
  46825. // if (el.hasAttribute('antialias')) {
  46826. // warn('Component `antialias` is deprecated. Use `renderer="antialias: true"` instead.');
  46827. // }
  46828. },
  46829. update: function (prevData) {
  46830. var data = this.data;
  46831. var sceneEl = this.el;
  46832. var renderer = sceneEl.renderer;
  46833. var needsShaderUpdate = false;
  46834. if (sceneEl.time > 0 && data.antialias !== prevData.antialias) {
  46835. warn('Property "antialias" cannot be changed after scene initialization');
  46836. }
  46837. if (sceneEl.time > 0 && data.logarithmicDepthBuffer !== prevData.logarithmicDepthBuffer) {
  46838. warn('Property "logarithmicDepthBuffer" cannot be changed after scene initialization');
  46839. }
  46840. if (data.sortObjects !== prevData.sortObjects) {
  46841. renderer.sortObjects = data.sortObjects;
  46842. }
  46843. if (data.gammaOutput !== prevData.gammaOutput) {
  46844. renderer.gammaOutput = data.gammaOutput;
  46845. needsShaderUpdate = true;
  46846. }
  46847. if (data.physicallyCorrectLights !== prevData.physicallyCorrectLights) {
  46848. renderer.physicallyCorrectLights = data.physicallyCorrectLights;
  46849. needsShaderUpdate = true;
  46850. }
  46851. if (!needsShaderUpdate || sceneEl.time === 0) { return; }
  46852. warn('Modifying renderer properties at runtime requires shader update and may drop frames.');
  46853. sceneEl.object3D.traverse(function (node) {
  46854. if (!node.isMesh) { return; }
  46855. if (Array.isArray(node.material)) {
  46856. node.material.forEach(function (material) {
  46857. material.needsUpdate = true;
  46858. });
  46859. } else {
  46860. node.material.needsUpdate = true;
  46861. }
  46862. });
  46863. }
  46864. });
  46865. },{"../../core/component":105,"../../utils/debug":174}],83:[function(_dereq_,module,exports){
  46866. /* global ImageData, URL */
  46867. var registerComponent = _dereq_('../../core/component').registerComponent;
  46868. var THREE = _dereq_('../../lib/three');
  46869. var VERTEX_SHADER = [
  46870. 'attribute vec3 position;',
  46871. 'attribute vec2 uv;',
  46872. 'uniform mat4 projectionMatrix;',
  46873. 'uniform mat4 modelViewMatrix;',
  46874. 'varying vec2 vUv;',
  46875. 'void main() {',
  46876. ' vUv = vec2( 1.- uv.x, uv.y );',
  46877. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  46878. '}'
  46879. ].join('\n');
  46880. var FRAGMENT_SHADER = [
  46881. 'precision mediump float;',
  46882. 'uniform samplerCube map;',
  46883. 'varying vec2 vUv;',
  46884. '#define M_PI 3.141592653589793238462643383279',
  46885. 'void main() {',
  46886. ' vec2 uv = vUv;',
  46887. ' float longitude = uv.x * 2. * M_PI - M_PI + M_PI / 2.;',
  46888. ' float latitude = uv.y * M_PI;',
  46889. ' vec3 dir = vec3(',
  46890. ' - sin( longitude ) * sin( latitude ),',
  46891. ' cos( latitude ),',
  46892. ' - cos( longitude ) * sin( latitude )',
  46893. ' );',
  46894. ' normalize( dir );',
  46895. ' gl_FragColor = vec4( textureCube( map, dir ).rgb, 1.0 );',
  46896. '}'
  46897. ].join('\n');
  46898. /**
  46899. * Component to take screenshots of the scene using a keboard shortcut (alt+s).
  46900. * It can be configured to either take 360&deg; captures (`equirectangular`)
  46901. * or regular screenshots (`projection`)
  46902. *
  46903. * This is based on https://github.com/spite/THREE.CubemapToEquirectangular
  46904. * To capture an equirectangular projection of the scene a THREE.CubeCamera is used
  46905. * The cube map produced by the CubeCamera is projected on a quad and then rendered to
  46906. * WebGLRenderTarget with an ortographic camera.
  46907. */
  46908. module.exports.Component = registerComponent('screenshot', {
  46909. schema: {
  46910. width: {default: 4096},
  46911. height: {default: 2048},
  46912. camera: {type: 'selector'}
  46913. },
  46914. init: function () {
  46915. var el = this.el;
  46916. var self = this;
  46917. if (el.renderer) {
  46918. setup();
  46919. } else {
  46920. el.addEventListener('render-target-loaded', setup);
  46921. }
  46922. function setup () {
  46923. var gl = el.renderer.getContext();
  46924. if (!gl) { return; }
  46925. self.cubeMapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  46926. self.material = new THREE.RawShaderMaterial({
  46927. uniforms: {map: {type: 't', value: null}},
  46928. vertexShader: VERTEX_SHADER,
  46929. fragmentShader: FRAGMENT_SHADER,
  46930. side: THREE.DoubleSide
  46931. });
  46932. self.quad = new THREE.Mesh(
  46933. new THREE.PlaneBufferGeometry(1, 1),
  46934. self.material
  46935. );
  46936. self.quad.visible = false;
  46937. self.camera = new THREE.OrthographicCamera(-1 / 2, 1 / 2, 1 / 2, -1 / 2, -10000, 10000);
  46938. self.canvas = document.createElement('canvas');
  46939. self.ctx = self.canvas.getContext('2d');
  46940. if (el.camera) { el.camera.add(self.quad); }
  46941. self.onKeyDown = self.onKeyDown.bind(self);
  46942. self.onCameraActive = self.onCameraActive.bind(self);
  46943. el.addEventListener('camera-set-active', self.onCameraActive);
  46944. }
  46945. },
  46946. getRenderTarget: function (width, height) {
  46947. return new THREE.WebGLRenderTarget(width, height, {
  46948. minFilter: THREE.LinearFilter,
  46949. magFilter: THREE.LinearFilter,
  46950. wrapS: THREE.ClampToEdgeWrapping,
  46951. wrapT: THREE.ClampToEdgeWrapping,
  46952. format: THREE.RGBAFormat,
  46953. type: THREE.UnsignedByteType
  46954. });
  46955. },
  46956. resize: function (width, height) {
  46957. // Resize quad.
  46958. this.quad.scale.set(width, height, 1);
  46959. // Resize camera.
  46960. this.camera.left = -1 * width / 2;
  46961. this.camera.right = width / 2;
  46962. this.camera.top = height / 2;
  46963. this.camera.bottom = -1 * height / 2;
  46964. this.camera.updateProjectionMatrix();
  46965. // Resize canvas.
  46966. this.canvas.width = width;
  46967. this.canvas.height = height;
  46968. },
  46969. play: function () {
  46970. window.addEventListener('keydown', this.onKeyDown);
  46971. },
  46972. onCameraActive: function (evt) {
  46973. var cameraParent = this.quad.parent;
  46974. if (cameraParent) { cameraParent.remove(this.quad); }
  46975. evt.detail.cameraEl.getObject3D('camera').add(this.quad);
  46976. },
  46977. /**
  46978. * <ctrl> + <alt> + s = Regular screenshot.
  46979. * <ctrl> + <alt> + <shift> + s = Equirectangular screenshot.
  46980. */
  46981. onKeyDown: function (evt) {
  46982. var shortcutPressed = evt.keyCode === 83 && evt.ctrlKey && evt.altKey;
  46983. if (!this.data || !shortcutPressed) { return; }
  46984. var projection = evt.shiftKey ? 'equirectangular' : 'perspective';
  46985. this.capture(projection);
  46986. },
  46987. /**
  46988. * Capture a screenshot of the scene.
  46989. *
  46990. * @param {string} projection - Screenshot projection (equirectangular or perspective).
  46991. */
  46992. setCapture: function (projection) {
  46993. var el = this.el;
  46994. var size;
  46995. var camera;
  46996. var cubeCamera;
  46997. // Configure camera.
  46998. if (projection === 'perspective') {
  46999. // Quad is only used in equirectangular mode. Hide it in this case.
  47000. this.quad.visible = false;
  47001. // Use scene camera.
  47002. camera = (this.data.camera && this.data.camera.components.camera.camera) || el.camera;
  47003. size = {width: this.data.width, height: this.data.height};
  47004. } else {
  47005. // Use ortho camera.
  47006. camera = this.camera;
  47007. // Copy position and rotation of scene camera into the ortho one.
  47008. el.camera.getWorldPosition(camera.position);
  47009. el.camera.getWorldQuaternion(camera.quaternion);
  47010. // Create cube camera and copy position from scene camera.
  47011. cubeCamera = new THREE.CubeCamera(el.camera.near, el.camera.far,
  47012. Math.min(this.cubeMapSize, 2048));
  47013. el.camera.getWorldPosition(cubeCamera.position);
  47014. el.camera.getWorldQuaternion(cubeCamera.quaternion);
  47015. // Render scene with cube camera.
  47016. cubeCamera.updateCubeMap(el.renderer, el.object3D);
  47017. this.quad.material.uniforms.map.value = cubeCamera.renderTarget.texture;
  47018. size = {width: this.data.width, height: this.data.height};
  47019. // Use quad to project image taken by the cube camera.
  47020. this.quad.visible = true;
  47021. }
  47022. return {
  47023. camera: camera,
  47024. size: size,
  47025. projection: projection
  47026. };
  47027. },
  47028. /**
  47029. * Maintained for backwards compatibility.
  47030. */
  47031. capture: function (projection) {
  47032. var params = this.setCapture(projection);
  47033. this.renderCapture(params.camera, params.size, params.projection);
  47034. // Trigger file download.
  47035. this.saveCapture();
  47036. },
  47037. /**
  47038. * Return canvas instead of triggering download (e.g., for uploading blob to server).
  47039. */
  47040. getCanvas: function (projection) {
  47041. var params = this.setCapture(projection);
  47042. this.renderCapture(params.camera, params.size, params.projection);
  47043. return this.canvas;
  47044. },
  47045. renderCapture: function (camera, size, projection) {
  47046. var autoClear = this.el.renderer.autoClear;
  47047. var el = this.el;
  47048. var imageData;
  47049. var output;
  47050. var pixels;
  47051. var renderer = this.el.renderer;
  47052. // Create rendering target and buffer to store the read pixels.
  47053. output = this.getRenderTarget(size.width, size.height);
  47054. pixels = new Uint8Array(4 * size.width * size.height);
  47055. // Resize quad, camera, and canvas.
  47056. this.resize(size.width, size.height);
  47057. // Render scene to render target.
  47058. renderer.autoClear = true;
  47059. renderer.render(el.object3D, camera, output, true);
  47060. renderer.autoClear = autoClear;
  47061. // Read image pizels back.
  47062. renderer.readRenderTargetPixels(output, 0, 0, size.width, size.height, pixels);
  47063. if (projection === 'perspective') {
  47064. pixels = this.flipPixelsVertically(pixels, size.width, size.height);
  47065. }
  47066. imageData = new ImageData(new Uint8ClampedArray(pixels), size.width, size.height);
  47067. // Hide quad after projecting the image.
  47068. this.quad.visible = false;
  47069. // Copy pixels into canvas.
  47070. this.ctx.putImageData(imageData, 0, 0);
  47071. },
  47072. flipPixelsVertically: function (pixels, width, height) {
  47073. var flippedPixels = pixels.slice(0);
  47074. for (var x = 0; x < width; ++x) {
  47075. for (var y = 0; y < height; ++y) {
  47076. flippedPixels[x * 4 + y * width * 4] = pixels[x * 4 + (height - y) * width * 4];
  47077. flippedPixels[x * 4 + 1 + y * width * 4] = pixels[x * 4 + 1 + (height - y) * width * 4];
  47078. flippedPixels[x * 4 + 2 + y * width * 4] = pixels[x * 4 + 2 + (height - y) * width * 4];
  47079. flippedPixels[x * 4 + 3 + y * width * 4] = pixels[x * 4 + 3 + (height - y) * width * 4];
  47080. }
  47081. }
  47082. return flippedPixels;
  47083. },
  47084. /**
  47085. * Download capture to file.
  47086. */
  47087. saveCapture: function () {
  47088. this.canvas.toBlob(function (blob) {
  47089. var fileName = 'screenshot-' + document.title.toLowerCase() + '-' + Date.now() + '.png';
  47090. var linkEl = document.createElement('a');
  47091. var url = URL.createObjectURL(blob);
  47092. linkEl.href = url;
  47093. linkEl.setAttribute('download', fileName);
  47094. linkEl.innerHTML = 'downloading...';
  47095. linkEl.style.display = 'none';
  47096. document.body.appendChild(linkEl);
  47097. setTimeout(function () {
  47098. linkEl.click();
  47099. document.body.removeChild(linkEl);
  47100. }, 1);
  47101. }, 'image/png');
  47102. }
  47103. });
  47104. },{"../../core/component":105,"../../lib/three":154}],84:[function(_dereq_,module,exports){
  47105. var registerComponent = _dereq_('../../core/component').registerComponent;
  47106. var RStats = _dereq_('../../../vendor/rStats');
  47107. var utils = _dereq_('../../utils');
  47108. _dereq_('../../../vendor/rStats.extras');
  47109. _dereq_('../../lib/rStatsAframe');
  47110. var AFrameStats = window.aframeStats;
  47111. var bind = utils.bind;
  47112. var HIDDEN_CLASS = 'a-hidden';
  47113. var ThreeStats = window.threeStats;
  47114. /**
  47115. * Stats appended to document.body by RStats.
  47116. */
  47117. module.exports.Component = registerComponent('stats', {
  47118. schema: {default: true},
  47119. init: function () {
  47120. var scene = this.el;
  47121. if (utils.getUrlParameter('stats') === 'false') { return; }
  47122. this.stats = createStats(scene);
  47123. this.statsEl = document.querySelector('.rs-base');
  47124. this.hideBound = bind(this.hide, this);
  47125. this.showBound = bind(this.show, this);
  47126. scene.addEventListener('enter-vr', this.hideBound);
  47127. scene.addEventListener('exit-vr', this.showBound);
  47128. },
  47129. update: function () {
  47130. if (!this.stats) { return; }
  47131. return (!this.data) ? this.hide() : this.show();
  47132. },
  47133. remove: function () {
  47134. this.el.removeEventListener('enter-vr', this.hideBound);
  47135. this.el.removeEventListener('exit-vr', this.showBound);
  47136. if (!this.statsEl) { return; } // Scene detached.
  47137. this.statsEl.parentNode.removeChild(this.statsEl);
  47138. },
  47139. tick: function () {
  47140. var stats = this.stats;
  47141. if (!stats) { return; }
  47142. stats('rAF').tick();
  47143. stats('FPS').frame();
  47144. stats().update();
  47145. },
  47146. hide: function () {
  47147. this.statsEl.classList.add(HIDDEN_CLASS);
  47148. },
  47149. show: function () {
  47150. this.statsEl.classList.remove(HIDDEN_CLASS);
  47151. }
  47152. });
  47153. function createStats (scene) {
  47154. var threeStats = new ThreeStats(scene.renderer);
  47155. var aframeStats = new AFrameStats(scene);
  47156. var plugins = scene.isMobile ? [] : [threeStats, aframeStats];
  47157. return new RStats({
  47158. css: [], // Our stylesheet is injected from `src/index.js`.
  47159. values: {
  47160. fps: {caption: 'fps', below: 30}
  47161. },
  47162. groups: [
  47163. {caption: 'Framerate', values: ['fps', 'raf']}
  47164. ],
  47165. plugins: plugins
  47166. });
  47167. }
  47168. },{"../../../vendor/rStats":187,"../../../vendor/rStats.extras":186,"../../core/component":105,"../../lib/rStatsAframe":153,"../../utils":178}],85:[function(_dereq_,module,exports){
  47169. var registerComponent = _dereq_('../../core/component').registerComponent;
  47170. var constants = _dereq_('../../constants/');
  47171. var utils = _dereq_('../../utils/');
  47172. var bind = utils.bind;
  47173. var ENTER_VR_CLASS = 'a-enter-vr';
  47174. var ENTER_VR_BTN_CLASS = 'a-enter-vr-button';
  47175. var HIDDEN_CLASS = 'a-hidden';
  47176. var ORIENTATION_MODAL_CLASS = 'a-orientation-modal';
  47177. /**
  47178. * UI for entering VR mode.
  47179. */
  47180. module.exports.Component = registerComponent('vr-mode-ui', {
  47181. dependencies: ['canvas'],
  47182. schema: {
  47183. enabled: {default: true},
  47184. enterVRButton: {default: ''}
  47185. },
  47186. init: function () {
  47187. var self = this;
  47188. var sceneEl = this.el;
  47189. if (utils.getUrlParameter('ui') === 'false') { return; }
  47190. this.insideLoader = false;
  47191. this.enterVREl = null;
  47192. this.orientationModalEl = null;
  47193. this.bindMethods();
  47194. // Hide/show VR UI when entering/exiting VR mode.
  47195. sceneEl.addEventListener('enter-vr', this.updateEnterVRInterface);
  47196. sceneEl.addEventListener('exit-vr', this.updateEnterVRInterface);
  47197. window.addEventListener('message', function (event) {
  47198. if (event.data.type === 'loaderReady') {
  47199. self.insideLoader = true;
  47200. self.remove();
  47201. }
  47202. });
  47203. // Modal that tells the user to change orientation if in portrait.
  47204. window.addEventListener('orientationchange', this.toggleOrientationModalIfNeeded);
  47205. },
  47206. bindMethods: function () {
  47207. this.onEnterVRButtonClick = bind(this.onEnterVRButtonClick, this);
  47208. this.onModalClick = bind(this.onModalClick, this);
  47209. this.toggleOrientationModalIfNeeded = bind(this.toggleOrientationModalIfNeeded, this);
  47210. this.updateEnterVRInterface = bind(this.updateEnterVRInterface, this);
  47211. },
  47212. /**
  47213. * Exit VR when modal clicked.
  47214. */
  47215. onModalClick: function () {
  47216. this.el.exitVR();
  47217. },
  47218. /**
  47219. * Enter VR when modal clicked.
  47220. */
  47221. onEnterVRButtonClick: function () {
  47222. this.el.enterVR();
  47223. },
  47224. update: function () {
  47225. var data = this.data;
  47226. var sceneEl = this.el;
  47227. if (!data.enabled || this.insideLoader || utils.getUrlParameter('ui') === 'false') {
  47228. return this.remove();
  47229. }
  47230. if (this.enterVREl || this.orientationModalEl) { return; }
  47231. // Add UI if enabled and not already present.
  47232. if (data.enterVRButton) {
  47233. // Custom button.
  47234. this.enterVREl = document.querySelector(data.enterVRButton);
  47235. this.enterVREl.addEventListener('click', this.onEnterVRButtonClick);
  47236. } else {
  47237. this.enterVREl = createEnterVRButton(this.onEnterVRButtonClick);
  47238. sceneEl.appendChild(this.enterVREl);
  47239. }
  47240. this.orientationModalEl = createOrientationModal(this.onModalClick);
  47241. sceneEl.appendChild(this.orientationModalEl);
  47242. this.updateEnterVRInterface();
  47243. },
  47244. remove: function () {
  47245. [this.enterVREl, this.orientationModalEl].forEach(function (uiElement) {
  47246. if (uiElement && uiElement.parentNode) {
  47247. uiElement.parentNode.removeChild(uiElement);
  47248. }
  47249. });
  47250. },
  47251. updateEnterVRInterface: function () {
  47252. this.toggleEnterVRButtonIfNeeded();
  47253. this.toggleOrientationModalIfNeeded();
  47254. },
  47255. toggleEnterVRButtonIfNeeded: function () {
  47256. var sceneEl = this.el;
  47257. if (!this.enterVREl) { return; }
  47258. if (sceneEl.is('vr-mode')) {
  47259. this.enterVREl.classList.add(HIDDEN_CLASS);
  47260. } else {
  47261. this.enterVREl.classList.remove(HIDDEN_CLASS);
  47262. }
  47263. },
  47264. toggleOrientationModalIfNeeded: function () {
  47265. var sceneEl = this.el;
  47266. var orientationModalEl = this.orientationModalEl;
  47267. if (!orientationModalEl || !sceneEl.isMobile) { return; }
  47268. if (!utils.device.isLandscape() && sceneEl.is('vr-mode')) {
  47269. // Show if in VR mode on portrait.
  47270. orientationModalEl.classList.remove(HIDDEN_CLASS);
  47271. } else {
  47272. orientationModalEl.classList.add(HIDDEN_CLASS);
  47273. }
  47274. }
  47275. });
  47276. /**
  47277. * Create a button that when clicked will enter into stereo-rendering mode for VR.
  47278. *
  47279. * Structure: <div><button></div>
  47280. *
  47281. * @param {function} onClick - click event handler
  47282. * @returns {Element} Wrapper <div>.
  47283. */
  47284. function createEnterVRButton (onClick) {
  47285. var vrButton;
  47286. var wrapper;
  47287. // Create elements.
  47288. wrapper = document.createElement('div');
  47289. wrapper.classList.add(ENTER_VR_CLASS);
  47290. wrapper.setAttribute(constants.AFRAME_INJECTED, '');
  47291. vrButton = document.createElement('button');
  47292. vrButton.className = ENTER_VR_BTN_CLASS;
  47293. vrButton.setAttribute('title',
  47294. 'Enter VR mode with a headset or fullscreen mode on a desktop. ' +
  47295. 'Visit https://webvr.rocks or https://webvr.info for more information.');
  47296. vrButton.setAttribute(constants.AFRAME_INJECTED, '');
  47297. // Insert elements.
  47298. wrapper.appendChild(vrButton);
  47299. vrButton.addEventListener('click', function (evt) {
  47300. onClick();
  47301. evt.stopPropagation();
  47302. });
  47303. return wrapper;
  47304. }
  47305. /**
  47306. * Creates a modal dialog to request the user to switch to landscape orientation.
  47307. *
  47308. * @param {function} onClick - click event handler
  47309. * @returns {Element} Wrapper <div>.
  47310. */
  47311. function createOrientationModal (onClick) {
  47312. var modal = document.createElement('div');
  47313. modal.className = ORIENTATION_MODAL_CLASS;
  47314. modal.classList.add(HIDDEN_CLASS);
  47315. modal.setAttribute(constants.AFRAME_INJECTED, '');
  47316. var exit = document.createElement('button');
  47317. exit.setAttribute(constants.AFRAME_INJECTED, '');
  47318. exit.innerHTML = 'Exit VR';
  47319. // Exit VR on close.
  47320. exit.addEventListener('click', onClick);
  47321. modal.appendChild(exit);
  47322. return modal;
  47323. }
  47324. },{"../../constants/":97,"../../core/component":105,"../../utils/":178}],86:[function(_dereq_,module,exports){
  47325. var component = _dereq_('../core/component');
  47326. var THREE = _dereq_('../lib/three');
  47327. var bind = _dereq_('../utils/bind');
  47328. var registerComponent = component.registerComponent;
  47329. /**
  47330. * Shadow component.
  47331. *
  47332. * When applied to an entity, that entity's geometry and any descendants will cast or receive
  47333. * shadows as specified by the `cast` and `receive` properties.
  47334. */
  47335. module.exports.Component = registerComponent('shadow', {
  47336. schema: {
  47337. cast: {default: true},
  47338. receive: {default: true}
  47339. },
  47340. init: function () {
  47341. this.onMeshChanged = bind(this.update, this);
  47342. this.el.addEventListener('object3dset', this.onMeshChanged);
  47343. this.system.setShadowMapEnabled(true);
  47344. },
  47345. update: function () {
  47346. var data = this.data;
  47347. this.updateDescendants(data.cast, data.receive);
  47348. },
  47349. remove: function () {
  47350. var el = this.el;
  47351. el.removeEventListener('object3dset', this.onMeshChanged);
  47352. this.updateDescendants(false, false);
  47353. },
  47354. updateDescendants: function (cast, receive) {
  47355. var sceneEl = this.el.sceneEl;
  47356. this.el.object3D.traverse(function (node) {
  47357. if (!(node instanceof THREE.Mesh)) { return; }
  47358. node.castShadow = cast;
  47359. node.receiveShadow = receive;
  47360. // If scene has already rendered, materials must be updated.
  47361. if (sceneEl.hasLoaded && node.material) {
  47362. var materials = Array.isArray(node.material) ? node.material : [node.material];
  47363. for (var i = 0; i < materials.length; i++) {
  47364. materials[i].needsUpdate = true;
  47365. }
  47366. }
  47367. });
  47368. }
  47369. });
  47370. },{"../core/component":105,"../lib/three":154,"../utils/bind":172}],87:[function(_dereq_,module,exports){
  47371. var registerComponent = _dereq_('../core/component').registerComponent;
  47372. var debug = _dereq_('../utils/debug');
  47373. var THREE = _dereq_('../lib/three');
  47374. var warn = debug('components:sound:warn');
  47375. /**
  47376. * Sound component.
  47377. */
  47378. module.exports.Component = registerComponent('sound', {
  47379. schema: {
  47380. autoplay: {default: false},
  47381. distanceModel: {default: 'inverse', oneOf: ['linear', 'inverse', 'exponential']},
  47382. loop: {default: false},
  47383. maxDistance: {default: 10000},
  47384. on: {default: ''},
  47385. poolSize: {default: 1},
  47386. positional: {default: true},
  47387. refDistance: {default: 1},
  47388. rolloffFactor: {default: 1},
  47389. src: {type: 'audio'},
  47390. volume: {default: 1}
  47391. },
  47392. multiple: true,
  47393. init: function () {
  47394. var self = this;
  47395. this.listener = null;
  47396. this.audioLoader = new THREE.AudioLoader();
  47397. this.pool = new THREE.Group();
  47398. this.loaded = false;
  47399. this.mustPlay = false;
  47400. // Don't pass evt because playSound takes a function as parameter.
  47401. this.playSoundBound = function () { self.playSound(); };
  47402. },
  47403. update: function (oldData) {
  47404. var data = this.data;
  47405. var i;
  47406. var sound;
  47407. var srcChanged = data.src !== oldData.src;
  47408. // Create new sound if not yet created or changing `src`.
  47409. if (srcChanged) {
  47410. if (!data.src) { return; }
  47411. this.setupSound();
  47412. }
  47413. for (i = 0; i < this.pool.children.length; i++) {
  47414. sound = this.pool.children[i];
  47415. if (data.positional) {
  47416. sound.setDistanceModel(data.distanceModel);
  47417. sound.setMaxDistance(data.maxDistance);
  47418. sound.setRefDistance(data.refDistance);
  47419. sound.setRolloffFactor(data.rolloffFactor);
  47420. }
  47421. sound.setLoop(data.loop);
  47422. sound.setVolume(data.volume);
  47423. sound.isPaused = false;
  47424. }
  47425. if (data.on !== oldData.on) {
  47426. this.updateEventListener(oldData.on);
  47427. }
  47428. // All sound values set. Load in `src`.
  47429. if (srcChanged) {
  47430. var self = this;
  47431. this.loaded = false;
  47432. this.audioLoader.load(data.src, function (buffer) {
  47433. for (i = 0; i < self.pool.children.length; i++) {
  47434. sound = self.pool.children[i];
  47435. sound.setBuffer(buffer);
  47436. }
  47437. self.loaded = true;
  47438. // Remove this key from cache, otherwise we can't play it again
  47439. THREE.Cache.remove(data.src);
  47440. if (self.data.autoplay || self.mustPlay) { self.playSound(); }
  47441. self.el.emit('sound-loaded', self.evtDetail, false);
  47442. });
  47443. }
  47444. },
  47445. pause: function () {
  47446. this.stopSound();
  47447. this.removeEventListener();
  47448. },
  47449. play: function () {
  47450. if (this.data.autoplay) { this.playSound(); }
  47451. this.updateEventListener();
  47452. },
  47453. remove: function () {
  47454. var i;
  47455. var sound;
  47456. this.removeEventListener();
  47457. if (this.el.getObject3D(this.attrName)) {
  47458. this.el.removeObject3D(this.attrName);
  47459. }
  47460. try {
  47461. for (i = 0; i < this.pool.children.length; i++) {
  47462. sound = this.pool.children[i];
  47463. sound.disconnect();
  47464. }
  47465. } catch (e) {
  47466. // disconnect() will throw if it was never connected initially.
  47467. warn('Audio source not properly disconnected');
  47468. }
  47469. },
  47470. /**
  47471. * Update listener attached to the user defined on event.
  47472. */
  47473. updateEventListener: function (oldEvt) {
  47474. var el = this.el;
  47475. if (oldEvt) { el.removeEventListener(oldEvt, this.playSoundBound); }
  47476. el.addEventListener(this.data.on, this.playSoundBound);
  47477. },
  47478. removeEventListener: function () {
  47479. this.el.removeEventListener(this.data.on, this.playSoundBound);
  47480. },
  47481. /**
  47482. * Removes current sound object, creates new sound object, adds to entity.
  47483. *
  47484. * @returns {object} sound
  47485. */
  47486. setupSound: function () {
  47487. var self = this;
  47488. var el = this.el;
  47489. var i;
  47490. var sceneEl = el.sceneEl;
  47491. var sound;
  47492. if (this.pool.children.length > 0) {
  47493. this.stopSound();
  47494. el.removeObject3D('sound');
  47495. }
  47496. // Only want one AudioListener. Cache it on the scene.
  47497. var listener = this.listener = sceneEl.audioListener || new THREE.AudioListener();
  47498. sceneEl.audioListener = listener;
  47499. if (sceneEl.camera) {
  47500. sceneEl.camera.add(listener);
  47501. }
  47502. // Wait for camera if necessary.
  47503. sceneEl.addEventListener('camera-set-active', function (evt) {
  47504. evt.detail.cameraEl.getObject3D('camera').add(listener);
  47505. });
  47506. // Create [poolSize] audio instances and attach them to pool
  47507. this.pool = new THREE.Group();
  47508. for (i = 0; i < this.data.poolSize; i++) {
  47509. sound = this.data.positional
  47510. ? new THREE.PositionalAudio(listener)
  47511. : new THREE.Audio(listener);
  47512. this.pool.add(sound);
  47513. }
  47514. el.setObject3D(this.attrName, this.pool);
  47515. for (i = 0; i < this.pool.children.length; i++) {
  47516. sound = this.pool.children[i];
  47517. sound.onEnded = function () {
  47518. this.isPlaying = false;
  47519. el.emit('sound-ended', self.evtDetail, false);
  47520. };
  47521. }
  47522. },
  47523. /**
  47524. * Pause all the sounds in the pool.
  47525. */
  47526. pauseSound: function () {
  47527. var i;
  47528. var sound;
  47529. this.isPlaying = false;
  47530. for (i = 0; i < this.pool.children.length; i++) {
  47531. sound = this.pool.children[i];
  47532. if (!sound.source || !sound.source.buffer || !sound.isPlaying || sound.isPaused) {
  47533. continue;
  47534. }
  47535. sound.isPaused = true;
  47536. sound.pause();
  47537. }
  47538. },
  47539. /**
  47540. * Look for an unused sound in the pool and play it if found.
  47541. */
  47542. playSound: function (processSound) {
  47543. var found;
  47544. var i;
  47545. var sound;
  47546. if (!this.loaded) {
  47547. warn('Sound not loaded yet. It will be played once it finished loading');
  47548. this.mustPlay = true;
  47549. return;
  47550. }
  47551. found = false;
  47552. this.isPlaying = true;
  47553. for (i = 0; i < this.pool.children.length; i++) {
  47554. sound = this.pool.children[i];
  47555. if (!sound.isPlaying && sound.buffer && !found) {
  47556. if (processSound) { processSound(sound); }
  47557. sound.play();
  47558. sound.isPaused = false;
  47559. found = true;
  47560. continue;
  47561. }
  47562. }
  47563. if (!found) {
  47564. warn('All the sounds are playing. If you need to play more sounds simultaneously ' +
  47565. 'consider increasing the size of pool with the `poolSize` attribute.', this.el);
  47566. return;
  47567. }
  47568. this.mustPlay = false;
  47569. },
  47570. /**
  47571. * Stop all the sounds in the pool.
  47572. */
  47573. stopSound: function () {
  47574. var i;
  47575. var sound;
  47576. this.isPlaying = false;
  47577. for (i = 0; i < this.pool.children.length; i++) {
  47578. sound = this.pool.children[i];
  47579. if (!sound.source || !sound.source.buffer) { return; }
  47580. sound.stop();
  47581. }
  47582. }
  47583. });
  47584. },{"../core/component":105,"../lib/three":154,"../utils/debug":174}],88:[function(_dereq_,module,exports){
  47585. var createTextGeometry = _dereq_('three-bmfont-text');
  47586. var loadBMFont = _dereq_('load-bmfont');
  47587. var registerComponent = _dereq_('../core/component').registerComponent;
  47588. var coreShader = _dereq_('../core/shader');
  47589. var THREE = _dereq_('../lib/three');
  47590. var utils = _dereq_('../utils/');
  47591. var error = utils.debug('components:text:error');
  47592. var shaders = coreShader.shaders;
  47593. var warn = utils.debug('components:text:warn');
  47594. // 1 to match other A-Frame default widths.
  47595. var DEFAULT_WIDTH = 1;
  47596. // @bryik set anisotropy to 16. Improves look of large amounts of text when viewed from angle.
  47597. var MAX_ANISOTROPY = 16;
  47598. var FONT_BASE_URL = 'https://cdn.aframe.io/fonts/';
  47599. var FONTS = {
  47600. aileronsemibold: FONT_BASE_URL + 'Aileron-Semibold.fnt',
  47601. dejavu: FONT_BASE_URL + 'DejaVu-sdf.fnt',
  47602. exo2bold: FONT_BASE_URL + 'Exo2Bold.fnt',
  47603. exo2semibold: FONT_BASE_URL + 'Exo2SemiBold.fnt',
  47604. kelsonsans: FONT_BASE_URL + 'KelsonSans.fnt',
  47605. monoid: FONT_BASE_URL + 'Monoid.fnt',
  47606. mozillavr: FONT_BASE_URL + 'mozillavr.fnt',
  47607. roboto: FONT_BASE_URL + 'Roboto-msdf.json',
  47608. sourcecodepro: FONT_BASE_URL + 'SourceCodePro.fnt'
  47609. };
  47610. var MSDF_FONTS = ['roboto'];
  47611. var DEFAULT_FONT = 'roboto';
  47612. module.exports.FONTS = FONTS;
  47613. var cache = new PromiseCache();
  47614. var fontWidthFactors = {};
  47615. var textures = {};
  47616. // Regular expression for detecting a URLs with a protocol prefix.
  47617. var protocolRe = /^\w+:/;
  47618. /**
  47619. * SDF-based text component.
  47620. * Based on https://github.com/Jam3/three-bmfont-text.
  47621. *
  47622. * All the stock fonts are for the `sdf` registered shader, an improved version of jam3's
  47623. * original `sdf` shader.
  47624. */
  47625. module.exports.Component = registerComponent('text', {
  47626. multiple: true,
  47627. schema: {
  47628. align: {type: 'string', default: 'left', oneOf: ['left', 'right', 'center']},
  47629. alphaTest: {default: 0.5},
  47630. // `anchor` defaults to center to match geometries.
  47631. anchor: {default: 'center', oneOf: ['left', 'right', 'center', 'align']},
  47632. baseline: {default: 'center', oneOf: ['top', 'center', 'bottom']},
  47633. color: {type: 'color', default: '#FFF'},
  47634. font: {type: 'string', default: DEFAULT_FONT},
  47635. // `fontImage` defaults to the font name as a .png (e.g., mozillavr.fnt -> mozillavr.png).
  47636. fontImage: {type: 'string'},
  47637. // `height` has no default, will be populated at layout.
  47638. height: {type: 'number'},
  47639. letterSpacing: {type: 'number', default: 0},
  47640. // `lineHeight` defaults to font's `lineHeight` value.
  47641. lineHeight: {type: 'number'},
  47642. // `negate` must be true for fonts generated with older versions of msdfgen (white background).
  47643. negate: {type: 'boolean', default: true},
  47644. opacity: {type: 'number', default: 1.0},
  47645. shader: {default: 'sdf', oneOf: shaders},
  47646. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  47647. tabSize: {default: 4},
  47648. transparent: {default: true},
  47649. value: {type: 'string'},
  47650. whiteSpace: {default: 'normal', oneOf: ['normal', 'pre', 'nowrap']},
  47651. // `width` defaults to geometry width if present, else `DEFAULT_WIDTH`.
  47652. width: {type: 'number'},
  47653. // `wrapCount` units are about one default font character. Wrap roughly at this number.
  47654. wrapCount: {type: 'number', default: 40},
  47655. // `wrapPixels` will wrap using bmfont pixel units (e.g., dejavu's is 32 pixels).
  47656. wrapPixels: {type: 'number'},
  47657. // `xOffset` to add padding.
  47658. xOffset: {type: 'number', default: 0},
  47659. // `yOffset` to adjust generated fonts from tools that may have incorrect metrics.
  47660. yOffset: {type: 'number', default: 0},
  47661. // `zOffset` will provide a small z offset to avoid z-fighting.
  47662. zOffset: {type: 'number', default: 0.001}
  47663. },
  47664. init: function () {
  47665. this.shaderData = {};
  47666. this.geometry = createTextGeometry();
  47667. this.createOrUpdateMaterial();
  47668. this.mesh = new THREE.Mesh(this.geometry, this.material);
  47669. this.el.setObject3D(this.attrName, this.mesh);
  47670. },
  47671. update: function (oldData) {
  47672. var data = this.data;
  47673. var font = this.currentFont;
  47674. if (textures[data.font]) {
  47675. this.texture = textures[data.font];
  47676. } else {
  47677. // Create texture per font.
  47678. this.texture = textures[data.font] = new THREE.Texture();
  47679. this.texture.anisotropy = MAX_ANISOTROPY;
  47680. }
  47681. // Update material.
  47682. this.createOrUpdateMaterial();
  47683. // New font. `updateFont` will later change data and layout.
  47684. if (oldData.font !== data.font) {
  47685. this.updateFont();
  47686. return;
  47687. }
  47688. // Update geometry and layout.
  47689. if (font) {
  47690. this.updateGeometry(this.geometry, font);
  47691. this.updateLayout();
  47692. }
  47693. },
  47694. /**
  47695. * Clean up geometry, material, texture, mesh, objects.
  47696. */
  47697. remove: function () {
  47698. this.geometry.dispose();
  47699. this.geometry = null;
  47700. this.el.removeObject3D(this.attrName);
  47701. this.material.dispose();
  47702. this.material = null;
  47703. this.texture.dispose();
  47704. this.texture = null;
  47705. if (this.shaderObject) {
  47706. delete this.shaderObject;
  47707. }
  47708. },
  47709. /**
  47710. * Update the shader of the material.
  47711. */
  47712. createOrUpdateMaterial: function () {
  47713. var data = this.data;
  47714. var hasChangedShader;
  47715. var material = this.material;
  47716. var NewShader;
  47717. var shaderData = this.shaderData;
  47718. var shaderName;
  47719. // Infer shader if using a stock font (or from `-msdf` filename convention).
  47720. shaderName = data.shader;
  47721. if (MSDF_FONTS.indexOf(data.font) !== -1 || data.font.indexOf('-msdf.') >= 0) {
  47722. shaderName = 'msdf';
  47723. } else if (data.font in FONTS && MSDF_FONTS.indexOf(data.font) === -1) {
  47724. shaderName = 'sdf';
  47725. }
  47726. hasChangedShader = (this.shaderObject && this.shaderObject.name) !== shaderName;
  47727. shaderData.alphaTest = data.alphaTest;
  47728. shaderData.color = data.color;
  47729. shaderData.map = this.texture;
  47730. shaderData.opacity = data.opacity;
  47731. shaderData.side = parseSide(data.side);
  47732. shaderData.transparent = data.transparent;
  47733. shaderData.negate = data.negate;
  47734. // Shader has not changed, do an update.
  47735. if (!hasChangedShader) {
  47736. // Update shader material.
  47737. this.shaderObject.update(shaderData);
  47738. // Apparently, was not set on `init` nor `update`.
  47739. material.transparent = shaderData.transparent;
  47740. material.side = shaderData.side;
  47741. return;
  47742. }
  47743. // Shader has changed. Create a shader material.
  47744. NewShader = createShader(this.el, shaderName, shaderData);
  47745. this.material = NewShader.material;
  47746. this.shaderObject = NewShader.shader;
  47747. // Set new shader material.
  47748. this.material.side = shaderData.side;
  47749. if (this.mesh) { this.mesh.material = this.material; }
  47750. },
  47751. /**
  47752. * Load font for geometry, load font image for material, and apply.
  47753. */
  47754. updateFont: function () {
  47755. var data = this.data;
  47756. var el = this.el;
  47757. var fontSrc;
  47758. var geometry = this.geometry;
  47759. var self = this;
  47760. if (!data.font) { warn('No font specified. Using the default font.'); }
  47761. // Make invisible during font swap.
  47762. this.mesh.visible = false;
  47763. // Look up font URL to use, and perform cached load.
  47764. fontSrc = this.lookupFont(data.font || DEFAULT_FONT) || data.font;
  47765. cache.get(fontSrc, function doLoadFont () {
  47766. return loadFont(fontSrc, data.yOffset);
  47767. }).then(function setFont (font) {
  47768. var fontImgSrc;
  47769. if (font.pages.length !== 1) {
  47770. throw new Error('Currently only single-page bitmap fonts are supported.');
  47771. }
  47772. if (!fontWidthFactors[fontSrc]) {
  47773. font.widthFactor = fontWidthFactors[font] = computeFontWidthFactor(font);
  47774. }
  47775. // Update geometry given font metrics.
  47776. self.updateGeometry(geometry, font);
  47777. // Set font and update layout.
  47778. self.currentFont = font;
  47779. self.updateLayout();
  47780. // Look up font image URL to use, and perform cached load.
  47781. fontImgSrc = self.getFontImageSrc();
  47782. cache.get(fontImgSrc, function () {
  47783. return loadTexture(fontImgSrc);
  47784. }).then(function (image) {
  47785. // Make mesh visible and apply font image as texture.
  47786. var texture = self.texture;
  47787. texture.image = image;
  47788. texture.needsUpdate = true;
  47789. textures[data.font] = texture;
  47790. self.texture = texture;
  47791. self.mesh.visible = true;
  47792. el.emit('textfontset', {font: data.font, fontObj: font});
  47793. }).catch(function (err) {
  47794. error(err.message);
  47795. error(err.stack);
  47796. });
  47797. }).catch(function (err) {
  47798. error(err.message);
  47799. error(err.stack);
  47800. });
  47801. },
  47802. getFontImageSrc: function () {
  47803. if (this.data.fontImage) { return this.data.fontImage; }
  47804. var fontSrc = this.lookupFont(this.data.font || DEFAULT_FONT) || this.data.font;
  47805. var imageSrc = this.currentFont.pages[0];
  47806. // If the image URL contains a non-HTTP(S) protocol, assume it's an absolute
  47807. // path on disk and try to infer the path from the font source instead.
  47808. if (imageSrc.match(protocolRe) && imageSrc.indexOf('http') !== 0) {
  47809. return fontSrc.replace(/(\.fnt)|(\.json)/, '.png');
  47810. }
  47811. return THREE.LoaderUtils.extractUrlBase(fontSrc) + imageSrc;
  47812. },
  47813. /**
  47814. * Update layout with anchor, alignment, baseline, and considering any meshes.
  47815. */
  47816. updateLayout: function () {
  47817. var anchor;
  47818. var baseline;
  47819. var el = this.el;
  47820. var data = this.data;
  47821. var geometry = this.geometry;
  47822. var geometryComponent;
  47823. var height;
  47824. var layout;
  47825. var mesh = this.mesh;
  47826. var textRenderWidth;
  47827. var textScale;
  47828. var width;
  47829. var x;
  47830. var y;
  47831. if (!geometry.layout) { return; }
  47832. // Determine width to use (defined width, geometry's width, or default width).
  47833. geometryComponent = el.getAttribute('geometry');
  47834. width = data.width || (geometryComponent && geometryComponent.width) || DEFAULT_WIDTH;
  47835. // Determine wrap pixel count. Either specified or by experimental fudge factor.
  47836. // Note that experimental factor will never be correct for variable width fonts.
  47837. textRenderWidth = computeWidth(data.wrapPixels, data.wrapCount,
  47838. this.currentFont.widthFactor);
  47839. textScale = width / textRenderWidth;
  47840. // Determine height to use.
  47841. layout = geometry.layout;
  47842. height = textScale * (layout.height + layout.descender);
  47843. // Update geometry dimensions to match text layout if width and height are set to 0.
  47844. // For example, scales a plane to fit text.
  47845. if (geometryComponent && geometryComponent.primitive === 'plane') {
  47846. if (!geometryComponent.width) { el.setAttribute('geometry', 'width', width); }
  47847. if (!geometryComponent.height) { el.setAttribute('geometry', 'height', height); }
  47848. }
  47849. // Calculate X position to anchor text left, center, or right.
  47850. anchor = data.anchor === 'align' ? data.align : data.anchor;
  47851. if (anchor === 'left') {
  47852. x = 0;
  47853. } else if (anchor === 'right') {
  47854. x = -1 * layout.width;
  47855. } else if (anchor === 'center') {
  47856. x = -1 * layout.width / 2;
  47857. } else {
  47858. throw new TypeError('Invalid text.anchor property value', anchor);
  47859. }
  47860. // Calculate Y position to anchor text top, center, or bottom.
  47861. baseline = data.baseline;
  47862. if (baseline === 'bottom') {
  47863. y = 0;
  47864. } else if (baseline === 'top') {
  47865. y = -1 * layout.height + layout.ascender;
  47866. } else if (baseline === 'center') {
  47867. y = -1 * layout.height / 2;
  47868. } else {
  47869. throw new TypeError('Invalid text.baseline property value', baseline);
  47870. }
  47871. // Position and scale mesh to apply layout.
  47872. mesh.position.x = x * textScale + data.xOffset;
  47873. mesh.position.y = y * textScale;
  47874. // Place text slightly in front to avoid Z-fighting.
  47875. mesh.position.z = data.zOffset;
  47876. mesh.scale.set(textScale, -1 * textScale, textScale);
  47877. },
  47878. /**
  47879. * Grab font from the constant.
  47880. * Set as a method for test stubbing purposes.
  47881. */
  47882. lookupFont: function (key) {
  47883. return FONTS[key];
  47884. },
  47885. /**
  47886. * Update the text geometry using `three-bmfont-text.update`.
  47887. */
  47888. updateGeometry: (function () {
  47889. var geometryUpdateBase = {};
  47890. var geometryUpdateData = {};
  47891. var newLineRegex = /\\n/g;
  47892. var tabRegex = /\\t/g;
  47893. return function (geometry, font) {
  47894. var data = this.data;
  47895. geometryUpdateData.font = font;
  47896. geometryUpdateData.lineHeight = data.lineHeight && isFinite(data.lineHeight)
  47897. ? data.lineHeight
  47898. : font.common.lineHeight;
  47899. geometryUpdateData.text = data.value.toString().replace(newLineRegex, '\n')
  47900. .replace(tabRegex, '\t');
  47901. geometryUpdateData.width = computeWidth(data.wrapPixels, data.wrapCount,
  47902. font.widthFactor);
  47903. geometry.update(utils.extend(geometryUpdateBase, data, geometryUpdateData));
  47904. };
  47905. })()
  47906. });
  47907. /**
  47908. * Due to using negative scale, we return the opposite side specified.
  47909. * https://github.com/mrdoob/three.js/pull/12787/
  47910. */
  47911. function parseSide (side) {
  47912. switch (side) {
  47913. case 'back': {
  47914. return THREE.FrontSide;
  47915. }
  47916. case 'double': {
  47917. return THREE.DoubleSide;
  47918. }
  47919. default: {
  47920. return THREE.BackSide;
  47921. }
  47922. }
  47923. }
  47924. /**
  47925. * @returns {Promise}
  47926. */
  47927. function loadFont (src, yOffset) {
  47928. return new Promise(function (resolve, reject) {
  47929. loadBMFont(src, function (err, font) {
  47930. if (err) {
  47931. error('Error loading font', src);
  47932. reject(err);
  47933. return;
  47934. }
  47935. // Fix negative Y offsets for Roboto MSDF font from tool. Experimentally determined.
  47936. if (src.indexOf('/Roboto-msdf.json') >= 0) { yOffset = 30; }
  47937. if (yOffset) { font.chars.map(function doOffset (ch) { ch.yoffset += yOffset; }); }
  47938. resolve(font);
  47939. });
  47940. });
  47941. }
  47942. /**
  47943. * @returns {Promise}
  47944. */
  47945. function loadTexture (src) {
  47946. return new Promise(function (resolve, reject) {
  47947. new THREE.ImageLoader().load(src, function (image) {
  47948. resolve(image);
  47949. }, undefined, function () {
  47950. error('Error loading font image', src);
  47951. reject(null);
  47952. });
  47953. });
  47954. }
  47955. function createShader (el, shaderName, data) {
  47956. var shader;
  47957. var shaderObject;
  47958. // Set up Shader.
  47959. shaderObject = new shaders[shaderName].Shader();
  47960. shaderObject.el = el;
  47961. shaderObject.init(data);
  47962. shaderObject.update(data);
  47963. // Get material.
  47964. shader = shaderObject.material;
  47965. // Apparently, was not set on `init` nor `update`.
  47966. shader.transparent = data.transparent;
  47967. return {
  47968. material: shader,
  47969. shader: shaderObject
  47970. };
  47971. }
  47972. /**
  47973. * Determine wrap pixel count. Either specified or by experimental fudge factor.
  47974. * Note that experimental factor will never be correct for variable width fonts.
  47975. */
  47976. function computeWidth (wrapPixels, wrapCount, widthFactor) {
  47977. return wrapPixels || ((0.5 + wrapCount) * widthFactor);
  47978. }
  47979. /**
  47980. * Compute default font width factor to use.
  47981. */
  47982. function computeFontWidthFactor (font) {
  47983. var sum = 0;
  47984. var digitsum = 0;
  47985. var digits = 0;
  47986. font.chars.map(function (ch) {
  47987. sum += ch.xadvance;
  47988. if (ch.id >= 48 && ch.id <= 57) {
  47989. digits++;
  47990. digitsum += ch.xadvance;
  47991. }
  47992. });
  47993. return digits ? digitsum / digits : sum / font.chars.length;
  47994. }
  47995. /**
  47996. * Get or create a promise given a key and promise generator.
  47997. * @todo Move to a utility and use in other parts of A-Frame.
  47998. */
  47999. function PromiseCache () {
  48000. var cache = this.cache = {};
  48001. this.get = function (key, promiseGenerator) {
  48002. if (key in cache) {
  48003. return cache[key];
  48004. }
  48005. cache[key] = promiseGenerator();
  48006. return cache[key];
  48007. };
  48008. }
  48009. },{"../core/component":105,"../core/shader":115,"../lib/three":154,"../utils/":178,"load-bmfont":23,"three-bmfont-text":35}],89:[function(_dereq_,module,exports){
  48010. var registerComponent = _dereq_('../core/component').registerComponent;
  48011. var controllerUtils = _dereq_('../utils/tracked-controls');
  48012. var DEFAULT_CAMERA_HEIGHT = _dereq_('../constants').DEFAULT_CAMERA_HEIGHT;
  48013. var THREE = _dereq_('../lib/three');
  48014. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  48015. // Vector from eyes to elbow (divided by user height).
  48016. var EYES_TO_ELBOW = {x: 0.175, y: -0.3, z: -0.03};
  48017. // Vector from eyes to elbow (divided by user height).
  48018. var FOREARM = {x: 0, y: 0, z: -0.175};
  48019. // Due to unfortunate name collision, add empty touches array to avoid Daydream error.
  48020. var EMPTY_DAYDREAM_TOUCHES = {touches: []};
  48021. var EVENTS = {
  48022. AXISMOVE: 'axismove',
  48023. BUTTONCHANGED: 'buttonchanged',
  48024. BUTTONDOWN: 'buttondown',
  48025. BUTTONUP: 'buttonup',
  48026. TOUCHSTART: 'touchstart',
  48027. TOUCHEND: 'touchend'
  48028. };
  48029. /**
  48030. * Tracked controls component.
  48031. * Wrap the gamepad API for pose and button states.
  48032. * Select the appropriate controller and apply pose to the entity.
  48033. * Observe button states and emit appropriate events.
  48034. *
  48035. * @property {number} controller - Index of controller in array returned by Gamepad API.
  48036. * Only used if hand property is not set.
  48037. * @property {string} id - Selected controller among those returned by Gamepad API.
  48038. * @property {number} hand - If multiple controllers found with id, choose the one with the
  48039. * given value for hand. If set, we ignore 'controller' property
  48040. */
  48041. module.exports.Component = registerComponent('tracked-controls-webvr', {
  48042. schema: {
  48043. autoHide: {default: true},
  48044. controller: {default: 0},
  48045. id: {type: 'string', default: ''},
  48046. hand: {type: 'string', default: ''},
  48047. idPrefix: {type: 'string', default: ''},
  48048. orientationOffset: {type: 'vec3'},
  48049. // Arm model parameters when not 6DoF.
  48050. armModel: {default: true},
  48051. headElement: {type: 'selector'}
  48052. },
  48053. init: function () {
  48054. // Copy variables back to tracked-controls for backwards compatibility.
  48055. // Some 3rd components rely on them.
  48056. this.axis = this.el.components['tracked-controls'].axis = [0, 0, 0];
  48057. this.buttonStates = this.el.components['tracked-controls'].buttonStates = {};
  48058. this.changedAxes = [];
  48059. this.targetControllerNumber = this.data.controller;
  48060. this.axisMoveEventDetail = {axis: this.axis, changed: this.changedAxes};
  48061. this.deltaControllerPosition = new THREE.Vector3();
  48062. this.controllerQuaternion = new THREE.Quaternion();
  48063. this.controllerEuler = new THREE.Euler();
  48064. this.updateGamepad();
  48065. this.buttonEventDetails = {};
  48066. },
  48067. tick: function (time, delta) {
  48068. var mesh = this.el.getObject3D('mesh');
  48069. // Update mesh animations.
  48070. if (mesh && mesh.update) { mesh.update(delta / 1000); }
  48071. this.updateGamepad();
  48072. this.updatePose();
  48073. this.updateButtons();
  48074. },
  48075. /**
  48076. * Return default user height to use for non-6DOF arm model.
  48077. */
  48078. defaultUserHeight: function () {
  48079. return DEFAULT_CAMERA_HEIGHT;
  48080. },
  48081. /**
  48082. * Return head element to use for non-6DOF arm model.
  48083. */
  48084. getHeadElement: function () {
  48085. return this.data.headElement || this.el.sceneEl.camera.el;
  48086. },
  48087. /**
  48088. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  48089. */
  48090. updateGamepad: function () {
  48091. var data = this.data;
  48092. var controller = controllerUtils.findMatchingControllerWebVR(
  48093. this.system.controllers,
  48094. data.id,
  48095. data.idPrefix,
  48096. data.hand,
  48097. data.controller
  48098. );
  48099. this.controller = controller;
  48100. // Legacy handle to the controller for old components.
  48101. this.el.components['tracked-controls'].controller = controller;
  48102. if (this.data.autoHide) { this.el.object3D.visible = !!this.controller; }
  48103. },
  48104. /**
  48105. * Applies an artificial arm model to simulate elbow to wrist positioning
  48106. * based on the orientation of the controller.
  48107. *
  48108. * @param {object} controllerPosition - Existing vector to update with controller position.
  48109. */
  48110. applyArmModel: function (controllerPosition) {
  48111. // Use controllerPosition and deltaControllerPosition to avoid creating variables.
  48112. var controller = this.controller;
  48113. var controllerEuler = this.controllerEuler;
  48114. var controllerQuaternion = this.controllerQuaternion;
  48115. var deltaControllerPosition = this.deltaControllerPosition;
  48116. var hand;
  48117. var headEl;
  48118. var headObject3D;
  48119. var pose;
  48120. var userHeight;
  48121. headEl = this.getHeadElement();
  48122. headObject3D = headEl.object3D;
  48123. userHeight = this.defaultUserHeight();
  48124. pose = controller.pose;
  48125. hand = (controller ? controller.hand : undefined) || DEFAULT_HANDEDNESS;
  48126. // Use camera position as head position.
  48127. controllerPosition.copy(headObject3D.position);
  48128. // Set offset for degenerate "arm model" to elbow.
  48129. deltaControllerPosition.set(
  48130. EYES_TO_ELBOW.x * (hand === 'left' ? -1 : hand === 'right' ? 1 : 0),
  48131. EYES_TO_ELBOW.y, // Lower than our eyes.
  48132. EYES_TO_ELBOW.z); // Slightly out in front.
  48133. // Scale offset by user height.
  48134. deltaControllerPosition.multiplyScalar(userHeight);
  48135. // Apply camera Y rotation (not X or Z, so you can look down at your hand).
  48136. deltaControllerPosition.applyAxisAngle(headObject3D.up, headObject3D.rotation.y);
  48137. // Apply rotated offset to position.
  48138. controllerPosition.add(deltaControllerPosition);
  48139. // Set offset for degenerate "arm model" forearm. Forearm sticking out from elbow.
  48140. deltaControllerPosition.set(FOREARM.x, FOREARM.y, FOREARM.z);
  48141. // Scale offset by user height.
  48142. deltaControllerPosition.multiplyScalar(userHeight);
  48143. // Apply controller X/Y rotation (tilting up/down/left/right is usually moving the arm).
  48144. if (pose.orientation) {
  48145. controllerQuaternion.fromArray(pose.orientation);
  48146. } else {
  48147. controllerQuaternion.copy(headObject3D.quaternion);
  48148. }
  48149. controllerEuler.setFromQuaternion(controllerQuaternion);
  48150. controllerEuler.set(controllerEuler.x, controllerEuler.y, 0);
  48151. deltaControllerPosition.applyEuler(controllerEuler);
  48152. // Apply rotated offset to position.
  48153. controllerPosition.add(deltaControllerPosition);
  48154. },
  48155. /**
  48156. * Read pose from controller (from Gamepad API), apply transforms, apply to entity.
  48157. */
  48158. updatePose: function () {
  48159. var controller = this.controller;
  48160. var data = this.data;
  48161. var object3D = this.el.object3D;
  48162. var pose;
  48163. var vrDisplay = this.system.vrDisplay;
  48164. var standingMatrix;
  48165. if (!controller) { return; }
  48166. // Compose pose from Gamepad.
  48167. pose = controller.pose;
  48168. if (pose.position) {
  48169. object3D.position.fromArray(pose.position);
  48170. } else {
  48171. // Controller not 6DOF, apply arm model.
  48172. if (data.armModel) { this.applyArmModel(object3D.position); }
  48173. }
  48174. if (pose.orientation) {
  48175. object3D.quaternion.fromArray(pose.orientation);
  48176. }
  48177. // Apply transforms, if 6DOF and in VR.
  48178. if (vrDisplay && pose.position) {
  48179. standingMatrix = this.el.sceneEl.renderer.vr.getStandingMatrix();
  48180. object3D.matrix.compose(object3D.position, object3D.quaternion, object3D.scale);
  48181. object3D.matrix.multiplyMatrices(standingMatrix, object3D.matrix);
  48182. object3D.matrix.decompose(object3D.position, object3D.quaternion, object3D.scale);
  48183. }
  48184. object3D.rotateX(this.data.orientationOffset.x * THREE.Math.DEG2RAD);
  48185. object3D.rotateY(this.data.orientationOffset.y * THREE.Math.DEG2RAD);
  48186. object3D.rotateZ(this.data.orientationOffset.z * THREE.Math.DEG2RAD);
  48187. },
  48188. /**
  48189. * Handle button changes including axes, presses, touches, values.
  48190. */
  48191. updateButtons: function () {
  48192. var buttonState;
  48193. var controller = this.controller;
  48194. var id;
  48195. if (!controller) { return; }
  48196. // Check every button.
  48197. for (id = 0; id < controller.buttons.length; ++id) {
  48198. // Initialize button state.
  48199. if (!this.buttonStates[id]) {
  48200. this.buttonStates[id] = {pressed: false, touched: false, value: 0};
  48201. }
  48202. if (!this.buttonEventDetails[id]) {
  48203. this.buttonEventDetails[id] = {id: id, state: this.buttonStates[id]};
  48204. }
  48205. buttonState = controller.buttons[id];
  48206. this.handleButton(id, buttonState);
  48207. }
  48208. // Check axes.
  48209. this.handleAxes();
  48210. },
  48211. /**
  48212. * Handle presses and touches for a single button.
  48213. *
  48214. * @param {number} id - Index of button in Gamepad button array.
  48215. * @param {number} buttonState - Value of button state from 0 to 1.
  48216. * @returns {boolean} Whether button has changed in any way.
  48217. */
  48218. handleButton: function (id, buttonState) {
  48219. var changed;
  48220. changed = this.handlePress(id, buttonState) |
  48221. this.handleTouch(id, buttonState) |
  48222. this.handleValue(id, buttonState);
  48223. if (!changed) { return false; }
  48224. this.el.emit(EVENTS.BUTTONCHANGED, this.buttonEventDetails[id], false);
  48225. return true;
  48226. },
  48227. /**
  48228. * An axis is an array of values from -1 (up, left) to 1 (down, right).
  48229. * Compare each component of the axis to the previous value to determine change.
  48230. *
  48231. * @returns {boolean} Whether axes changed.
  48232. */
  48233. handleAxes: function () {
  48234. var changed = false;
  48235. var controllerAxes = this.controller.axes;
  48236. var i;
  48237. var previousAxis = this.axis;
  48238. var changedAxes = this.changedAxes;
  48239. // Check if axis changed.
  48240. this.changedAxes.length = 0;
  48241. for (i = 0; i < controllerAxes.length; ++i) {
  48242. changedAxes.push(previousAxis[i] !== controllerAxes[i]);
  48243. if (changedAxes[i]) { changed = true; }
  48244. }
  48245. if (!changed) { return false; }
  48246. this.axis.length = 0;
  48247. for (i = 0; i < controllerAxes.length; i++) {
  48248. this.axis.push(controllerAxes[i]);
  48249. }
  48250. this.el.emit(EVENTS.AXISMOVE, this.axisMoveEventDetail, false);
  48251. return true;
  48252. },
  48253. /**
  48254. * Determine whether a button press has occured and emit events as appropriate.
  48255. *
  48256. * @param {string} id - ID of the button to check.
  48257. * @param {object} buttonState - State of the button to check.
  48258. * @returns {boolean} Whether button press state changed.
  48259. */
  48260. handlePress: function (id, buttonState) {
  48261. var evtName;
  48262. var previousButtonState = this.buttonStates[id];
  48263. // Not changed.
  48264. if (buttonState.pressed === previousButtonState.pressed) { return false; }
  48265. evtName = buttonState.pressed ? EVENTS.BUTTONDOWN : EVENTS.BUTTONUP;
  48266. this.el.emit(evtName, this.buttonEventDetails[id], false);
  48267. previousButtonState.pressed = buttonState.pressed;
  48268. return true;
  48269. },
  48270. /**
  48271. * Determine whether a button touch has occured and emit events as appropriate.
  48272. *
  48273. * @param {string} id - ID of the button to check.
  48274. * @param {object} buttonState - State of the button to check.
  48275. * @returns {boolean} Whether button touch state changed.
  48276. */
  48277. handleTouch: function (id, buttonState) {
  48278. var evtName;
  48279. var previousButtonState = this.buttonStates[id];
  48280. // Not changed.
  48281. if (buttonState.touched === previousButtonState.touched) { return false; }
  48282. evtName = buttonState.touched ? EVENTS.TOUCHSTART : EVENTS.TOUCHEND;
  48283. this.el.emit(evtName, this.buttonEventDetails[id], false, EMPTY_DAYDREAM_TOUCHES);
  48284. previousButtonState.touched = buttonState.touched;
  48285. return true;
  48286. },
  48287. /**
  48288. * Determine whether a button value has changed.
  48289. *
  48290. * @param {string} id - Id of the button to check.
  48291. * @param {object} buttonState - State of the button to check.
  48292. * @returns {boolean} Whether button value changed.
  48293. */
  48294. handleValue: function (id, buttonState) {
  48295. var previousButtonState = this.buttonStates[id];
  48296. // Not changed.
  48297. if (buttonState.value === previousButtonState.value) { return false; }
  48298. previousButtonState.value = buttonState.value;
  48299. return true;
  48300. }
  48301. });
  48302. },{"../constants":97,"../core/component":105,"../lib/three":154,"../utils/tracked-controls":185}],90:[function(_dereq_,module,exports){
  48303. var controllerUtils = _dereq_('../utils/tracked-controls');
  48304. var registerComponent = _dereq_('../core/component').registerComponent;
  48305. module.exports.Component = registerComponent('tracked-controls-webxr', {
  48306. schema: {
  48307. hand: {type: 'string', default: ''}
  48308. },
  48309. init: function () {
  48310. this.addSessionEventListeners = this.addSessionEventListeners.bind(this);
  48311. this.updateController = this.updateController.bind(this);
  48312. this.emitButtonUpEvent = this.emitButtonUpEvent.bind(this);
  48313. this.emitButtonDownEvent = this.emitButtonDownEvent.bind(this);
  48314. this.buttonEventDetails = {id: 'trigger'};
  48315. },
  48316. play: function () {
  48317. var sceneEl = this.el.sceneEl;
  48318. this.updateController();
  48319. this.addSessionEventListeners();
  48320. sceneEl.addEventListener('enter-vr', this.addSessionEventListeners);
  48321. sceneEl.addEventListener('controllersupdated', this.updateController);
  48322. },
  48323. pause: function () {
  48324. var sceneEl = this.el.sceneEl;
  48325. this.removeSessionEventListeners();
  48326. sceneEl.removeEventListener('enter-vr', this.addSessionEventListeners);
  48327. sceneEl.removeEventListener('controllersupdated', this.updateController);
  48328. },
  48329. addSessionEventListeners: function () {
  48330. var sceneEl = this.el.sceneEl;
  48331. if (!sceneEl.xrSession) { return; }
  48332. sceneEl.xrSession.addEventListener('selectstart', this.emitButtonDownEvent);
  48333. sceneEl.xrSession.addEventListener('selectend', this.emitButtonUpEvent);
  48334. },
  48335. removeSessionEventListeners: function () {
  48336. var sceneEl = this.el.sceneEl;
  48337. if (!sceneEl.xrSession) { return; }
  48338. sceneEl.xrSession.addEventListener('selectstart', this.emitButtonDownEvent);
  48339. sceneEl.xrSession.addEventListener('selectend', this.emitButtonUpEvent);
  48340. },
  48341. emitButtonDownEvent: function (evt) {
  48342. if (!this.controller || evt.inputSource.handedness !== this.data.hand) { return; }
  48343. this.el.emit('buttondown', this.buttonEventDetails);
  48344. this.el.emit('triggerdown');
  48345. },
  48346. emitButtonUpEvent: function (evt) {
  48347. if (!this.controller || evt.inputSource.handedness !== this.data.hand) { return; }
  48348. this.el.emit('buttonup', this.buttonEventDetails);
  48349. this.el.emit('triggerup');
  48350. },
  48351. /**
  48352. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  48353. */
  48354. updateController: function () {
  48355. this.controller = controllerUtils.findMatchingControllerWebXR(
  48356. this.system.controllers,
  48357. this.data.hand
  48358. );
  48359. // Legacy handle to the controller for old components.
  48360. this.el.components['tracked-controls'].controller = this.controller;
  48361. if (this.data.autoHide) { this.el.object3D.visible = !!this.controller; }
  48362. },
  48363. tick: function () {
  48364. var pose;
  48365. var sceneEl = this.el.sceneEl;
  48366. var object3D = this.el.object3D;
  48367. if (!this.controller || !sceneEl.frame) { return; }
  48368. pose = sceneEl.frame.getInputPose(this.controller, sceneEl.frameOfReference);
  48369. if (!pose) { return; }
  48370. object3D.matrix.elements = pose.targetRay.transformMatrix;
  48371. object3D.matrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  48372. }
  48373. });
  48374. },{"../core/component":105,"../utils/tracked-controls":185}],91:[function(_dereq_,module,exports){
  48375. var registerComponent = _dereq_('../core/component').registerComponent;
  48376. /**
  48377. * Tracked controls.
  48378. * Abstract controls that decide if the WebVR or WebXR version is going to be applied.
  48379. *
  48380. * @property {number} controller - Index of controller in array returned by Gamepad API.
  48381. * Only used if hand property is not set.
  48382. * @property {string} id - Selected controller among those returned by Gamepad API.
  48383. * @property {number} hand - If multiple controllers found with id, choose the one with the
  48384. * given value for hand. If set, we ignore 'controller' property
  48385. */
  48386. module.exports.Component = registerComponent('tracked-controls', {
  48387. schema: {
  48388. autoHide: {default: true},
  48389. controller: {default: 0},
  48390. id: {type: 'string', default: ''},
  48391. hand: {type: 'string', default: ''},
  48392. idPrefix: {type: 'string', default: ''},
  48393. orientationOffset: {type: 'vec3'},
  48394. // Arm model parameters when not 6DoF.
  48395. armModel: {default: true},
  48396. headElement: {type: 'selector'}
  48397. },
  48398. update: function () {
  48399. var data = this.data;
  48400. var el = this.el;
  48401. if (el.sceneEl.hasWebXR) {
  48402. el.setAttribute('tracked-controls-webxr', data);
  48403. } else {
  48404. el.setAttribute('tracked-controls-webvr', data);
  48405. }
  48406. }
  48407. });
  48408. },{"../core/component":105}],92:[function(_dereq_,module,exports){
  48409. var registerComponent = _dereq_('../core/component').registerComponent;
  48410. /**
  48411. * Visibility component.
  48412. */
  48413. module.exports.Component = registerComponent('visible', {
  48414. schema: {default: true},
  48415. update: function () {
  48416. this.el.object3D.visible = this.data;
  48417. }
  48418. });
  48419. },{"../core/component":105}],93:[function(_dereq_,module,exports){
  48420. var registerComponent = _dereq_('../core/component').registerComponent;
  48421. var utils = _dereq_('../utils/');
  48422. var bind = utils.bind;
  48423. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  48424. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  48425. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  48426. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  48427. var VIVE_CONTROLLER_MODEL_OBJ_URL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.obj';
  48428. var VIVE_CONTROLLER_MODEL_OBJ_MTL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.mtl';
  48429. var GAMEPAD_ID_PREFIX = 'OpenVR ';
  48430. /**
  48431. * Vive controls.
  48432. * Interface with Vive controllers and map Gamepad events to controller buttons:
  48433. * trackpad, trigger, grip, menu, system
  48434. * Load a controller model and highlight the pressed buttons.
  48435. */
  48436. module.exports.Component = registerComponent('vive-controls', {
  48437. schema: {
  48438. hand: {default: 'left'},
  48439. buttonColor: {type: 'color', default: '#FAFAFA'}, // Off-white.
  48440. buttonHighlightColor: {type: 'color', default: '#22D1EE'}, // Light blue.
  48441. model: {default: true},
  48442. orientationOffset: {type: 'vec3'}
  48443. },
  48444. /**
  48445. * Button IDs:
  48446. * 0 - trackpad
  48447. * 1 - trigger (intensity value from 0.5 to 1)
  48448. * 2 - grip
  48449. * 3 - menu (dispatch but better for menu options)
  48450. * 4 - system (never dispatched on this layer)
  48451. */
  48452. mapping: {
  48453. axes: {trackpad: [0, 1]},
  48454. buttons: ['trackpad', 'trigger', 'grip', 'menu', 'system']
  48455. },
  48456. init: function () {
  48457. var self = this;
  48458. this.animationActive = 'pointing';
  48459. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // To allow mock.
  48460. this.controllerPresent = false;
  48461. this.emitIfAxesChanged = emitIfAxesChanged; // To allow mock.
  48462. this.lastControllerCheck = 0;
  48463. this.onButtonChanged = bind(this.onButtonChanged, this);
  48464. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  48465. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  48466. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  48467. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  48468. this.onAxisMoved = bind(this.onAxisMoved, this);
  48469. this.previousButtonValues = {};
  48470. this.bindMethods();
  48471. },
  48472. play: function () {
  48473. this.checkIfControllerPresent();
  48474. this.addControllersUpdateListener();
  48475. },
  48476. pause: function () {
  48477. this.removeEventListeners();
  48478. this.removeControllersUpdateListener();
  48479. },
  48480. bindMethods: function () {
  48481. this.onModelLoaded = bind(this.onModelLoaded, this);
  48482. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  48483. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  48484. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  48485. this.onAxisMoved = bind(this.onAxisMoved, this);
  48486. },
  48487. addEventListeners: function () {
  48488. var el = this.el;
  48489. el.addEventListener('buttonchanged', this.onButtonChanged);
  48490. el.addEventListener('buttondown', this.onButtonDown);
  48491. el.addEventListener('buttonup', this.onButtonUp);
  48492. el.addEventListener('touchend', this.onButtonTouchEnd);
  48493. el.addEventListener('touchstart', this.onButtonTouchStart);
  48494. el.addEventListener('model-loaded', this.onModelLoaded);
  48495. el.addEventListener('axismove', this.onAxisMoved);
  48496. this.controllerEventsActive = true;
  48497. },
  48498. removeEventListeners: function () {
  48499. var el = this.el;
  48500. el.removeEventListener('buttonchanged', this.onButtonChanged);
  48501. el.removeEventListener('buttondown', this.onButtonDown);
  48502. el.removeEventListener('buttonup', this.onButtonUp);
  48503. el.removeEventListener('touchend', this.onButtonTouchEnd);
  48504. el.removeEventListener('touchstart', this.onButtonTouchStart);
  48505. el.removeEventListener('model-loaded', this.onModelLoaded);
  48506. el.removeEventListener('axismove', this.onAxisMoved);
  48507. this.controllerEventsActive = false;
  48508. },
  48509. /**
  48510. * Once OpenVR returns correct hand data in supporting browsers, we can use hand property.
  48511. * var isPresent = this.checkControllerPresentAndSetup(this.el.sceneEl, GAMEPAD_ID_PREFIX,
  48512. { hand: data.hand });
  48513. * Until then, use hardcoded index.
  48514. */
  48515. checkIfControllerPresent: function () {
  48516. var data = this.data;
  48517. var controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  48518. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {index: controllerIndex});
  48519. },
  48520. injectTrackedControls: function () {
  48521. var el = this.el;
  48522. var data = this.data;
  48523. // If we have an OpenVR Gamepad, use the fixed mapping.
  48524. el.setAttribute('tracked-controls', {
  48525. idPrefix: GAMEPAD_ID_PREFIX,
  48526. // Hand IDs: 0 = right, 1 = left, 2 = anything else.
  48527. controller: data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2,
  48528. hand: data.hand,
  48529. orientationOffset: data.orientationOffset
  48530. });
  48531. // Load model.
  48532. if (!this.data.model) { return; }
  48533. this.el.setAttribute('obj-model', {
  48534. obj: VIVE_CONTROLLER_MODEL_OBJ_URL,
  48535. mtl: VIVE_CONTROLLER_MODEL_OBJ_MTL
  48536. });
  48537. },
  48538. addControllersUpdateListener: function () {
  48539. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  48540. },
  48541. removeControllersUpdateListener: function () {
  48542. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  48543. },
  48544. onControllersUpdate: function () {
  48545. this.checkIfControllerPresent();
  48546. },
  48547. /**
  48548. * Rotate the trigger button based on how hard the trigger is pressed.
  48549. */
  48550. onButtonChanged: function (evt) {
  48551. var button = this.mapping.buttons[evt.detail.id];
  48552. var buttonMeshes = this.buttonMeshes;
  48553. var analogValue;
  48554. if (!button) { return; }
  48555. if (button === 'trigger') {
  48556. analogValue = evt.detail.state.value;
  48557. // Update trigger rotation depending on button value.
  48558. if (buttonMeshes && buttonMeshes.trigger) {
  48559. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 12);
  48560. }
  48561. }
  48562. // Pass along changed event with button state, using button mapping for convenience.
  48563. this.el.emit(button + 'changed', evt.detail.state);
  48564. },
  48565. onModelLoaded: function (evt) {
  48566. var buttonMeshes;
  48567. var controllerObject3D = evt.detail.model;
  48568. var self = this;
  48569. if (!this.data.model) { return; }
  48570. // Store button meshes object to be able to change their colors.
  48571. buttonMeshes = this.buttonMeshes = {};
  48572. buttonMeshes.grip = {
  48573. left: controllerObject3D.getObjectByName('leftgrip'),
  48574. right: controllerObject3D.getObjectByName('rightgrip')
  48575. };
  48576. buttonMeshes.menu = controllerObject3D.getObjectByName('menubutton');
  48577. buttonMeshes.system = controllerObject3D.getObjectByName('systembutton');
  48578. buttonMeshes.trackpad = controllerObject3D.getObjectByName('touchpad');
  48579. buttonMeshes.trigger = controllerObject3D.getObjectByName('trigger');
  48580. // Set default colors.
  48581. Object.keys(buttonMeshes).forEach(function (buttonName) {
  48582. self.setButtonColor(buttonName, self.data.buttonColor);
  48583. });
  48584. // Offset pivot point.
  48585. controllerObject3D.position.set(0, -0.015, 0.04);
  48586. },
  48587. onAxisMoved: function (evt) {
  48588. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  48589. },
  48590. updateModel: function (buttonName, evtName) {
  48591. var color;
  48592. var isTouch;
  48593. if (!this.data.model) { return; }
  48594. isTouch = evtName.indexOf('touch') !== -1;
  48595. // Don't change color for trackpad touch.
  48596. if (isTouch) { return; }
  48597. // Update colors.
  48598. color = evtName === 'up' ? this.data.buttonColor : this.data.buttonHighlightColor;
  48599. this.setButtonColor(buttonName, color);
  48600. },
  48601. setButtonColor: function (buttonName, color) {
  48602. var buttonMeshes = this.buttonMeshes;
  48603. if (!buttonMeshes) { return; }
  48604. // Need to do both left and right sides for grip.
  48605. if (buttonName === 'grip') {
  48606. buttonMeshes.grip.left.material.color.set(color);
  48607. buttonMeshes.grip.right.material.color.set(color);
  48608. return;
  48609. }
  48610. buttonMeshes[buttonName].material.color.set(color);
  48611. }
  48612. });
  48613. },{"../core/component":105,"../utils/":178,"../utils/tracked-controls":185}],94:[function(_dereq_,module,exports){
  48614. var registerComponent = _dereq_('../core/component').registerComponent;
  48615. var bind = _dereq_('../utils/bind');
  48616. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  48617. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  48618. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  48619. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  48620. var GAMEPAD_ID_PREFIX = 'HTC Vive Focus';
  48621. var VIVE_FOCUS_CONTROLLER_MODEL_URL = 'https://cdn.aframe.io/controllers/vive/focus-controller/focus-controller.gltf';
  48622. /**
  48623. * Vive Focus controls.
  48624. * Interface with Vive Focus controller and map Gamepad events to
  48625. * controller buttons: trackpad, trigger
  48626. * Load a controller model and highlight the pressed buttons.
  48627. */
  48628. module.exports.Component = registerComponent('vive-focus-controls', {
  48629. schema: {
  48630. hand: {default: ''}, // This informs the degenerate arm model.
  48631. buttonTouchedColor: {type: 'color', default: '#BBBBBB'},
  48632. buttonHighlightColor: {type: 'color', default: '#7A7A7A'},
  48633. model: {default: true},
  48634. rotationOffset: {default: 0},
  48635. armModel: {default: true}
  48636. },
  48637. /**
  48638. * Button IDs:
  48639. * 0 - trackpad
  48640. * 1 - trigger
  48641. */
  48642. mapping: {
  48643. axes: {trackpad: [0, 1]},
  48644. buttons: ['trigger', 'trackpad']
  48645. },
  48646. bindMethods: function () {
  48647. this.onModelLoaded = bind(this.onModelLoaded, this);
  48648. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  48649. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  48650. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  48651. this.onAxisMoved = bind(this.onAxisMoved, this);
  48652. },
  48653. init: function () {
  48654. var self = this;
  48655. this.animationActive = 'pointing';
  48656. this.onButtonChanged = bind(this.onButtonChanged, this);
  48657. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  48658. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  48659. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  48660. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  48661. this.onAxisMoved = bind(this.onAxisMoved, this);
  48662. this.controllerPresent = false;
  48663. this.lastControllerCheck = 0;
  48664. this.bindMethods();
  48665. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // To allow mock.
  48666. this.emitIfAxesChanged = emitIfAxesChanged; // To allow mock.
  48667. },
  48668. addEventListeners: function () {
  48669. var el = this.el;
  48670. el.addEventListener('buttonchanged', this.onButtonChanged);
  48671. el.addEventListener('buttondown', this.onButtonDown);
  48672. el.addEventListener('buttonup', this.onButtonUp);
  48673. el.addEventListener('touchstart', this.onButtonTouchStart);
  48674. el.addEventListener('touchend', this.onButtonTouchEnd);
  48675. el.addEventListener('model-loaded', this.onModelLoaded);
  48676. el.addEventListener('axismove', this.onAxisMoved);
  48677. this.controllerEventsActive = true;
  48678. this.addControllersUpdateListener();
  48679. },
  48680. removeEventListeners: function () {
  48681. var el = this.el;
  48682. el.removeEventListener('buttonchanged', this.onButtonChanged);
  48683. el.removeEventListener('buttondown', this.onButtonDown);
  48684. el.removeEventListener('buttonup', this.onButtonUp);
  48685. el.removeEventListener('touchstart', this.onButtonTouchStart);
  48686. el.removeEventListener('touchend', this.onButtonTouchEnd);
  48687. el.removeEventListener('model-loaded', this.onModelLoaded);
  48688. el.removeEventListener('axismove', this.onAxisMoved);
  48689. this.controllerEventsActive = false;
  48690. this.removeControllersUpdateListener();
  48691. },
  48692. checkIfControllerPresent: function () {
  48693. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  48694. this.data.hand ? {hand: this.data.hand} : {});
  48695. },
  48696. play: function () {
  48697. this.checkIfControllerPresent();
  48698. this.addControllersUpdateListener();
  48699. },
  48700. pause: function () {
  48701. this.removeEventListeners();
  48702. this.removeControllersUpdateListener();
  48703. },
  48704. injectTrackedControls: function () {
  48705. var el = this.el;
  48706. var data = this.data;
  48707. el.setAttribute('tracked-controls', {
  48708. armModel: data.armModel,
  48709. idPrefix: GAMEPAD_ID_PREFIX,
  48710. rotationOffset: data.rotationOffset
  48711. });
  48712. if (!this.data.model) { return; }
  48713. this.el.setAttribute('gltf-model', VIVE_FOCUS_CONTROLLER_MODEL_URL);
  48714. },
  48715. addControllersUpdateListener: function () {
  48716. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  48717. },
  48718. removeControllersUpdateListener: function () {
  48719. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  48720. },
  48721. onControllersUpdate: function () {
  48722. this.checkIfControllerPresent();
  48723. },
  48724. onModelLoaded: function (evt) {
  48725. var controllerObject3D = evt.detail.model;
  48726. var buttonMeshes;
  48727. if (!this.data.model) { return; }
  48728. buttonMeshes = this.buttonMeshes = {};
  48729. buttonMeshes.trigger = controllerObject3D.getObjectByName('BumperKey');
  48730. buttonMeshes.triggerPressed = controllerObject3D.getObjectByName('BumperKey_Press');
  48731. if (buttonMeshes.triggerPressed) {
  48732. buttonMeshes.triggerPressed.visible = false;
  48733. }
  48734. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad');
  48735. buttonMeshes.trackpadPressed = controllerObject3D.getObjectByName('TouchPad_Press');
  48736. if (buttonMeshes.trackpadPressed) {
  48737. buttonMeshes.trackpadPressed.visible = false;
  48738. }
  48739. },
  48740. // No analog buttons, only emits 0/1 values
  48741. onButtonChanged: function (evt) {
  48742. var button = this.mapping.buttons[evt.detail.id];
  48743. if (!button) return;
  48744. // Pass along changed event with button state, using button mapping for convenience.
  48745. this.el.emit(button + 'changed', evt.detail.state);
  48746. },
  48747. onAxisMoved: function (evt) {
  48748. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  48749. },
  48750. updateModel: function (buttonName, evtName) {
  48751. if (!this.data.model) { return; }
  48752. this.updateButtonModel(buttonName, evtName);
  48753. },
  48754. updateButtonModel: function (buttonName, state) {
  48755. var buttonMeshes = this.buttonMeshes;
  48756. var pressedName = buttonName + 'Pressed';
  48757. if (!buttonMeshes || !buttonMeshes[buttonName] || !buttonMeshes[pressedName]) {
  48758. return;
  48759. }
  48760. var color;
  48761. switch (state) {
  48762. case 'down':
  48763. color = this.data.buttonHighlightColor;
  48764. break;
  48765. case 'touchstart':
  48766. color = this.data.buttonTouchedColor;
  48767. break;
  48768. }
  48769. if (color) {
  48770. buttonMeshes[pressedName].material.color.set(color);
  48771. }
  48772. buttonMeshes[pressedName].visible = !!color;
  48773. buttonMeshes[buttonName].visible = !color;
  48774. }
  48775. });
  48776. },{"../core/component":105,"../utils/bind":172,"../utils/tracked-controls":185}],95:[function(_dereq_,module,exports){
  48777. var KEYCODE_TO_CODE = _dereq_('../constants').keyboardevent.KEYCODE_TO_CODE;
  48778. var registerComponent = _dereq_('../core/component').registerComponent;
  48779. var THREE = _dereq_('../lib/three');
  48780. var utils = _dereq_('../utils/');
  48781. var bind = utils.bind;
  48782. var shouldCaptureKeyEvent = utils.shouldCaptureKeyEvent;
  48783. var CLAMP_VELOCITY = 0.00001;
  48784. var MAX_DELTA = 0.2;
  48785. var KEYS = [
  48786. 'KeyW', 'KeyA', 'KeyS', 'KeyD',
  48787. 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'ArrowDown'
  48788. ];
  48789. /**
  48790. * WASD component to control entities using WASD keys.
  48791. */
  48792. module.exports.Component = registerComponent('wasd-controls', {
  48793. schema: {
  48794. acceleration: {default: 65},
  48795. adAxis: {default: 'x', oneOf: ['x', 'y', 'z']},
  48796. adEnabled: {default: true},
  48797. adInverted: {default: false},
  48798. easing: {default: 20},
  48799. enabled: {default: true},
  48800. fly: {default: false},
  48801. wsAxis: {default: 'z', oneOf: ['x', 'y', 'z']},
  48802. wsEnabled: {default: true},
  48803. wsInverted: {default: false}
  48804. },
  48805. init: function () {
  48806. // To keep track of the pressed keys.
  48807. this.keys = {};
  48808. this.velocity = new THREE.Vector3();
  48809. // Bind methods and add event listeners.
  48810. this.onBlur = bind(this.onBlur, this);
  48811. this.onFocus = bind(this.onFocus, this);
  48812. this.onKeyDown = bind(this.onKeyDown, this);
  48813. this.onKeyUp = bind(this.onKeyUp, this);
  48814. this.onVisibilityChange = bind(this.onVisibilityChange, this);
  48815. this.attachVisibilityEventListeners();
  48816. },
  48817. tick: function (time, delta) {
  48818. var data = this.data;
  48819. var el = this.el;
  48820. var velocity = this.velocity;
  48821. if (!velocity[data.adAxis] && !velocity[data.wsAxis] &&
  48822. isEmptyObject(this.keys)) { return; }
  48823. // Update velocity.
  48824. delta = delta / 1000;
  48825. this.updateVelocity(delta);
  48826. if (!velocity[data.adAxis] && !velocity[data.wsAxis]) { return; }
  48827. // Get movement vector and translate position.
  48828. el.object3D.position.add(this.getMovementVector(delta));
  48829. },
  48830. remove: function () {
  48831. this.removeKeyEventListeners();
  48832. this.removeVisibilityEventListeners();
  48833. },
  48834. play: function () {
  48835. this.attachKeyEventListeners();
  48836. },
  48837. pause: function () {
  48838. this.keys = {};
  48839. this.removeKeyEventListeners();
  48840. },
  48841. updateVelocity: function (delta) {
  48842. var acceleration;
  48843. var adAxis;
  48844. var adSign;
  48845. var data = this.data;
  48846. var keys = this.keys;
  48847. var velocity = this.velocity;
  48848. var wsAxis;
  48849. var wsSign;
  48850. adAxis = data.adAxis;
  48851. wsAxis = data.wsAxis;
  48852. // If FPS too low, reset velocity.
  48853. if (delta > MAX_DELTA) {
  48854. velocity[adAxis] = 0;
  48855. velocity[wsAxis] = 0;
  48856. return;
  48857. }
  48858. // Decay velocity.
  48859. if (velocity[adAxis] !== 0) {
  48860. velocity[adAxis] -= velocity[adAxis] * data.easing * delta;
  48861. }
  48862. if (velocity[wsAxis] !== 0) {
  48863. velocity[wsAxis] -= velocity[wsAxis] * data.easing * delta;
  48864. }
  48865. // Clamp velocity easing.
  48866. if (Math.abs(velocity[adAxis]) < CLAMP_VELOCITY) { velocity[adAxis] = 0; }
  48867. if (Math.abs(velocity[wsAxis]) < CLAMP_VELOCITY) { velocity[wsAxis] = 0; }
  48868. if (!data.enabled) { return; }
  48869. // Update velocity using keys pressed.
  48870. acceleration = data.acceleration;
  48871. if (data.adEnabled) {
  48872. adSign = data.adInverted ? -1 : 1;
  48873. if (keys.KeyA || keys.ArrowLeft) { velocity[adAxis] -= adSign * acceleration * delta; }
  48874. if (keys.KeyD || keys.ArrowRight) { velocity[adAxis] += adSign * acceleration * delta; }
  48875. }
  48876. if (data.wsEnabled) {
  48877. wsSign = data.wsInverted ? -1 : 1;
  48878. if (keys.KeyW || keys.ArrowUp) { velocity[wsAxis] -= wsSign * acceleration * delta; }
  48879. if (keys.KeyS || keys.ArrowDown) { velocity[wsAxis] += wsSign * acceleration * delta; }
  48880. }
  48881. },
  48882. getMovementVector: (function () {
  48883. var directionVector = new THREE.Vector3(0, 0, 0);
  48884. var rotationEuler = new THREE.Euler(0, 0, 0, 'YXZ');
  48885. return function (delta) {
  48886. var rotation = this.el.getAttribute('rotation');
  48887. var velocity = this.velocity;
  48888. var xRotation;
  48889. directionVector.copy(velocity);
  48890. directionVector.multiplyScalar(delta);
  48891. // Absolute.
  48892. if (!rotation) { return directionVector; }
  48893. xRotation = this.data.fly ? rotation.x : 0;
  48894. // Transform direction relative to heading.
  48895. rotationEuler.set(THREE.Math.degToRad(xRotation), THREE.Math.degToRad(rotation.y), 0);
  48896. directionVector.applyEuler(rotationEuler);
  48897. return directionVector;
  48898. };
  48899. })(),
  48900. attachVisibilityEventListeners: function () {
  48901. window.addEventListener('blur', this.onBlur);
  48902. window.addEventListener('focus', this.onFocus);
  48903. document.addEventListener('visibilitychange', this.onVisibilityChange);
  48904. },
  48905. removeVisibilityEventListeners: function () {
  48906. window.removeEventListener('blur', this.onBlur);
  48907. window.removeEventListener('focus', this.onFocus);
  48908. document.removeEventListener('visibilitychange', this.onVisibilityChange);
  48909. },
  48910. attachKeyEventListeners: function () {
  48911. window.addEventListener('keydown', this.onKeyDown);
  48912. window.addEventListener('keyup', this.onKeyUp);
  48913. },
  48914. removeKeyEventListeners: function () {
  48915. window.removeEventListener('keydown', this.onKeyDown);
  48916. window.removeEventListener('keyup', this.onKeyUp);
  48917. },
  48918. onBlur: function () {
  48919. this.pause();
  48920. },
  48921. onFocus: function () {
  48922. this.play();
  48923. },
  48924. onVisibilityChange: function () {
  48925. if (document.hidden) {
  48926. this.onBlur();
  48927. } else {
  48928. this.onFocus();
  48929. }
  48930. },
  48931. onKeyDown: function (event) {
  48932. var code;
  48933. if (!shouldCaptureKeyEvent(event)) { return; }
  48934. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  48935. if (KEYS.indexOf(code) !== -1) { this.keys[code] = true; }
  48936. },
  48937. onKeyUp: function (event) {
  48938. var code;
  48939. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  48940. delete this.keys[code];
  48941. }
  48942. });
  48943. function isEmptyObject (keys) {
  48944. var key;
  48945. for (key in keys) { return false; }
  48946. return true;
  48947. }
  48948. },{"../constants":97,"../core/component":105,"../lib/three":154,"../utils/":178}],96:[function(_dereq_,module,exports){
  48949. /* global THREE */
  48950. var bind = _dereq_('../utils/bind');
  48951. var registerComponent = _dereq_('../core/component').registerComponent;
  48952. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  48953. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  48954. var utils = _dereq_('../utils/');
  48955. var debug = utils.debug('components:windows-motion-controls:debug');
  48956. var warn = utils.debug('components:windows-motion-controls:warn');
  48957. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  48958. var MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/microsoft/';
  48959. var MODEL_FILENAMES = { left: 'left.glb', right: 'right.glb', default: 'universal.glb' };
  48960. var GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  48961. var GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  48962. /**
  48963. * Windows Motion Controller controls.
  48964. * Interface with Windows Motion Controller controllers and map Gamepad events to
  48965. * controller buttons: trackpad, trigger, grip, menu, thumbstick
  48966. * Load a controller model and transform the pressed buttons.
  48967. */
  48968. module.exports.Component = registerComponent('windows-motion-controls', {
  48969. schema: {
  48970. hand: {default: DEFAULT_HANDEDNESS},
  48971. // It is possible to have multiple pairs of controllers attached (a pair has both left and right).
  48972. // Set this to 1 to use a controller from the second pair, 2 from the third pair, etc.
  48973. pair: {default: 0},
  48974. // If true, loads the controller glTF asset.
  48975. model: {default: true},
  48976. // If true, will hide the model from the scene if no matching gamepad (based on ID & hand) is connected.
  48977. hideDisconnected: {default: true}
  48978. },
  48979. mapping: {
  48980. // A-Frame specific semantic axis names
  48981. axes: {'thumbstick': [0, 1], 'trackpad': [2, 3]},
  48982. // A-Frame specific semantic button names
  48983. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  48984. // A mapping of the semantic name to node name in the glTF model file,
  48985. // that should be transformed by axis value.
  48986. // This array mirrors the browser Gamepad.axes array, such that
  48987. // the mesh corresponding to axis 0 is in this array index 0.
  48988. axisMeshNames: [
  48989. 'THUMBSTICK_X',
  48990. 'THUMBSTICK_Y',
  48991. 'TOUCHPAD_TOUCH_X',
  48992. 'TOUCHPAD_TOUCH_Y'
  48993. ],
  48994. // A mapping of the semantic name to button node name in the glTF model file,
  48995. // that should be transformed by button value.
  48996. buttonMeshNames: {
  48997. 'trigger': 'SELECT',
  48998. 'menu': 'MENU',
  48999. 'grip': 'GRASP',
  49000. 'thumbstick': 'THUMBSTICK_PRESS',
  49001. 'trackpad': 'TOUCHPAD_PRESS'
  49002. },
  49003. pointingPoseMeshName: 'POINTING_POSE'
  49004. },
  49005. bindMethods: function () {
  49006. this.onModelError = bind(this.onModelError, this);
  49007. this.onModelLoaded = bind(this.onModelLoaded, this);
  49008. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  49009. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  49010. this.onAxisMoved = bind(this.onAxisMoved, this);
  49011. },
  49012. init: function () {
  49013. var self = this;
  49014. var el = this.el;
  49015. this.onButtonChanged = bind(this.onButtonChanged, this);
  49016. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  49017. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  49018. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  49019. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  49020. this.onControllerConnected = function () { self.setModelVisibility(true); };
  49021. this.onControllerDisconnected = function () { self.setModelVisibility(false); };
  49022. this.controllerPresent = false;
  49023. this.lastControllerCheck = 0;
  49024. this.previousButtonValues = {};
  49025. this.bindMethods();
  49026. // Cache for submeshes that we have looked up by name.
  49027. this.loadedMeshInfo = {
  49028. buttonMeshes: null,
  49029. axisMeshes: null
  49030. };
  49031. // Pointing poses
  49032. this.rayOrigin = {
  49033. origin: new THREE.Vector3(),
  49034. direction: new THREE.Vector3(0, 0, -1),
  49035. createdFromMesh: false
  49036. };
  49037. // Stored on object to allow for mocking in tests
  49038. this.emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  49039. this.checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  49040. el.addEventListener('controllerconnected', this.onControllerConnected);
  49041. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  49042. },
  49043. addEventListeners: function () {
  49044. var el = this.el;
  49045. el.addEventListener('buttonchanged', this.onButtonChanged);
  49046. el.addEventListener('buttondown', this.onButtonDown);
  49047. el.addEventListener('buttonup', this.onButtonUp);
  49048. el.addEventListener('touchstart', this.onButtonTouchStart);
  49049. el.addEventListener('touchend', this.onButtonTouchEnd);
  49050. el.addEventListener('axismove', this.onAxisMoved);
  49051. el.addEventListener('model-error', this.onModelError);
  49052. el.addEventListener('model-loaded', this.onModelLoaded);
  49053. this.controllerEventsActive = true;
  49054. },
  49055. removeEventListeners: function () {
  49056. var el = this.el;
  49057. el.removeEventListener('buttonchanged', this.onButtonChanged);
  49058. el.removeEventListener('buttondown', this.onButtonDown);
  49059. el.removeEventListener('buttonup', this.onButtonUp);
  49060. el.removeEventListener('touchstart', this.onButtonTouchStart);
  49061. el.removeEventListener('touchend', this.onButtonTouchEnd);
  49062. el.removeEventListener('axismove', this.onAxisMoved);
  49063. el.removeEventListener('model-error', this.onModelError);
  49064. el.removeEventListener('model-loaded', this.onModelLoaded);
  49065. this.controllerEventsActive = false;
  49066. },
  49067. checkIfControllerPresent: function () {
  49068. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  49069. hand: this.data.hand,
  49070. index: this.data.pair
  49071. });
  49072. },
  49073. play: function () {
  49074. this.checkIfControllerPresent();
  49075. this.addControllersUpdateListener();
  49076. },
  49077. pause: function () {
  49078. this.removeEventListeners();
  49079. this.removeControllersUpdateListener();
  49080. },
  49081. updateControllerModel: function () {
  49082. // If we do not want to load a model, or, have already loaded the model, emit the controllermodelready event.
  49083. if (!this.data.model || this.rayOrigin.createdFromMesh) {
  49084. this.modelReady();
  49085. return;
  49086. }
  49087. var sourceUrl = this.createControllerModelUrl();
  49088. this.loadModel(sourceUrl);
  49089. },
  49090. /**
  49091. * Helper function that constructs a URL from the controller ID suffix, for future proofed
  49092. * art assets.
  49093. */
  49094. createControllerModelUrl: function (forceDefault) {
  49095. // Determine the device specific folder based on the ID suffix
  49096. var trackedControlsComponent = this.el.components['tracked-controls'];
  49097. var controller = trackedControlsComponent ? trackedControlsComponent.controller : null;
  49098. var device = 'default';
  49099. var hand = this.data.hand;
  49100. var filename;
  49101. if (controller) {
  49102. // Read hand directly from the controller, rather than this.data, as in the case that the controller
  49103. // is unhanded this.data will still have 'left' or 'right' (depending on what the user inserted in to the scene).
  49104. // In this case, we want to load the universal model, so need to get the '' from the controller.
  49105. hand = controller.hand;
  49106. if (!forceDefault) {
  49107. var match = controller.id.match(GAMEPAD_ID_PATTERN);
  49108. device = ((match && match[0]) || device);
  49109. }
  49110. }
  49111. // Hand
  49112. filename = MODEL_FILENAMES[hand] || MODEL_FILENAMES.default;
  49113. // Final url
  49114. return MODEL_BASE_URL + device + '/' + filename;
  49115. },
  49116. injectTrackedControls: function () {
  49117. var data = this.data;
  49118. this.el.setAttribute('tracked-controls', {
  49119. idPrefix: GAMEPAD_ID_PREFIX,
  49120. controller: data.pair,
  49121. hand: data.hand,
  49122. armModel: false
  49123. });
  49124. this.updateControllerModel();
  49125. },
  49126. addControllersUpdateListener: function () {
  49127. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  49128. },
  49129. removeControllersUpdateListener: function () {
  49130. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  49131. },
  49132. onControllersUpdate: function () {
  49133. this.checkIfControllerPresent();
  49134. },
  49135. onModelError: function (evt) {
  49136. var defaultUrl = this.createControllerModelUrl(true);
  49137. if (evt.detail.src !== defaultUrl) {
  49138. warn('Failed to load controller model for device, attempting to load default.');
  49139. this.loadModel(defaultUrl);
  49140. } else {
  49141. warn('Failed to load default controller model.');
  49142. }
  49143. },
  49144. loadModel: function (url) {
  49145. // The model is loaded by the gltf-model compoent when this attribute is initially set,
  49146. // removed and re-loaded if the given url changes.
  49147. this.el.setAttribute('gltf-model', 'url(' + url + ')');
  49148. },
  49149. onModelLoaded: function (evt) {
  49150. var rootNode = this.controllerModel = evt.detail.model;
  49151. var loadedMeshInfo = this.loadedMeshInfo;
  49152. var i;
  49153. var meshName;
  49154. var mesh;
  49155. var meshInfo;
  49156. debug('Processing model');
  49157. // Reset the caches
  49158. loadedMeshInfo.buttonMeshes = {};
  49159. loadedMeshInfo.axisMeshes = {};
  49160. // Cache our meshes so we aren't traversing the hierarchy per frame
  49161. if (rootNode) {
  49162. // Button Meshes
  49163. for (i = 0; i < this.mapping.buttons.length; i++) {
  49164. meshName = this.mapping.buttonMeshNames[this.mapping.buttons[i]];
  49165. if (!meshName) {
  49166. debug('Skipping unknown button at index: ' + i + ' with mapped name: ' + this.mapping.buttons[i]);
  49167. continue;
  49168. }
  49169. mesh = rootNode.getObjectByName(meshName);
  49170. if (!mesh) {
  49171. warn('Missing button mesh with name: ' + meshName);
  49172. continue;
  49173. }
  49174. meshInfo = {
  49175. index: i,
  49176. value: getImmediateChildByName(mesh, 'VALUE'),
  49177. pressed: getImmediateChildByName(mesh, 'PRESSED'),
  49178. unpressed: getImmediateChildByName(mesh, 'UNPRESSED')
  49179. };
  49180. if (meshInfo.value && meshInfo.pressed && meshInfo.unpressed) {
  49181. loadedMeshInfo.buttonMeshes[this.mapping.buttons[i]] = meshInfo;
  49182. } else {
  49183. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  49184. warn('Missing button submesh under mesh with name: ' + meshName +
  49185. '(VALUE: ' + !!meshInfo.value +
  49186. ', PRESSED: ' + !!meshInfo.pressed +
  49187. ', UNPRESSED:' + !!meshInfo.unpressed +
  49188. ')');
  49189. }
  49190. }
  49191. // Axis Meshes
  49192. for (i = 0; i < this.mapping.axisMeshNames.length; i++) {
  49193. meshName = this.mapping.axisMeshNames[i];
  49194. if (!meshName) {
  49195. debug('Skipping unknown axis at index: ' + i);
  49196. continue;
  49197. }
  49198. mesh = rootNode.getObjectByName(meshName);
  49199. if (!mesh) {
  49200. warn('Missing axis mesh with name: ' + meshName);
  49201. continue;
  49202. }
  49203. meshInfo = {
  49204. index: i,
  49205. value: getImmediateChildByName(mesh, 'VALUE'),
  49206. min: getImmediateChildByName(mesh, 'MIN'),
  49207. max: getImmediateChildByName(mesh, 'MAX')
  49208. };
  49209. if (meshInfo.value && meshInfo.min && meshInfo.max) {
  49210. loadedMeshInfo.axisMeshes[i] = meshInfo;
  49211. } else {
  49212. // If we didn't find the mesh, it simply means this axis won't have transforms applied as mapped axis values change.
  49213. warn('Missing axis submesh under mesh with name: ' + meshName +
  49214. '(VALUE: ' + !!meshInfo.value +
  49215. ', MIN: ' + !!meshInfo.min +
  49216. ', MAX:' + !!meshInfo.max +
  49217. ')');
  49218. }
  49219. }
  49220. this.calculateRayOriginFromMesh(rootNode);
  49221. // Determine if the model has to be visible or not.
  49222. this.setModelVisibility();
  49223. }
  49224. debug('Model load complete.');
  49225. // Look through only immediate children. This will return null if no mesh exists with the given name.
  49226. function getImmediateChildByName (object3d, value) {
  49227. for (var i = 0, l = object3d.children.length; i < l; i++) {
  49228. var obj = object3d.children[i];
  49229. if (obj && obj['name'] === value) {
  49230. return obj;
  49231. }
  49232. }
  49233. return undefined;
  49234. }
  49235. },
  49236. calculateRayOriginFromMesh: (function () {
  49237. var quaternion = new THREE.Quaternion();
  49238. return function (rootNode) {
  49239. var mesh;
  49240. // Calculate the pointer pose (used for rays), by applying the world transform of th POINTER_POSE node
  49241. // in the glTF (assumes that root node is at world origin)
  49242. this.rayOrigin.origin.set(0, 0, 0);
  49243. this.rayOrigin.direction.set(0, 0, -1);
  49244. this.rayOrigin.createdFromMesh = true;
  49245. // Try to read Pointing pose from the source model
  49246. mesh = rootNode.getObjectByName(this.mapping.pointingPoseMeshName);
  49247. if (mesh) {
  49248. var parent = rootNode.parent;
  49249. // We need to read pose transforms accumulated from the root of the glTF, not the scene.
  49250. if (parent) {
  49251. rootNode.parent = null;
  49252. rootNode.updateMatrixWorld(true);
  49253. rootNode.parent = parent;
  49254. }
  49255. mesh.getWorldPosition(this.rayOrigin.origin);
  49256. mesh.getWorldQuaternion(quaternion);
  49257. this.rayOrigin.direction.applyQuaternion(quaternion);
  49258. // Recalculate the world matrices now that the rootNode is re-attached to the parent.
  49259. if (parent) {
  49260. rootNode.updateMatrixWorld(true);
  49261. }
  49262. } else {
  49263. debug('Mesh does not contain pointing origin data, defaulting to none.');
  49264. }
  49265. // Emit event stating that our pointing ray is now accurate.
  49266. this.modelReady();
  49267. };
  49268. })(),
  49269. lerpAxisTransform: (function () {
  49270. var quaternion = new THREE.Quaternion();
  49271. return function (axis, axisValue) {
  49272. var axisMeshInfo = this.loadedMeshInfo.axisMeshes[axis];
  49273. if (!axisMeshInfo) return;
  49274. var min = axisMeshInfo.min;
  49275. var max = axisMeshInfo.max;
  49276. var target = axisMeshInfo.value;
  49277. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  49278. var lerpValue = axisValue * 0.5 + 0.5;
  49279. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, lerpValue));
  49280. target.position.lerpVectors(min.position, max.position, lerpValue);
  49281. };
  49282. })(),
  49283. lerpButtonTransform: (function () {
  49284. var quaternion = new THREE.Quaternion();
  49285. return function (buttonName, buttonValue) {
  49286. var buttonMeshInfo = this.loadedMeshInfo.buttonMeshes[buttonName];
  49287. if (!buttonMeshInfo) return;
  49288. var min = buttonMeshInfo.unpressed;
  49289. var max = buttonMeshInfo.pressed;
  49290. var target = buttonMeshInfo.value;
  49291. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, buttonValue));
  49292. target.position.lerpVectors(min.position, max.position, buttonValue);
  49293. };
  49294. })(),
  49295. modelReady: function () {
  49296. this.el.emit('controllermodelready', {
  49297. name: 'windows-motion-controls',
  49298. model: this.data.model,
  49299. rayOrigin: this.rayOrigin
  49300. });
  49301. },
  49302. onButtonChanged: function (evt) {
  49303. var buttonName = this.mapping.buttons[evt.detail.id];
  49304. if (buttonName) {
  49305. // Update the button mesh transform
  49306. if (this.loadedMeshInfo && this.loadedMeshInfo.buttonMeshes) {
  49307. this.lerpButtonTransform(buttonName, evt.detail.state.value);
  49308. }
  49309. // Only emit events for buttons that we know how to map from index to name
  49310. this.el.emit(buttonName + 'changed', evt.detail.state);
  49311. }
  49312. },
  49313. onAxisMoved: function (evt) {
  49314. var numAxes = this.mapping.axisMeshNames.length;
  49315. // Only attempt to update meshes if we have valid data.
  49316. if (this.loadedMeshInfo && this.loadedMeshInfo.axisMeshes) {
  49317. for (var axis = 0; axis < numAxes; axis++) {
  49318. // Update the button mesh transform
  49319. this.lerpAxisTransform(axis, evt.detail.axis[axis] || 0.0);
  49320. }
  49321. }
  49322. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  49323. },
  49324. setModelVisibility: function (visible) {
  49325. var model = this.el.getObject3D('mesh');
  49326. visible = visible !== undefined ? visible : this.modelVisible;
  49327. this.modelVisible = visible;
  49328. if (!model) { return; }
  49329. model.visible = visible;
  49330. }
  49331. });
  49332. },{"../constants":97,"../core/component":105,"../utils/":178,"../utils/bind":172,"../utils/tracked-controls":185}],97:[function(_dereq_,module,exports){
  49333. module.exports = {
  49334. AFRAME_INJECTED: 'aframe-injected',
  49335. DEFAULT_CAMERA_HEIGHT: 1.6,
  49336. DEFAULT_HANDEDNESS: 'right',
  49337. keyboardevent: _dereq_('./keyboardevent')
  49338. };
  49339. },{"./keyboardevent":98}],98:[function(_dereq_,module,exports){
  49340. module.exports = {
  49341. // Tiny KeyboardEvent.code polyfill.
  49342. KEYCODE_TO_CODE: {
  49343. '38': 'ArrowUp',
  49344. '37': 'ArrowLeft',
  49345. '40': 'ArrowDown',
  49346. '39': 'ArrowRight',
  49347. '87': 'KeyW',
  49348. '65': 'KeyA',
  49349. '83': 'KeyS',
  49350. '68': 'KeyD'
  49351. }
  49352. };
  49353. },{}],99:[function(_dereq_,module,exports){
  49354. var ANode = _dereq_('./a-node');
  49355. var bind = _dereq_('../utils/bind');
  49356. var debug = _dereq_('../utils/debug');
  49357. var registerElement = _dereq_('./a-register-element').registerElement;
  49358. var THREE = _dereq_('../lib/three');
  49359. var fileLoader = new THREE.FileLoader();
  49360. var warn = debug('core:a-assets:warn');
  49361. /**
  49362. * Asset management system. Handles blocking on asset loading.
  49363. */
  49364. module.exports = registerElement('a-assets', {
  49365. prototype: Object.create(ANode.prototype, {
  49366. createdCallback: {
  49367. value: function () {
  49368. this.isAssets = true;
  49369. this.fileLoader = fileLoader;
  49370. this.timeout = null;
  49371. }
  49372. },
  49373. attachedCallback: {
  49374. value: function () {
  49375. var self = this;
  49376. var i;
  49377. var loaded = [];
  49378. var mediaEl;
  49379. var mediaEls;
  49380. var imgEl;
  49381. var imgEls;
  49382. var timeout;
  49383. if (!this.parentNode.isScene) {
  49384. throw new Error('<a-assets> must be a child of a <a-scene>.');
  49385. }
  49386. // Wait for <img>s.
  49387. imgEls = this.querySelectorAll('img');
  49388. for (i = 0; i < imgEls.length; i++) {
  49389. imgEl = fixUpMediaElement(imgEls[i]);
  49390. loaded.push(new Promise(function (resolve, reject) {
  49391. // Set in cache because we won't be needing to call three.js loader if we have.
  49392. // a loaded media element.
  49393. THREE.Cache.files[imgEls[i].getAttribute('src')] = imgEl;
  49394. imgEl.onload = resolve;
  49395. imgEl.onerror = reject;
  49396. }));
  49397. }
  49398. // Wait for <audio>s and <video>s.
  49399. mediaEls = this.querySelectorAll('audio, video');
  49400. for (i = 0; i < mediaEls.length; i++) {
  49401. mediaEl = fixUpMediaElement(mediaEls[i]);
  49402. if (!mediaEl.src && !mediaEl.srcObject) {
  49403. warn('Audio/video asset has neither `src` nor `srcObject` attributes.');
  49404. }
  49405. loaded.push(mediaElementLoaded(mediaEl));
  49406. }
  49407. // Trigger loaded for scene to start rendering.
  49408. Promise.all(loaded).then(bind(this.load, this));
  49409. // Timeout to start loading anyways.
  49410. timeout = parseInt(this.getAttribute('timeout'), 10) || 3000;
  49411. this.timeout = setTimeout(function () {
  49412. if (self.hasLoaded) { return; }
  49413. warn('Asset loading timed out in ', timeout, 'ms');
  49414. self.emit('timeout');
  49415. self.load();
  49416. }, timeout);
  49417. }
  49418. },
  49419. detachedCallback: {
  49420. value: function () {
  49421. if (this.timeout) { clearTimeout(this.timeout); }
  49422. }
  49423. },
  49424. load: {
  49425. value: function () {
  49426. ANode.prototype.load.call(this, null, function waitOnFilter (el) {
  49427. return el.isAssetItem && el.hasAttribute('src');
  49428. });
  49429. }
  49430. }
  49431. })
  49432. });
  49433. /**
  49434. * Preload using XHRLoader for any type of asset.
  49435. */
  49436. registerElement('a-asset-item', {
  49437. prototype: Object.create(ANode.prototype, {
  49438. createdCallback: {
  49439. value: function () {
  49440. this.data = null;
  49441. this.isAssetItem = true;
  49442. }
  49443. },
  49444. attachedCallback: {
  49445. value: function () {
  49446. var self = this;
  49447. var src = this.getAttribute('src');
  49448. fileLoader.setResponseType(
  49449. this.getAttribute('response-type') || inferResponseType(src));
  49450. fileLoader.load(src, function handleOnLoad (response) {
  49451. self.data = response;
  49452. /*
  49453. Workaround for a Chrome bug. If another XHR is sent to the same url before the
  49454. previous one closes, the second request never finishes.
  49455. setTimeout finishes the first request and lets the logic triggered by load open
  49456. subsequent requests.
  49457. setTimeout can be removed once the fix for the bug below ships:
  49458. 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
  49459. */
  49460. setTimeout(function load () { ANode.prototype.load.call(self); });
  49461. }, function handleOnProgress (xhr) {
  49462. self.emit('progress', {
  49463. loadedBytes: xhr.loaded,
  49464. totalBytes: xhr.total,
  49465. xhr: xhr
  49466. });
  49467. }, function handleOnError (xhr) {
  49468. self.emit('error', {xhr: xhr});
  49469. });
  49470. }
  49471. }
  49472. })
  49473. });
  49474. /**
  49475. * Create a Promise that resolves once the media element has finished buffering.
  49476. *
  49477. * @param {Element} el - HTMLMediaElement.
  49478. * @returns {Promise}
  49479. */
  49480. function mediaElementLoaded (el) {
  49481. if (!el.hasAttribute('autoplay') && el.getAttribute('preload') !== 'auto') {
  49482. return;
  49483. }
  49484. // If media specifies autoplay or preload, wait until media is completely buffered.
  49485. return new Promise(function (resolve, reject) {
  49486. if (el.readyState === 4) { return resolve(); } // Already loaded.
  49487. if (el.error) { return reject(); } // Error.
  49488. el.addEventListener('loadeddata', checkProgress, false);
  49489. el.addEventListener('progress', checkProgress, false);
  49490. el.addEventListener('error', reject, false);
  49491. function checkProgress () {
  49492. // Add up the seconds buffered.
  49493. var secondsBuffered = 0;
  49494. for (var i = 0; i < el.buffered.length; i++) {
  49495. secondsBuffered += el.buffered.end(i) - el.buffered.start(i);
  49496. }
  49497. // Compare seconds buffered to media duration.
  49498. if (secondsBuffered >= el.duration) {
  49499. // Set in cache because we won't be needing to call three.js loader if we have.
  49500. // a loaded media element.
  49501. // Store video elements only. three.js loader is used for audio elements.
  49502. // See assetParse too.
  49503. if (el.tagName === 'VIDEO') {
  49504. THREE.Cache.files[el.getAttribute('src')] = el;
  49505. }
  49506. resolve();
  49507. }
  49508. }
  49509. });
  49510. }
  49511. /**
  49512. * Automatically add attributes to media elements where convenient.
  49513. * crossorigin, playsinline.
  49514. */
  49515. function fixUpMediaElement (mediaEl) {
  49516. // Cross-origin.
  49517. var newMediaEl = setCrossOrigin(mediaEl);
  49518. // Plays inline for mobile.
  49519. if (newMediaEl.tagName && newMediaEl.tagName.toLowerCase() === 'video') {
  49520. newMediaEl.setAttribute('playsinline', '');
  49521. newMediaEl.setAttribute('webkit-playsinline', '');
  49522. }
  49523. if (newMediaEl !== mediaEl) {
  49524. mediaEl.parentNode.appendChild(newMediaEl);
  49525. mediaEl.parentNode.removeChild(mediaEl);
  49526. }
  49527. return newMediaEl;
  49528. }
  49529. /**
  49530. * Automatically set `crossorigin` if not defined on the media element.
  49531. * If it is not defined, we must create and re-append a new media element <img> and
  49532. * have the browser re-request it with `crossorigin` set.
  49533. *
  49534. * @param {Element} Media element (e.g., <img>, <audio>, <video>).
  49535. * @returns {Element} Media element to be used to listen to for loaded events.
  49536. */
  49537. function setCrossOrigin (mediaEl) {
  49538. var newMediaEl;
  49539. var src;
  49540. // Already has crossorigin set.
  49541. if (mediaEl.hasAttribute('crossorigin')) { return mediaEl; }
  49542. src = mediaEl.getAttribute('src');
  49543. if (src !== null) {
  49544. // Does not have protocol.
  49545. if (src.indexOf('://') === -1) { return mediaEl; }
  49546. // Determine if cross origin is actually needed.
  49547. if (extractDomain(src) === window.location.host) { return mediaEl; }
  49548. }
  49549. warn('Cross-origin element (e.g., <img>) was requested without `crossorigin` set. ' +
  49550. 'A-Frame will re-request the asset with `crossorigin` attribute set. ' +
  49551. 'Please set `crossorigin` on the element (e.g., <img crossorigin="anonymous">)', src);
  49552. mediaEl.crossOrigin = 'anonymous';
  49553. newMediaEl = mediaEl.cloneNode(true);
  49554. return newMediaEl;
  49555. }
  49556. /**
  49557. * Extract domain out of URL.
  49558. *
  49559. * @param {string} url
  49560. * @returns {string}
  49561. */
  49562. function extractDomain (url) {
  49563. // Find and remove protocol (e.g., http, ftp, etc.) to get domain.
  49564. var domain = url.indexOf('://') > -1 ? url.split('/')[2] : url.split('/')[0];
  49565. // Find and remove port number.
  49566. return domain.substring(0, domain.indexOf(':'));
  49567. }
  49568. /**
  49569. * Infer response-type attribute from src.
  49570. * Default is text(default XMLHttpRequest.responseType)
  49571. * but we use arraybuffer for .gltf and .glb files
  49572. * because of THREE.GLTFLoader specification.
  49573. *
  49574. * @param {string} src
  49575. * @returns {string}
  49576. */
  49577. function inferResponseType (src) {
  49578. var dotLastIndex = src.lastIndexOf('.');
  49579. if (dotLastIndex >= 0) {
  49580. var extension = src.slice(dotLastIndex, src.length);
  49581. if (extension === '.gltf' || extension === '.glb') {
  49582. return 'arraybuffer';
  49583. }
  49584. }
  49585. return 'text';
  49586. }
  49587. module.exports.inferResponseType = inferResponseType;
  49588. },{"../lib/three":154,"../utils/bind":172,"../utils/debug":174,"./a-node":103,"./a-register-element":104}],100:[function(_dereq_,module,exports){
  49589. var debug = _dereq_('../utils/debug');
  49590. var registerElement = _dereq_('./a-register-element').registerElement;
  49591. var warn = debug('core:cubemap:warn');
  49592. /**
  49593. * Cubemap element that handles validation and exposes list of URLs.
  49594. * Does not listen to updates.
  49595. */
  49596. module.exports = registerElement('a-cubemap', {
  49597. prototype: Object.create(window.HTMLElement.prototype, {
  49598. /**
  49599. * Calculates this.srcs.
  49600. */
  49601. attachedCallback: {
  49602. value: function () {
  49603. this.srcs = this.validate();
  49604. },
  49605. writable: window.debug
  49606. },
  49607. /**
  49608. * Checks for exactly six elements with [src].
  49609. * Does not check explicitly for <img>s in case user does not want
  49610. * prefetching.
  49611. *
  49612. * @returns {Array|null} - six URLs if valid, else null.
  49613. */
  49614. validate: {
  49615. value: function () {
  49616. var elements = this.querySelectorAll('[src]');
  49617. var i;
  49618. var srcs = [];
  49619. if (elements.length === 6) {
  49620. for (i = 0; i < elements.length; i++) {
  49621. srcs.push(elements[i].getAttribute('src'));
  49622. }
  49623. return srcs;
  49624. }
  49625. // Else if there are not six elements, throw a warning.
  49626. warn(
  49627. '<a-cubemap> did not contain exactly six elements each with a ' +
  49628. '`src` attribute.');
  49629. },
  49630. writable: window.debug
  49631. }
  49632. })
  49633. });
  49634. },{"../utils/debug":174,"./a-register-element":104}],101:[function(_dereq_,module,exports){
  49635. var ANode = _dereq_('./a-node');
  49636. var COMPONENTS = _dereq_('./component').components;
  49637. var registerElement = _dereq_('./a-register-element').registerElement;
  49638. var THREE = _dereq_('../lib/three');
  49639. var utils = _dereq_('../utils/');
  49640. var AEntity;
  49641. var debug = utils.debug('core:a-entity:debug');
  49642. var warn = utils.debug('core:a-entity:warn');
  49643. var MULTIPLE_COMPONENT_DELIMITER = '__';
  49644. var OBJECT3D_COMPONENTS = ['position', 'rotation', 'scale', 'visible'];
  49645. var ONCE = {once: true};
  49646. /**
  49647. * Entity is a container object that components are plugged into to comprise everything in
  49648. * the scene. In A-Frame, they inherently have position, rotation, and scale.
  49649. *
  49650. * To be able to take components, the scene element inherits from the entity definition.
  49651. *
  49652. * @member {object} components - entity's currently initialized components.
  49653. * @member {object} object3D - three.js object.
  49654. * @member {array} states
  49655. * @member {boolean} isPlaying - false if dynamic behavior of the entity is paused.
  49656. */
  49657. var proto = Object.create(ANode.prototype, {
  49658. createdCallback: {
  49659. value: function () {
  49660. this.components = {};
  49661. // To avoid double initializations and infinite loops.
  49662. this.initializingComponents = {};
  49663. this.componentsToUpdate = {};
  49664. this.isEntity = true;
  49665. this.isPlaying = false;
  49666. this.object3D = new THREE.Group();
  49667. this.object3D.el = this;
  49668. this.object3DMap = {};
  49669. this.parentEl = null;
  49670. this.rotationObj = {};
  49671. this.states = [];
  49672. }
  49673. },
  49674. /**
  49675. * Handle changes coming from the browser DOM inspector.
  49676. */
  49677. attributeChangedCallback: {
  49678. value: function (attr, oldVal, newVal) {
  49679. var component = this.components[attr];
  49680. // If the empty string is passed by the component initialization
  49681. // logic we ignore the component update.
  49682. if (component && component.justInitialized && newVal === '') {
  49683. delete component.justInitialized;
  49684. return;
  49685. }
  49686. // When a component is removed after calling el.removeAttribute('material')
  49687. if (!component && newVal === null) { return; }
  49688. this.setEntityAttribute(attr, oldVal, newVal);
  49689. }
  49690. },
  49691. /**
  49692. * Add to parent, load, play.
  49693. */
  49694. attachedCallback: {
  49695. value: function () {
  49696. var assetsEl; // Asset management system element.
  49697. var sceneEl = this.sceneEl;
  49698. var self = this; // Component.
  49699. this.addToParent();
  49700. // Don't .load() scene on attachedCallback.
  49701. if (this.isScene) { return; }
  49702. // Gracefully not error when outside of <a-scene> (e.g., tests).
  49703. if (!sceneEl) {
  49704. this.load();
  49705. return;
  49706. }
  49707. // Wait for asset management system to finish before loading.
  49708. assetsEl = sceneEl.querySelector('a-assets');
  49709. if (assetsEl && !assetsEl.hasLoaded) {
  49710. assetsEl.addEventListener('loaded', function () { self.load(); });
  49711. return;
  49712. }
  49713. this.load();
  49714. }
  49715. },
  49716. /**
  49717. * Tell parent to remove this element's object3D from its object3D.
  49718. * Do not call on scene element because that will cause a call to document.body.remove().
  49719. */
  49720. detachedCallback: {
  49721. value: function () {
  49722. var componentName;
  49723. if (!this.parentEl) { return; }
  49724. // Remove components.
  49725. for (componentName in this.components) { this.removeComponent(componentName); }
  49726. if (this.isScene) { return; }
  49727. this.removeFromParent();
  49728. ANode.prototype.detachedCallback.call(this);
  49729. // Remove cyclic reference.
  49730. this.object3D.el = null;
  49731. }
  49732. },
  49733. getObject3D: {
  49734. value: function (type) {
  49735. return this.object3DMap[type];
  49736. }
  49737. },
  49738. /**
  49739. * Set a THREE.Object3D into the map.
  49740. *
  49741. * @param {string} type - Developer-set name of the type of object, will be unique per type.
  49742. * @param {object} obj - A THREE.Object3D.
  49743. */
  49744. setObject3D: {
  49745. value: function (type, obj) {
  49746. var oldObj;
  49747. var self = this;
  49748. if (!(obj instanceof THREE.Object3D)) {
  49749. throw new Error(
  49750. '`Entity.setObject3D` was called with an object that was not an instance of ' +
  49751. 'THREE.Object3D.'
  49752. );
  49753. }
  49754. // Remove existing object of the type.
  49755. oldObj = this.getObject3D(type);
  49756. if (oldObj) { this.object3D.remove(oldObj); }
  49757. // Set references to A-Frame entity.
  49758. obj.el = this;
  49759. if (obj.children.length) {
  49760. obj.traverse(function bindEl (child) {
  49761. child.el = self;
  49762. });
  49763. }
  49764. // Add.
  49765. this.object3D.add(obj);
  49766. this.object3DMap[type] = obj;
  49767. this.emit('object3dset', {object: obj, type: type});
  49768. }
  49769. },
  49770. /**
  49771. * Remove object from scene and entity object3D map.
  49772. */
  49773. removeObject3D: {
  49774. value: function (type) {
  49775. var obj = this.getObject3D(type);
  49776. if (!obj) {
  49777. warn('Tried to remove `Object3D` of type:', type, 'which was not defined.');
  49778. return;
  49779. }
  49780. this.object3D.remove(obj);
  49781. delete this.object3DMap[type];
  49782. this.emit('object3dremove', {type: type});
  49783. }
  49784. },
  49785. /**
  49786. * Gets or creates an object3D of a given type.
  49787. *
  49788. * @param {string} type - Type of the object3D.
  49789. * @param {string} Constructor - Constructor to use to create the object3D if needed.
  49790. * @returns {object}
  49791. */
  49792. getOrCreateObject3D: {
  49793. value: function (type, Constructor) {
  49794. var object3D = this.getObject3D(type);
  49795. if (!object3D && Constructor) {
  49796. object3D = new Constructor();
  49797. this.setObject3D(type, object3D);
  49798. }
  49799. warn('`getOrCreateObject3D` has been deprecated. Use `setObject3D()` ' +
  49800. 'and `object3dset` event instead.');
  49801. return object3D;
  49802. }
  49803. },
  49804. /**
  49805. * Add child entity.
  49806. *
  49807. * @param {Element} el - Child entity.
  49808. */
  49809. add: {
  49810. value: function (el) {
  49811. if (!el.object3D) {
  49812. throw new Error("Trying to add an element that doesn't have an `object3D`");
  49813. }
  49814. this.object3D.add(el.object3D);
  49815. this.emit('child-attached', {el: el});
  49816. }
  49817. },
  49818. /**
  49819. * Tell parentNode to add this entity to itself.
  49820. */
  49821. addToParent: {
  49822. value: function () {
  49823. var parentNode = this.parentEl = this.parentNode;
  49824. // `!parentNode` check primarily for unit tests.
  49825. if (!parentNode || !parentNode.add || this.attachedToParent) { return; }
  49826. parentNode.add(this);
  49827. this.attachedToParent = true; // To prevent multiple attachments to same parent.
  49828. }
  49829. },
  49830. /**
  49831. * Tell parentNode to remove this entity from itself.
  49832. */
  49833. removeFromParent: {
  49834. value: function () {
  49835. var parentEl = this.parentEl;
  49836. this.parentEl.remove(this);
  49837. this.attachedToParent = false;
  49838. this.parentEl = null;
  49839. parentEl.emit('child-detached', {el: this});
  49840. }
  49841. },
  49842. load: {
  49843. value: function () {
  49844. var self = this;
  49845. if (this.hasLoaded || !this.parentEl) { return; }
  49846. ANode.prototype.load.call(this, function entityLoadCallback () {
  49847. // Check if entity was detached while it was waiting to load.
  49848. if (!self.parentEl) { return; }
  49849. self.updateComponents();
  49850. if (self.isScene || self.parentEl.isPlaying) { self.play(); }
  49851. });
  49852. },
  49853. writable: window.debug
  49854. },
  49855. /**
  49856. * Remove child entity.
  49857. *
  49858. * @param {Element} el - Child entity.
  49859. */
  49860. remove: {
  49861. value: function (el) {
  49862. this.object3D.remove(el.object3D);
  49863. }
  49864. },
  49865. /**
  49866. * @returns {array} Direct children that are entities.
  49867. */
  49868. getChildEntities: {
  49869. value: function () {
  49870. var children = this.children;
  49871. var childEntities = [];
  49872. for (var i = 0; i < children.length; i++) {
  49873. var child = children[i];
  49874. if (child instanceof AEntity) {
  49875. childEntities.push(child);
  49876. }
  49877. }
  49878. return childEntities;
  49879. }
  49880. },
  49881. /**
  49882. * Initialize component.
  49883. *
  49884. * @param {string} attrName - Attribute name asociated to the component.
  49885. * @param {object} data - Component data
  49886. * @param {boolean} isDependency - True if the component is a dependency.
  49887. */
  49888. initComponent: {
  49889. value: function (attrName, data, isDependency) {
  49890. var component;
  49891. var componentId;
  49892. var componentInfo;
  49893. var componentName;
  49894. var isComponentDefined;
  49895. componentInfo = utils.split(attrName, MULTIPLE_COMPONENT_DELIMITER);
  49896. componentName = componentInfo[0];
  49897. componentId = componentInfo.length > 2
  49898. ? componentInfo.slice(1).join('__')
  49899. : componentInfo[1];
  49900. // Not a registered component.
  49901. if (!COMPONENTS[componentName]) { return; }
  49902. // Component is not a dependency and is undefined.
  49903. // If a component is a dependency, then it is okay to have no data.
  49904. isComponentDefined = checkComponentDefined(this, attrName) ||
  49905. data !== undefined;
  49906. if (!isComponentDefined && !isDependency) { return; }
  49907. // Component already initialized.
  49908. if (attrName in this.components) { return; }
  49909. // Initialize dependencies first
  49910. this.initComponentDependencies(componentName);
  49911. // If component name has an id we check component type multiplic
  49912. if (componentId && !COMPONENTS[componentName].multiple) {
  49913. throw new Error('Trying to initialize multiple ' +
  49914. 'components of type `' + componentName +
  49915. '`. There can only be one component of this type per entity.');
  49916. }
  49917. component = new COMPONENTS[componentName].Component(this, data, componentId);
  49918. if (this.isPlaying) { component.play(); }
  49919. // Components are reflected in the DOM as attributes but the state is not shown
  49920. // hence we set the attribute to empty string.
  49921. // The flag justInitialized is for attributeChangedCallback to not overwrite
  49922. // the component with the empty string.
  49923. if (!this.hasAttribute(attrName)) {
  49924. component.justInitialized = true;
  49925. window.HTMLElement.prototype.setAttribute.call(this, attrName, '');
  49926. }
  49927. debug('Component initialized: %s', attrName);
  49928. },
  49929. writable: window.debug
  49930. },
  49931. /**
  49932. * Initialize dependencies of a component.
  49933. *
  49934. * @param {string} name - Root component name.
  49935. */
  49936. initComponentDependencies: {
  49937. value: function (name) {
  49938. var self = this;
  49939. var component = COMPONENTS[name];
  49940. var dependencies;
  49941. var i;
  49942. // Not a component.
  49943. if (!component) { return; }
  49944. // No dependencies.
  49945. dependencies = COMPONENTS[name].dependencies;
  49946. if (!dependencies) { return; }
  49947. // Initialize dependencies.
  49948. for (i = 0; i < dependencies.length; i++) {
  49949. // Call getAttribute to initialize the data from the DOM.
  49950. self.initComponent(
  49951. dependencies[i],
  49952. window.HTMLElement.prototype.getAttribute.call(self, dependencies[i]) || undefined,
  49953. true
  49954. );
  49955. }
  49956. }
  49957. },
  49958. removeComponent: {
  49959. value: function (name) {
  49960. var component;
  49961. component = this.components[name];
  49962. if (!component) { return; }
  49963. // Wait for component to initialize.
  49964. if (!component.initialized) {
  49965. this.addEventListener('componentinitialized', function tryRemoveLater (evt) {
  49966. if (evt.detail.name !== name) { return; }
  49967. this.removeComponent(name);
  49968. this.removeEventListener('componentinitialized', tryRemoveLater);
  49969. });
  49970. return;
  49971. }
  49972. component.pause();
  49973. component.remove();
  49974. delete this.components[name];
  49975. this.emit('componentremoved', component.evtDetail);
  49976. },
  49977. writable: window.debug
  49978. },
  49979. /**
  49980. * Initialize or update all components.
  49981. * Build data using initial components, defined attributes, mixins, and defaults.
  49982. * Update default components before the rest.
  49983. *
  49984. * @member {function} getExtraComponents - Can be implemented to include component data
  49985. * from other sources (e.g., implemented by primitives).
  49986. */
  49987. updateComponents: {
  49988. value: function () {
  49989. var data;
  49990. var extraComponents;
  49991. var i;
  49992. var name;
  49993. var componentsToUpdate = this.componentsToUpdate;
  49994. if (!this.hasLoaded) { return; }
  49995. // Gather mixin-defined components.
  49996. for (i = 0; i < this.mixinEls.length; i++) {
  49997. for (name in this.mixinEls[i].componentCache) {
  49998. if (isComponent(name)) { componentsToUpdate[name] = true; }
  49999. }
  50000. }
  50001. // Gather from extra initial component data if defined (e.g., primitives).
  50002. if (this.getExtraComponents) {
  50003. extraComponents = this.getExtraComponents();
  50004. for (name in extraComponents) {
  50005. if (isComponent(name)) { componentsToUpdate[name] = true; }
  50006. }
  50007. }
  50008. // Gather entity-defined components.
  50009. for (i = 0; i < this.attributes.length; ++i) {
  50010. name = this.attributes[i].name;
  50011. if (OBJECT3D_COMPONENTS.indexOf(name) !== -1) { continue; }
  50012. if (isComponent(name)) { componentsToUpdate[name] = true; }
  50013. }
  50014. // object3D components first (position, rotation, scale, visible).
  50015. for (i = 0; i < OBJECT3D_COMPONENTS.length; i++) {
  50016. name = OBJECT3D_COMPONENTS[i];
  50017. if (!this.hasAttribute(name)) { continue; }
  50018. this.updateComponent(name, this.getDOMAttribute(name));
  50019. }
  50020. // Initialize or update rest of components.
  50021. for (name in componentsToUpdate) {
  50022. data = mergeComponentData(this.getDOMAttribute(name),
  50023. extraComponents && extraComponents[name]);
  50024. this.updateComponent(name, data);
  50025. delete componentsToUpdate[name];
  50026. }
  50027. },
  50028. writable: window.debug
  50029. },
  50030. /**
  50031. * Initialize, update, or remove a single component.
  50032. *
  50033. * When initializing, we set the component on `this.components`.
  50034. *
  50035. * @param {string} attr - Component name.
  50036. * @param {object} attrValue - Value of the DOM attribute.
  50037. * @param {boolean} clobber - If new attrValue completely replaces previous properties.
  50038. */
  50039. updateComponent: {
  50040. value: function (attr, attrValue, clobber) {
  50041. var component = this.components[attr];
  50042. if (component) {
  50043. // Remove component.
  50044. if (attrValue === null && !checkComponentDefined(this, attr)) {
  50045. this.removeComponent(attr);
  50046. return;
  50047. }
  50048. // Component already initialized. Update component.
  50049. component.updateProperties(attrValue, clobber);
  50050. return;
  50051. }
  50052. // Component not yet initialized. Initialize component.
  50053. this.initComponent(attr, attrValue, false);
  50054. }
  50055. },
  50056. /**
  50057. * If `attr` is a component name, detach the component from the entity.
  50058. *
  50059. * If `propertyName` is given, reset the component property value to its default.
  50060. *
  50061. * @param {string} attr - Attribute name, which could also be a component name.
  50062. * @param {string} propertyName - Component prop name, if resetting an individual prop.
  50063. */
  50064. removeAttribute: {
  50065. value: function (attr, propertyName) {
  50066. var component = this.components[attr];
  50067. // Remove component.
  50068. if (component && propertyName === undefined) {
  50069. this.removeComponent(attr);
  50070. }
  50071. // Reset component property value.
  50072. if (component && propertyName !== undefined) {
  50073. component.resetProperty(propertyName);
  50074. return;
  50075. }
  50076. // Remove mixins.
  50077. if (attr === 'mixin') {
  50078. this.mixinUpdate('');
  50079. }
  50080. window.HTMLElement.prototype.removeAttribute.call(this, attr);
  50081. }
  50082. },
  50083. /**
  50084. * Start dynamic behavior associated with entity such as dynamic components and animations.
  50085. * Tell all children entities to also play.
  50086. */
  50087. play: {
  50088. value: function () {
  50089. var entities;
  50090. var i;
  50091. var key;
  50092. // Already playing.
  50093. if (this.isPlaying || !this.hasLoaded) { return; }
  50094. this.isPlaying = true;
  50095. // Wake up all components.
  50096. for (key in this.components) { this.components[key].play(); }
  50097. // Tell all child entities to play.
  50098. entities = this.getChildEntities();
  50099. for (i = 0; i < entities.length; i++) { entities[i].play(); }
  50100. this.emit('play');
  50101. },
  50102. writable: true
  50103. },
  50104. /**
  50105. * Pause dynamic behavior associated with entity such as dynamic components and animations.
  50106. * Tell all children entities to also pause.
  50107. */
  50108. pause: {
  50109. value: function () {
  50110. var entities;
  50111. var i;
  50112. var key;
  50113. if (!this.isPlaying) { return; }
  50114. this.isPlaying = false;
  50115. // Sleep all components.
  50116. for (key in this.components) { this.components[key].pause(); }
  50117. // Tell all child entities to pause.
  50118. entities = this.getChildEntities();
  50119. for (i = 0; i < entities.length; i++) { entities[i].pause(); }
  50120. this.emit('pause');
  50121. },
  50122. writable: true
  50123. },
  50124. /**
  50125. * Deals with updates on entity-specific attributes (i.e., components and mixins).
  50126. *
  50127. * @param {string} attr
  50128. * @param {string} oldVal
  50129. * @param {string|object} newVal
  50130. */
  50131. setEntityAttribute: {
  50132. value: function (attr, oldVal, newVal) {
  50133. if (COMPONENTS[attr] || this.components[attr]) {
  50134. this.updateComponent(attr, newVal);
  50135. return;
  50136. }
  50137. if (attr === 'mixin') {
  50138. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  50139. if (newVal === this.computedMixinStr) { return; }
  50140. this.mixinUpdate(newVal, oldVal);
  50141. }
  50142. }
  50143. },
  50144. /**
  50145. * When mixins updated, trigger init or optimized-update of relevant components.
  50146. */
  50147. mixinUpdate: {
  50148. value: (function () {
  50149. var componentsUpdated = [];
  50150. return function (newMixins, oldMixins) {
  50151. var component;
  50152. var mixinEl;
  50153. var mixinIds;
  50154. var i;
  50155. var self = this;
  50156. if (!this.hasLoaded) {
  50157. this.addEventListener('loaded', function () {
  50158. self.mixinUpdate(newMixins, oldMixins);
  50159. }, ONCE);
  50160. return;
  50161. }
  50162. oldMixins = oldMixins || this.getAttribute('mixin');
  50163. mixinIds = this.updateMixins(newMixins, oldMixins);
  50164. // Loop over current mixins.
  50165. componentsUpdated.length = 0;
  50166. for (i = 0; i < this.mixinEls.length; i++) {
  50167. for (component in this.mixinEls[i].componentCache) {
  50168. if (componentsUpdated.indexOf(component) === -1) {
  50169. if (this.components[component]) {
  50170. // Update. Just rebuild data.
  50171. this.components[component].handleMixinUpdate();
  50172. } else {
  50173. // Init. buildData will gather mixin values.
  50174. this.initComponent(component, null);
  50175. }
  50176. componentsUpdated.push(component);
  50177. }
  50178. }
  50179. }
  50180. // Loop over old mixins to call for data rebuild.
  50181. for (i = 0; i < mixinIds.oldMixinIds.length; i++) {
  50182. mixinEl = document.getElementById(mixinIds.oldMixinIds[i]);
  50183. if (!mixinEl) { continue; }
  50184. for (component in mixinEl.componentCache) {
  50185. if (componentsUpdated.indexOf(component) === -1) {
  50186. if (this.components[component]) {
  50187. // Component removed. Rebuild data if not yet rebuilt.
  50188. this.components[component].handleMixinUpdate();
  50189. }
  50190. }
  50191. }
  50192. }
  50193. };
  50194. })()
  50195. },
  50196. /**
  50197. * setAttribute can:
  50198. *
  50199. * 1. Set a single property of a multi-property component.
  50200. * 2. Set multiple properties of a multi-property component.
  50201. * 3. Replace properties of a multi-property component.
  50202. * 4. Set a value for a single-property component, mixin, or normal HTML attribute.
  50203. *
  50204. * @param {string} attrName - Component or attribute name.
  50205. * @param {*} arg1 - Can be a value, property name, CSS-style property string, or
  50206. * object of properties.
  50207. * @param {*|bool} arg2 - If arg1 is a property name, this should be a value. Otherwise,
  50208. * it is a boolean indicating whether to clobber previous values (defaults to false).
  50209. */
  50210. setAttribute: {
  50211. value: (function () {
  50212. var singlePropUpdate = {};
  50213. return function (attrName, arg1, arg2) {
  50214. var newAttrValue;
  50215. var clobber;
  50216. var componentName;
  50217. var delimiterIndex;
  50218. var isDebugMode;
  50219. var key;
  50220. delimiterIndex = attrName.indexOf(MULTIPLE_COMPONENT_DELIMITER);
  50221. componentName = delimiterIndex > 0 ? attrName.substring(0, delimiterIndex) : attrName;
  50222. // Not a component. Normal set attribute.
  50223. if (!COMPONENTS[componentName]) {
  50224. if (attrName === 'mixin') { this.mixinUpdate(arg1); }
  50225. ANode.prototype.setAttribute.call(this, attrName, arg1);
  50226. return;
  50227. }
  50228. // Initialize component first if not yet initialized.
  50229. if (!this.components[attrName] && this.hasAttribute(attrName)) {
  50230. this.updateComponent(
  50231. attrName,
  50232. window.HTMLElement.prototype.getAttribute.call(this, attrName));
  50233. }
  50234. // Determine new attributes from the arguments
  50235. if (typeof arg2 !== 'undefined' &&
  50236. typeof arg1 === 'string' &&
  50237. arg1.length > 0 &&
  50238. typeof utils.styleParser.parse(arg1) === 'string') {
  50239. // Update a single property of a multi-property component
  50240. for (key in singlePropUpdate) { delete singlePropUpdate[key]; }
  50241. newAttrValue = singlePropUpdate;
  50242. newAttrValue[arg1] = arg2;
  50243. clobber = false;
  50244. } else {
  50245. // Update with a value, object, or CSS-style property string, with the possiblity
  50246. // of clobbering previous values.
  50247. newAttrValue = arg1;
  50248. clobber = (arg2 === true);
  50249. }
  50250. // Update component
  50251. this.updateComponent(attrName, newAttrValue, clobber);
  50252. // In debug mode, write component data up to the DOM.
  50253. isDebugMode = this.sceneEl && this.sceneEl.getAttribute('debug');
  50254. if (isDebugMode) { this.components[attrName].flushToDOM(); }
  50255. };
  50256. })(),
  50257. writable: window.debug
  50258. },
  50259. /**
  50260. * Reflect component data in the DOM (as seen from the browser DOM Inspector).
  50261. *
  50262. * @param {bool} recursive - Also flushToDOM on the children.
  50263. **/
  50264. flushToDOM: {
  50265. value: function (recursive) {
  50266. var components = this.components;
  50267. var child;
  50268. var children = this.children;
  50269. var i;
  50270. var key;
  50271. // Flush entity's components to DOM.
  50272. for (key in components) {
  50273. components[key].flushToDOM();
  50274. }
  50275. // Recurse.
  50276. if (!recursive) { return; }
  50277. for (i = 0; i < children.length; ++i) {
  50278. child = children[i];
  50279. if (!child.flushToDOM) { continue; }
  50280. child.flushToDOM(recursive);
  50281. }
  50282. }
  50283. },
  50284. /**
  50285. * If `attr` is a component, returns ALL component data including applied mixins and
  50286. * defaults.
  50287. *
  50288. * If `attr` is not a component, fall back to HTML getAttribute.
  50289. *
  50290. * @param {string} attr
  50291. * @returns {object|string} Object if component, else string.
  50292. */
  50293. getAttribute: {
  50294. value: function (attr) {
  50295. // If component, return component data.
  50296. var component;
  50297. if (attr === 'position') { return this.object3D.position; }
  50298. if (attr === 'rotation') { return getRotation(this); }
  50299. if (attr === 'scale') { return this.object3D.scale; }
  50300. if (attr === 'visible') { return this.object3D.visible; }
  50301. component = this.components[attr];
  50302. if (component) { return component.data; }
  50303. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  50304. },
  50305. writable: window.debug
  50306. },
  50307. /**
  50308. * If `attr` is a component, returns JUST the component data defined on the entity.
  50309. * Like a partial version of `getComputedAttribute` as returned component data
  50310. * does not include applied mixins or defaults.
  50311. *
  50312. * If `attr` is not a component, fall back to HTML getAttribute.
  50313. *
  50314. * @param {string} attr
  50315. * @returns {object|string} Object if component, else string.
  50316. */
  50317. getDOMAttribute: {
  50318. value: function (attr) {
  50319. // If cached value exists, return partial component data.
  50320. var component = this.components[attr];
  50321. if (component) { return component.attrValue; }
  50322. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  50323. },
  50324. writable: window.debug
  50325. },
  50326. addState: {
  50327. value: function (state) {
  50328. if (this.is(state)) { return; }
  50329. this.states.push(state);
  50330. this.emit('stateadded', state);
  50331. }
  50332. },
  50333. removeState: {
  50334. value: function (state) {
  50335. var stateIndex = this.states.indexOf(state);
  50336. if (stateIndex === -1) { return; }
  50337. this.states.splice(stateIndex, 1);
  50338. this.emit('stateremoved', state);
  50339. }
  50340. },
  50341. /**
  50342. * Checks if the element is in a given state. e.g. el.is('alive');
  50343. * @type {string} state - Name of the state we want to check
  50344. */
  50345. is: {
  50346. value: function (state) {
  50347. return this.states.indexOf(state) !== -1;
  50348. }
  50349. },
  50350. /**
  50351. * Open Inspector to this entity.
  50352. */
  50353. inspect: {
  50354. value: function () {
  50355. this.sceneEl.components.inspector.openInspector(this);
  50356. }
  50357. }
  50358. });
  50359. /**
  50360. * Check if a component is *defined* for an entity, including defaults and mixins.
  50361. * Does not check whether the component has been *initialized* for an entity.
  50362. *
  50363. * @param {string} el - Entity.
  50364. * @param {string} name - Component name.
  50365. * @returns {boolean}
  50366. */
  50367. function checkComponentDefined (el, name) {
  50368. // Check if element contains the component.
  50369. if (el.components[name] && el.components[name].attrValue) { return true; }
  50370. return isComponentMixedIn(name, el.mixinEls);
  50371. }
  50372. /**
  50373. * Check if any mixins contains a component.
  50374. *
  50375. * @param {string} name - Component name.
  50376. * @param {array} mixinEls - Array of <a-mixin>s.
  50377. */
  50378. function isComponentMixedIn (name, mixinEls) {
  50379. var i;
  50380. var inMixin = false;
  50381. for (i = 0; i < mixinEls.length; ++i) {
  50382. inMixin = mixinEls[i].hasAttribute(name);
  50383. if (inMixin) { break; }
  50384. }
  50385. return inMixin;
  50386. }
  50387. /**
  50388. * Given entity defined value, merge in extra data if necessary.
  50389. * Handle both single and multi-property components.
  50390. *
  50391. * @param {string} attrValue - Entity data.
  50392. * @param extraData - Entity data from another source to merge in.
  50393. */
  50394. function mergeComponentData (attrValue, extraData) {
  50395. // Extra data not defined, just return attrValue.
  50396. if (!extraData) { return attrValue; }
  50397. // Merge multi-property data.
  50398. if (extraData.constructor === Object) {
  50399. return utils.extend(extraData, utils.styleParser.parse(attrValue || {}));
  50400. }
  50401. // Return data, precendence to the defined value.
  50402. return attrValue || extraData;
  50403. }
  50404. function isComponent (componentName) {
  50405. if (componentName.indexOf(MULTIPLE_COMPONENT_DELIMITER) !== -1) {
  50406. componentName = utils.split(componentName, MULTIPLE_COMPONENT_DELIMITER)[0];
  50407. }
  50408. if (!COMPONENTS[componentName]) { return false; }
  50409. return true;
  50410. }
  50411. function getRotation (entityEl) {
  50412. var radToDeg = THREE.Math.radToDeg;
  50413. var rotation = entityEl.object3D.rotation;
  50414. var rotationObj = entityEl.rotationObj;
  50415. rotationObj.x = radToDeg(rotation.x);
  50416. rotationObj.y = radToDeg(rotation.y);
  50417. rotationObj.z = radToDeg(rotation.z);
  50418. return rotationObj;
  50419. }
  50420. AEntity = registerElement('a-entity', {prototype: proto});
  50421. module.exports = AEntity;
  50422. },{"../lib/three":154,"../utils/":178,"./a-node":103,"./a-register-element":104,"./component":105}],102:[function(_dereq_,module,exports){
  50423. var ANode = _dereq_('./a-node');
  50424. var registerElement = _dereq_('./a-register-element').registerElement;
  50425. var components = _dereq_('./component').components;
  50426. var utils = _dereq_('../utils');
  50427. var MULTIPLE_COMPONENT_DELIMITER = '__';
  50428. /**
  50429. * @member {object} componentCache - Cache of pre-parsed values. An object where the keys
  50430. * are component names and the values are already parsed by the component.
  50431. */
  50432. module.exports = registerElement('a-mixin', {
  50433. prototype: Object.create(ANode.prototype, {
  50434. createdCallback: {
  50435. value: function () {
  50436. this.componentCache = {};
  50437. this.id = this.getAttribute('id');
  50438. this.isMixin = true;
  50439. }
  50440. },
  50441. attributeChangedCallback: {
  50442. value: function (attr, oldVal, newVal) {
  50443. this.cacheAttribute(attr, newVal);
  50444. this.updateEntities();
  50445. }
  50446. },
  50447. attachedCallback: {
  50448. value: function () {
  50449. this.sceneEl = this.closestScene();
  50450. this.cacheAttributes();
  50451. this.updateEntities();
  50452. this.load();
  50453. }
  50454. },
  50455. /**
  50456. * setAttribute that parses and caches component values.
  50457. */
  50458. setAttribute: {
  50459. value: function (attr, value) {
  50460. window.HTMLElement.prototype.setAttribute.call(this, attr, value);
  50461. this.cacheAttribute(attr, value);
  50462. }
  50463. },
  50464. /**
  50465. * If `attr` is a component, then parse the value using the schema and store it.
  50466. */
  50467. cacheAttribute: {
  50468. value: function (attr, value) {
  50469. var component;
  50470. var componentName;
  50471. // Get component data.
  50472. componentName = utils.split(attr, MULTIPLE_COMPONENT_DELIMITER)[0];
  50473. component = components[componentName];
  50474. if (!component) { return; }
  50475. if (value === undefined) {
  50476. value = window.HTMLElement.prototype.getAttribute.call(this, attr);
  50477. }
  50478. this.componentCache[attr] = component.parseAttrValueForCache(value);
  50479. }
  50480. },
  50481. /**
  50482. * If `attr` is a component, then grab pre-parsed value from the cache.
  50483. * Else do a normal getAttribute.
  50484. */
  50485. getAttribute: {
  50486. value: function (attr) {
  50487. return this.componentCache[attr] ||
  50488. window.HTMLElement.prototype.getAttribute.call(this, attr);
  50489. }
  50490. },
  50491. /**
  50492. * Parse and cache every component defined on the mixin.
  50493. */
  50494. cacheAttributes: {
  50495. value: function () {
  50496. var attributes = this.attributes;
  50497. var attrName;
  50498. var i;
  50499. for (i = 0; i < attributes.length; i++) {
  50500. attrName = attributes[i].name;
  50501. this.cacheAttribute(attrName);
  50502. }
  50503. }
  50504. },
  50505. /**
  50506. * For entities that already have been loaded by the time the mixin was attached, tell
  50507. * those entities to register the mixin and refresh their component data.
  50508. */
  50509. updateEntities: {
  50510. value: function () {
  50511. var entity;
  50512. var entities;
  50513. var i;
  50514. if (!this.sceneEl) { return; }
  50515. entities = this.sceneEl.querySelectorAll('[mixin~=' + this.id + ']');
  50516. for (i = 0; i < entities.length; i++) {
  50517. entity = entities[i];
  50518. if (!entity.hasLoaded || entity.isMixin) { continue; }
  50519. entity.mixinUpdate(this.id);
  50520. }
  50521. }
  50522. }
  50523. })
  50524. });
  50525. },{"../utils":178,"./a-node":103,"./a-register-element":104,"./component":105}],103:[function(_dereq_,module,exports){
  50526. /* global CustomEvent */
  50527. var registerElement = _dereq_('./a-register-element').registerElement;
  50528. var isNode = _dereq_('./a-register-element').isNode;
  50529. var utils = _dereq_('../utils/');
  50530. var warn = utils.debug('core:a-node:warn');
  50531. var error = utils.debug('core:a-node:error');
  50532. /**
  50533. * Base class for A-Frame that manages loading of objects.
  50534. *
  50535. * Nodes can be modified using mixins.
  50536. * Nodes emit a `loaded` event when they and their children have initialized.
  50537. */
  50538. module.exports = registerElement('a-node', {
  50539. prototype: Object.create(window.HTMLElement.prototype, {
  50540. createdCallback: {
  50541. value: function () {
  50542. this.computedMixinStr = '';
  50543. this.hasLoaded = false;
  50544. this.isNode = true;
  50545. this.mixinEls = [];
  50546. },
  50547. writable: window.debug
  50548. },
  50549. attachedCallback: {
  50550. value: function () {
  50551. var mixins;
  50552. this.sceneEl = this.closestScene();
  50553. if (!this.sceneEl) {
  50554. warn('You are attempting to attach <' + this.tagName + '> outside of an A-Frame ' +
  50555. 'scene. Append this element to `<a-scene>` instead.');
  50556. }
  50557. this.hasLoaded = false;
  50558. this.emit('nodeready', undefined, false);
  50559. if (!this.isMixin) {
  50560. mixins = this.getAttribute('mixin');
  50561. if (mixins) { this.updateMixins(mixins); }
  50562. }
  50563. },
  50564. writable: window.debug
  50565. },
  50566. /**
  50567. * Handle mixin.
  50568. */
  50569. attributeChangedCallback: {
  50570. value: function (attr, oldVal, newVal) {
  50571. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  50572. if (newVal === this.computedMixinStr) { return; }
  50573. if (attr === 'mixin' && !this.isMixin) {
  50574. this.updateMixins(newVal, oldVal);
  50575. }
  50576. }
  50577. },
  50578. /**
  50579. * Returns the first scene by traversing up the tree starting from and
  50580. * including receiver element.
  50581. */
  50582. closestScene: {
  50583. value: function closest () {
  50584. var element = this;
  50585. while (element) {
  50586. if (element.isScene) { break; }
  50587. element = element.parentElement;
  50588. }
  50589. return element;
  50590. }
  50591. },
  50592. /**
  50593. * Returns first element matching a selector by traversing up the tree starting
  50594. * from and including receiver element.
  50595. *
  50596. * @param {string} selector - Selector of element to find.
  50597. */
  50598. closest: {
  50599. value: function closest (selector) {
  50600. var matches = this.matches || this.mozMatchesSelector ||
  50601. this.msMatchesSelector || this.oMatchesSelector || this.webkitMatchesSelector;
  50602. var element = this;
  50603. while (element) {
  50604. if (matches.call(element, selector)) { break; }
  50605. element = element.parentElement;
  50606. }
  50607. return element;
  50608. }
  50609. },
  50610. detachedCallback: {
  50611. value: function () {
  50612. this.hasLoaded = false;
  50613. }
  50614. },
  50615. /**
  50616. * Wait for children to load, if any.
  50617. * Then emit `loaded` event and set `hasLoaded`.
  50618. */
  50619. load: {
  50620. value: function (cb, childFilter) {
  50621. var children;
  50622. var childrenLoaded;
  50623. var self = this;
  50624. if (this.hasLoaded) { return; }
  50625. // Default to waiting for all nodes.
  50626. childFilter = childFilter || isNode;
  50627. // Wait for children to load (if any), then load.
  50628. children = this.getChildren();
  50629. childrenLoaded = children.filter(childFilter).map(function (child) {
  50630. return new Promise(function waitForLoaded (resolve) {
  50631. if (child.hasLoaded) { return resolve(); }
  50632. child.addEventListener('loaded', resolve);
  50633. });
  50634. });
  50635. Promise.all(childrenLoaded).then(function emitLoaded () {
  50636. self.hasLoaded = true;
  50637. if (cb) { cb(); }
  50638. self.emit('loaded', undefined, false);
  50639. }).catch(function (err) {
  50640. error('Failure loading node: ', err);
  50641. });
  50642. },
  50643. writable: true
  50644. },
  50645. getChildren: {
  50646. value: function () {
  50647. return Array.prototype.slice.call(this.children, 0);
  50648. }
  50649. },
  50650. /**
  50651. * Unregister old mixins and listeners.
  50652. * Register new mixins and listeners.
  50653. * Registering means to update `this.mixinEls` with listeners.
  50654. */
  50655. updateMixins: {
  50656. value: (function () {
  50657. var newMixinIdArray = [];
  50658. var oldMixinIdArray = [];
  50659. var mixinIds = {};
  50660. return function (newMixins, oldMixins) {
  50661. var i;
  50662. var newMixinIds;
  50663. var oldMixinIds;
  50664. newMixinIdArray.length = 0;
  50665. oldMixinIdArray.length = 0;
  50666. newMixinIds = newMixins ? utils.split(newMixins.trim(), /\s+/) : newMixinIdArray;
  50667. oldMixinIds = oldMixins ? utils.split(oldMixins.trim(), /\s+/) : oldMixinIdArray;
  50668. mixinIds.newMixinIds = newMixinIds;
  50669. mixinIds.oldMixinIds = oldMixinIds;
  50670. // Unregister old mixins.
  50671. for (i = 0; i < oldMixinIds.length; i++) {
  50672. if (newMixinIds.indexOf(oldMixinIds[i]) === -1) {
  50673. this.unregisterMixin(oldMixinIds[i]);
  50674. }
  50675. }
  50676. // Register new mixins.
  50677. this.computedMixinStr = '';
  50678. this.mixinEls.length = 0;
  50679. for (i = 0; i < newMixinIds.length; i++) {
  50680. this.registerMixin(document.getElementById(newMixinIds[i]));
  50681. }
  50682. // Update DOM. Keep track of `computedMixinStr` to not recurse back here after
  50683. // update.
  50684. if (this.computedMixinStr) {
  50685. this.computedMixinStr = this.computedMixinStr.trim();
  50686. window.HTMLElement.prototype.setAttribute.call(this, 'mixin',
  50687. this.computedMixinStr);
  50688. }
  50689. return mixinIds;
  50690. };
  50691. })()
  50692. },
  50693. /**
  50694. * From mixin ID, add mixin element to `mixinEls`.
  50695. *
  50696. * @param {Element} mixinEl
  50697. */
  50698. registerMixin: {
  50699. value: function (mixinEl) {
  50700. var compositedMixinIds;
  50701. var i;
  50702. var mixin;
  50703. if (!mixinEl) { return; }
  50704. // Register composited mixins (if mixin has mixins).
  50705. mixin = mixinEl.getAttribute('mixin');
  50706. if (mixin) {
  50707. compositedMixinIds = utils.split(mixin.trim(), /\s+/);
  50708. for (i = 0; i < compositedMixinIds.length; i++) {
  50709. this.registerMixin(document.getElementById(compositedMixinIds[i]));
  50710. }
  50711. }
  50712. // Register mixin.
  50713. this.computedMixinStr = this.computedMixinStr + ' ' + mixinEl.id;
  50714. this.mixinEls.push(mixinEl);
  50715. }
  50716. },
  50717. setAttribute: {
  50718. value: function (attr, newValue) {
  50719. if (attr === 'mixin') { this.updateMixins(newValue); }
  50720. window.HTMLElement.prototype.setAttribute.call(this, attr, newValue);
  50721. }
  50722. },
  50723. unregisterMixin: {
  50724. value: function (mixinId) {
  50725. var i;
  50726. var mixinEls = this.mixinEls;
  50727. var mixinEl;
  50728. for (i = 0; i < mixinEls.length; ++i) {
  50729. mixinEl = mixinEls[i];
  50730. if (mixinId === mixinEl.id) {
  50731. mixinEls.splice(i, 1);
  50732. break;
  50733. }
  50734. }
  50735. }
  50736. },
  50737. /**
  50738. * Emit a DOM event.
  50739. *
  50740. * @param {string} name - Name of event.
  50741. * @param {object} [detail={}] - Custom data to pass as `detail` to the event.
  50742. * @param {boolean} [bubbles=true] - Whether the event should bubble.
  50743. * @param {object} [extraData] - Extra data to pass to the event, if any.
  50744. */
  50745. emit: {
  50746. value: (function () {
  50747. var data = {};
  50748. return function (name, detail, bubbles, extraData) {
  50749. if (bubbles === undefined) { bubbles = true; }
  50750. data.bubbles = !!bubbles;
  50751. data.detail = detail;
  50752. // If extra data is present, we need to create a new object.
  50753. if (extraData) { data = utils.extend({}, extraData, data); }
  50754. this.dispatchEvent(new CustomEvent(name, data));
  50755. };
  50756. })(),
  50757. writable: window.debug
  50758. }
  50759. })
  50760. });
  50761. },{"../utils/":178,"./a-register-element":104}],104:[function(_dereq_,module,exports){
  50762. /*
  50763. ------------------------------------------------------------
  50764. ------------- WARNING WARNING WARNING WARNING --------------
  50765. ------------------------------------------------------------
  50766. This module wraps registerElement to deal with components that inherit from
  50767. `ANode` and `AEntity`. It's a pass through in any other case.
  50768. It wraps some of the prototype methods of the created element to make sure
  50769. that the corresponding functions in the base prototypes (`AEntity` and `ANode`)
  50770. are also invoked. The method in the base prototype is always called before the one
  50771. in the derived prototype.
  50772. */
  50773. // Polyfill `document.registerElement`.
  50774. _dereq_('document-register-element');
  50775. var ANode; // Must declare before AEntity. Initialized at the bottom.
  50776. var AEntity;
  50777. var knownTags = module.exports.knownTags = {};
  50778. function addTagName (tagName) {
  50779. knownTags[tagName.toLowerCase()] = true;
  50780. }
  50781. /**
  50782. * Return whether the element type is one of our known registered ones.
  50783. *
  50784. * @param {string} node - The name of the tag to register.
  50785. * @returns {boolean} Whether the tag name matches that of our registered custom elements.
  50786. */
  50787. module.exports.isNode = function (node) {
  50788. return node.tagName.toLowerCase() in knownTags || node.isNode;
  50789. };
  50790. /**
  50791. * @param {string} tagName - The name of the tag to register.
  50792. * @param {object} obj - The prototype of the new element.
  50793. * @returns {object} The prototype of the new element.
  50794. */
  50795. module.exports.registerElement = function (tagName, obj) {
  50796. var proto = Object.getPrototypeOf(obj.prototype);
  50797. var newObj = obj;
  50798. var isANode = ANode && proto === ANode.prototype;
  50799. var isAEntity = AEntity && proto === AEntity.prototype;
  50800. if (isANode || isAEntity) { addTagName(tagName); }
  50801. // Wrap if element inherits from `ANode`.
  50802. if (isANode) {
  50803. newObj = wrapANodeMethods(obj.prototype);
  50804. newObj = {prototype: Object.create(proto, newObj)};
  50805. }
  50806. // Wrap if element inherits from `AEntity`.
  50807. if (isAEntity) {
  50808. newObj = wrapAEntityMethods(obj.prototype);
  50809. newObj = {prototype: Object.create(proto, newObj)};
  50810. }
  50811. // Give all functions their proper name.
  50812. Object.getOwnPropertyNames(newObj.prototype).forEach(function (propName) {
  50813. var propVal = newObj.prototype[propName];
  50814. if (typeof propVal === 'function') {
  50815. propVal.displayName = propName;
  50816. }
  50817. });
  50818. return document.registerElement(tagName, newObj);
  50819. };
  50820. /**
  50821. * Wrap some obj methods to call those on `ANode` base prototype.
  50822. *
  50823. * @param {object} obj - Object that contains the methods that will be wrapped.
  50824. * @return {object} An object with the same properties as the input parameter but
  50825. * with some of methods wrapped.
  50826. */
  50827. function wrapANodeMethods (obj) {
  50828. var newObj = {};
  50829. var ANodeMethods = [
  50830. 'attachedCallback',
  50831. 'attributeChangedCallback',
  50832. 'createdCallback',
  50833. 'detachedCallback'
  50834. ];
  50835. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  50836. copyProperties(obj, newObj);
  50837. return newObj;
  50838. }
  50839. /**
  50840. * This wraps some of the obj methods to call those on `AEntity` base prototype.
  50841. *
  50842. * @param {object} obj - The objects that contains the methods that will be wrapped.
  50843. * @return {object} - An object with the same properties as the input parameter but
  50844. * with some of methods wrapped.
  50845. */
  50846. function wrapAEntityMethods (obj) {
  50847. var newObj = {};
  50848. var ANodeMethods = [
  50849. 'attachedCallback',
  50850. 'attributeChangedCallback',
  50851. 'createdCallback',
  50852. 'detachedCallback'
  50853. ];
  50854. var AEntityMethods = [
  50855. 'attachedCallback',
  50856. 'attributeChangedCallback',
  50857. 'createdCallback',
  50858. 'detachedCallback'
  50859. ];
  50860. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  50861. wrapMethods(newObj, AEntityMethods, obj, AEntity.prototype);
  50862. // Copies the remaining properties into the new object.
  50863. copyProperties(obj, newObj);
  50864. return newObj;
  50865. }
  50866. /**
  50867. * Wrap a list a methods to ensure that those in the base prototype are called
  50868. * before the derived one.
  50869. *
  50870. * @param {object} targetObj - Object that will contain the wrapped methods.
  50871. * @param {array} methodList - List of methods from the derivedObj that will be wrapped.
  50872. * @param {object} derivedObject - Object that inherits from the baseObj.
  50873. * @param {object} baseObj - Object that derivedObj inherits from.
  50874. */
  50875. function wrapMethods (targetObj, methodList, derivedObj, baseObj) {
  50876. methodList.forEach(function (methodName) {
  50877. wrapMethod(targetObj, methodName, derivedObj, baseObj);
  50878. });
  50879. }
  50880. module.exports.wrapMethods = wrapMethods;
  50881. /**
  50882. * Wrap one method to ensure that the one in the base prototype is called before
  50883. * the one in the derived one.
  50884. *
  50885. * @param {object} obj - Object that will contain the wrapped method.
  50886. * @param {string} methodName - The name of the method that will be wrapped.
  50887. * @param {object} derivedObject - Object that inherits from the baseObj.
  50888. * @param {object} baseObj - Object that derivedObj inherits from.
  50889. */
  50890. function wrapMethod (obj, methodName, derivedObj, baseObj) {
  50891. var derivedMethod = derivedObj[methodName];
  50892. var baseMethod = baseObj[methodName];
  50893. // Derived prototype does not define method, no need to wrap.
  50894. if (!derivedMethod || !baseMethod) { return; }
  50895. // Derived prototype doesn't override the one in the base one, no need to wrap.
  50896. if (derivedMethod === baseMethod) { return; }
  50897. // Wrap to ensure the base method is called before the one in the derived prototype.
  50898. obj[methodName] = {
  50899. value: function wrappedMethod () {
  50900. baseMethod.apply(this, arguments);
  50901. return derivedMethod.apply(this, arguments);
  50902. },
  50903. writable: window.debug
  50904. };
  50905. }
  50906. /**
  50907. * It copies the properties from source to destination object if they don't
  50908. * exist already.
  50909. *
  50910. * @param {object} source - The object where properties are copied from.
  50911. * @param {type} destination - The object where properties are copied to.
  50912. */
  50913. function copyProperties (source, destination) {
  50914. var props = Object.getOwnPropertyNames(source);
  50915. props.forEach(function (prop) {
  50916. var desc;
  50917. if (!destination[prop]) {
  50918. desc = Object.getOwnPropertyDescriptor(source, prop);
  50919. destination[prop] = {value: source[prop], writable: desc.writable};
  50920. }
  50921. });
  50922. }
  50923. ANode = _dereq_('./a-node');
  50924. AEntity = _dereq_('./a-entity');
  50925. },{"./a-entity":101,"./a-node":103,"document-register-element":11}],105:[function(_dereq_,module,exports){
  50926. /* global Node */
  50927. var schema = _dereq_('./schema');
  50928. var scenes = _dereq_('./scene/scenes');
  50929. var systems = _dereq_('./system');
  50930. var utils = _dereq_('../utils/');
  50931. var components = module.exports.components = {}; // Keep track of registered components.
  50932. var parseProperties = schema.parseProperties;
  50933. var parseProperty = schema.parseProperty;
  50934. var processSchema = schema.process;
  50935. var isSingleProp = schema.isSingleProperty;
  50936. var stringifyProperties = schema.stringifyProperties;
  50937. var stringifyProperty = schema.stringifyProperty;
  50938. var styleParser = utils.styleParser;
  50939. var warn = utils.debug('core:component:warn');
  50940. var aframeScript = document.currentScript;
  50941. var upperCaseRegExp = new RegExp('[A-Z]+');
  50942. // Object pools by component, created upon registration.
  50943. var objectPools = {};
  50944. /**
  50945. * Component class definition.
  50946. *
  50947. * Components configure appearance, modify behavior, or add functionality to
  50948. * entities. The behavior and appearance of an entity can be changed at runtime
  50949. * by adding, removing, or updating components. Entities do not share instances
  50950. * of components.
  50951. *
  50952. * @member {object} el - Reference to the entity element.
  50953. * @member {string} attrValue - Value of the corresponding HTML attribute.
  50954. * @member {object} data - Component data populated by parsing the
  50955. * mapped attribute of the component plus applying defaults and mixins.
  50956. */
  50957. var Component = module.exports.Component = function (el, attrValue, id) {
  50958. var self = this;
  50959. this.el = el;
  50960. this.id = id;
  50961. this.attrName = this.name + (id ? '__' + id : '');
  50962. this.evtDetail = {id: this.id, name: this.name};
  50963. this.initialized = false;
  50964. this.isSingleProperty = isSingleProp(this.schema);
  50965. this.isSinglePropertyObject = this.isSingleProperty &&
  50966. isObject(parseProperty(undefined, this.schema));
  50967. this.isObjectBased = !this.isSingleProperty || this.isSinglePropertyObject;
  50968. this.el.components[this.attrName] = this;
  50969. this.objectPool = objectPools[this.name];
  50970. // Store component data from previous update call.
  50971. this.attrValue = undefined;
  50972. this.nextData = this.isObjectBased ? this.objectPool.use() : undefined;
  50973. this.oldData = this.isObjectBased ? this.objectPool.use() : undefined;
  50974. this.previousOldData = this.isObjectBased ? this.objectPool.use() : undefined;
  50975. this.parsingAttrValue = this.isObjectBased ? this.objectPool.use() : undefined;
  50976. // Last value passed to updateProperties.
  50977. this.throttledEmitComponentChanged = utils.throttle(function emitChange () {
  50978. el.emit('componentchanged', self.evtDetail, false);
  50979. }, 200);
  50980. this.updateProperties(attrValue);
  50981. };
  50982. Component.prototype = {
  50983. /**
  50984. * Contains the type schema and defaults for the data values.
  50985. * Data is coerced into the types of the values of the defaults.
  50986. */
  50987. schema: {},
  50988. /**
  50989. * Init handler. Similar to attachedCallback.
  50990. * Called during component initialization and is only run once.
  50991. * Components can use this to set initial state.
  50992. */
  50993. init: function () { /* no-op */ },
  50994. /**
  50995. * Update handler. Similar to attributeChangedCallback.
  50996. * Called whenever component's data changes.
  50997. * Also called on component initialization when the component receives initial data.
  50998. *
  50999. * @param {object} prevData - Previous attributes of the component.
  51000. */
  51001. update: function (prevData) { /* no-op */ },
  51002. updateSchema: undefined,
  51003. /**
  51004. * Tick handler.
  51005. * Called on each tick of the scene render loop.
  51006. * Affected by play and pause.
  51007. *
  51008. * @param {number} time - Scene tick time.
  51009. * @param {number} timeDelta - Difference in current render time and previous render time.
  51010. */
  51011. tick: undefined,
  51012. /**
  51013. * Tock handler.
  51014. * Called on each tock of the scene render loop.
  51015. * Affected by play and pause.
  51016. *
  51017. * @param {number} time - Scene tick time.
  51018. * @param {number} timeDelta - Difference in current render time and previous render time.
  51019. * @param {object} camera - Camera used to render the last frame.
  51020. */
  51021. tock: undefined,
  51022. /**
  51023. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  51024. */
  51025. play: function () { /* no-op */ },
  51026. /**
  51027. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  51028. */
  51029. pause: function () { /* no-op */ },
  51030. /**
  51031. * Remove handler. Similar to detachedCallback.
  51032. * Called whenever component is removed from the entity (i.e., removeAttribute).
  51033. * Components can use this to reset behavior on the entity.
  51034. */
  51035. remove: function () { /* no-op */ },
  51036. /**
  51037. * Parses each property based on property type.
  51038. * If component is single-property, then parses the single property value.
  51039. *
  51040. * @param {string} value - HTML attribute value.
  51041. * @param {boolean} silent - Suppress warning messages.
  51042. * @returns {object} Component data.
  51043. */
  51044. parse: function (value, silent) {
  51045. var schema = this.schema;
  51046. if (this.isSingleProperty) { return parseProperty(value, schema); }
  51047. return parseProperties(styleParser.parse(value), schema, true, this.name, silent);
  51048. },
  51049. /**
  51050. * Stringify properties if necessary.
  51051. *
  51052. * Only called from `Entity.setAttribute` for properties whose parsers accept a non-string
  51053. * value (e.g., selector, vec3 property types).
  51054. *
  51055. * @param {object} data - Complete component data.
  51056. * @returns {string}
  51057. */
  51058. stringify: function (data) {
  51059. var schema = this.schema;
  51060. if (typeof data === 'string') { return data; }
  51061. if (this.isSingleProperty) { return stringifyProperty(data, schema); }
  51062. data = stringifyProperties(data, schema);
  51063. return styleParser.stringify(data);
  51064. },
  51065. /**
  51066. * Update the cache of the pre-parsed attribute value.
  51067. *
  51068. * @param {string} value - New data.
  51069. * @param {boolean } clobber - Whether to wipe out and replace previous data.
  51070. */
  51071. updateCachedAttrValue: function (value, clobber) {
  51072. var newAttrValue;
  51073. var tempObject;
  51074. var property;
  51075. if (value === undefined) { return; }
  51076. // If null value is the new attribute value, make the attribute value falsy.
  51077. if (value === null) {
  51078. if (this.isObjectBased && this.attrValue) {
  51079. this.objectPool.recycle(this.attrValue);
  51080. }
  51081. this.attrValue = undefined;
  51082. return;
  51083. }
  51084. if (value instanceof Object) {
  51085. // If value is an object, copy it to our pooled newAttrValue object to use to update
  51086. // the attrValue.
  51087. tempObject = this.objectPool.use();
  51088. newAttrValue = utils.extend(tempObject, value);
  51089. } else {
  51090. newAttrValue = this.parseAttrValueForCache(value);
  51091. }
  51092. // Merge new data with previous `attrValue` if updating and not clobbering.
  51093. if (this.isObjectBased && !clobber && this.attrValue) {
  51094. for (property in this.attrValue) {
  51095. if (newAttrValue[property] === undefined) {
  51096. newAttrValue[property] = this.attrValue[property];
  51097. }
  51098. }
  51099. }
  51100. // Update attrValue.
  51101. if (this.isObjectBased && !this.attrValue) {
  51102. this.attrValue = this.objectPool.use();
  51103. }
  51104. utils.objectPool.clearObject(this.attrValue);
  51105. this.attrValue = extendProperties(this.attrValue, newAttrValue, this.isObjectBased);
  51106. utils.objectPool.clearObject(tempObject);
  51107. },
  51108. /**
  51109. * Given an HTML attribute value parses the string based on the component schema.
  51110. * To avoid double parsings of strings into strings we store the original instead
  51111. * of the parsed one
  51112. *
  51113. * @param {string} value - HTML attribute value
  51114. */
  51115. parseAttrValueForCache: function (value) {
  51116. var parsedValue;
  51117. if (typeof value !== 'string') { return value; }
  51118. if (this.isSingleProperty) {
  51119. parsedValue = this.schema.parse(value);
  51120. /**
  51121. * To avoid bogus double parsings. Cached values will be parsed when building
  51122. * component data. For instance when parsing a src id to its url, we want to cache
  51123. * original string and not the parsed one (#monster -> models/monster.dae)
  51124. * so when building data we parse the expected value.
  51125. */
  51126. if (typeof parsedValue === 'string') { parsedValue = value; }
  51127. } else {
  51128. // Parse using the style parser to avoid double parsing of individual properties.
  51129. utils.objectPool.clearObject(this.parsingAttrValue);
  51130. parsedValue = styleParser.parse(value, this.parsingAttrValue);
  51131. }
  51132. return parsedValue;
  51133. },
  51134. /**
  51135. * Write cached attribute data to the entity DOM element.
  51136. *
  51137. * @param {boolean} isDefault - Whether component is a default component. Always flush for
  51138. * default components.
  51139. */
  51140. flushToDOM: function (isDefault) {
  51141. var attrValue = isDefault ? this.data : this.attrValue;
  51142. if (!attrValue) { return; }
  51143. window.HTMLElement.prototype.setAttribute.call(this.el, this.attrName,
  51144. this.stringify(attrValue));
  51145. },
  51146. /**
  51147. * Apply new component data if data has changed (from setAttribute).
  51148. *
  51149. * @param {string} attrValue - HTML attribute value.
  51150. * If undefined, use the cached attribute value and continue updating properties.
  51151. * @param {boolean} clobber - The previous component data is overwritten by the atrrValue
  51152. */
  51153. updateProperties: function (attrValue, clobber) {
  51154. var el = this.el;
  51155. // Just cache the attribute if the entity has not loaded
  51156. // Components are not initialized until the entity has loaded
  51157. if (!el.hasLoaded) {
  51158. this.updateCachedAttrValue(attrValue);
  51159. return;
  51160. }
  51161. // Parse the attribute value.
  51162. // Cache current attrValue for future updates. Updates `this.attrValue`.
  51163. // `null` means no value on purpose, do not set a default value, let mixins take over.
  51164. if (attrValue !== null) {
  51165. attrValue = this.parseAttrValueForCache(attrValue);
  51166. }
  51167. // Cache current attrValue for future updates.
  51168. this.updateCachedAttrValue(attrValue, clobber);
  51169. if (this.initialized) {
  51170. this.updateComponent(attrValue, clobber);
  51171. this.callUpdateHandler();
  51172. } else {
  51173. this.initComponent();
  51174. }
  51175. },
  51176. initComponent: function () {
  51177. var el = this.el;
  51178. var initialOldData;
  51179. // Build data.
  51180. if (this.updateSchema) { this.updateSchema(this.buildData(this.attrValue, false, true)); }
  51181. this.data = this.buildData(this.attrValue);
  51182. // Component is being already initialized.
  51183. if (el.initializingComponents[this.name]) { return; }
  51184. // Prevent infinite loop in case of init method setting same component on the entity.
  51185. el.initializingComponents[this.name] = true;
  51186. // Initialize component.
  51187. this.init();
  51188. this.initialized = true;
  51189. delete el.initializingComponents[this.name];
  51190. // Store current data as previous data for future updates.
  51191. this.oldData = extendProperties(this.oldData, this.data, this.isObjectBased);
  51192. // For oldData, pass empty object to multiple-prop schemas or object single-prop schema.
  51193. // Pass undefined to rest of types.
  51194. initialOldData = this.isObjectBased ? this.objectPool.use() : undefined;
  51195. this.update(initialOldData);
  51196. if (this.isObjectBased) { this.objectPool.recycle(initialOldData); }
  51197. // Play the component if the entity is playing.
  51198. if (el.isPlaying) { this.play(); }
  51199. el.emit('componentinitialized', this.evtDetail, false);
  51200. },
  51201. /**
  51202. * @param attrValue - Passed argument from setAttribute.
  51203. */
  51204. updateComponent: function (attrValue, clobber) {
  51205. var key;
  51206. var mayNeedSchemaUpdate;
  51207. if (clobber) {
  51208. // Clobber. Rebuild.
  51209. if (this.updateSchema) {
  51210. this.updateSchema(this.buildData(this.attrValue, true, true));
  51211. }
  51212. this.data = this.buildData(this.attrValue, true, false);
  51213. return;
  51214. }
  51215. // Apply new value to this.data in place since direct update.
  51216. if (this.isSingleProperty) {
  51217. if (this.isObjectBased) {
  51218. parseProperty(attrValue, this.schema);
  51219. }
  51220. // Single-property (already parsed).
  51221. this.data = attrValue;
  51222. return;
  51223. }
  51224. parseProperties(attrValue, this.schema, true, this.name);
  51225. // Check if we need to update schema.
  51226. if (this.schemaChangeKeys.length) {
  51227. for (key in attrValue) {
  51228. if (this.schema[key].schemaChange) {
  51229. mayNeedSchemaUpdate = true;
  51230. break;
  51231. }
  51232. }
  51233. }
  51234. if (mayNeedSchemaUpdate) {
  51235. // Rebuild data if need schema update.
  51236. if (this.updateSchema) {
  51237. this.updateSchema(this.buildData(this.attrValue, true, true));
  51238. }
  51239. this.data = this.buildData(this.attrValue, true, false);
  51240. return;
  51241. }
  51242. // Normal update.
  51243. for (key in attrValue) {
  51244. if (attrValue[key] === undefined) { continue; }
  51245. this.data[key] = attrValue[key];
  51246. }
  51247. },
  51248. /**
  51249. * Check if component should fire update and fire update lifecycle handler.
  51250. */
  51251. callUpdateHandler: function () {
  51252. var hasComponentChanged;
  51253. // Store the previous old data before we calculate the new oldData.
  51254. if (this.previousOldData instanceof Object) {
  51255. utils.objectPool.clearObject(this.previousOldData);
  51256. }
  51257. if (this.isObjectBased) {
  51258. copyData(this.previousOldData, this.oldData);
  51259. } else {
  51260. this.previousOldData = this.oldData;
  51261. }
  51262. hasComponentChanged = !utils.deepEqual(this.oldData, this.data);
  51263. // Don't update if properties haven't changed.
  51264. // Always update rotation, position, scale.
  51265. if (!this.isPositionRotationScale && !hasComponentChanged) { return; }
  51266. // Store current data as previous data for future updates.
  51267. // Reuse `this.oldData` object to try not to allocate another one.
  51268. if (this.oldData instanceof Object) { utils.objectPool.clearObject(this.oldData); }
  51269. this.oldData = extendProperties(this.oldData, this.data, this.isObjectBased);
  51270. // Update component with the previous old data.
  51271. this.update(this.previousOldData);
  51272. this.throttledEmitComponentChanged();
  51273. },
  51274. handleMixinUpdate: function () {
  51275. this.data = this.buildData(this.attrValue);
  51276. this.callUpdateHandler();
  51277. },
  51278. /**
  51279. * Reset value of a property to the property's default value.
  51280. * If single-prop component, reset value to component's default value.
  51281. *
  51282. * @param {string} propertyName - Name of property to reset.
  51283. */
  51284. resetProperty: function (propertyName) {
  51285. if (this.isObjectBased) {
  51286. if (!(propertyName in this.attrValue)) { return; }
  51287. delete this.attrValue[propertyName];
  51288. this.data[propertyName] = this.schema[propertyName].default;
  51289. } else {
  51290. this.attrValue = this.schema.default;
  51291. this.data = this.schema.default;
  51292. }
  51293. this.updateProperties(this.attrValue);
  51294. },
  51295. /**
  51296. * Extend schema of component given a partial schema.
  51297. *
  51298. * Some components might want to mutate their schema based on certain properties.
  51299. * e.g., Material component changes its schema based on `shader` to account for different
  51300. * uniforms
  51301. *
  51302. * @param {object} schemaAddon - Schema chunk that extend base schema.
  51303. */
  51304. extendSchema: function (schemaAddon) {
  51305. var extendedSchema;
  51306. // Clone base schema.
  51307. extendedSchema = utils.extend({}, components[this.name].schema);
  51308. // Extend base schema with new schema chunk.
  51309. utils.extend(extendedSchema, schemaAddon);
  51310. this.schema = processSchema(extendedSchema);
  51311. this.el.emit('schemachanged', this.evtDetail);
  51312. },
  51313. /**
  51314. * Build component data from the current state of the entity.data.
  51315. *
  51316. * Precedence:
  51317. * 1. Defaults data
  51318. * 2. Mixin data.
  51319. * 3. Attribute data.
  51320. *
  51321. * Finally coerce the data to the types of the defaults.
  51322. *
  51323. * @param {object} newData - Element new data.
  51324. * @param {boolean} clobber - The previous data is completely replaced by the new one.
  51325. * @param {boolean} silent - Suppress warning messages.
  51326. * @return {object} The component data
  51327. */
  51328. buildData: function (newData, clobber, silent) {
  51329. var componentDefined;
  51330. var data;
  51331. var defaultValue;
  51332. var key;
  51333. var mixinData;
  51334. var nextData = this.nextData;
  51335. var schema = this.schema;
  51336. var i;
  51337. var mixinEls = this.el.mixinEls;
  51338. var previousData;
  51339. // Whether component has a defined value. For arrays, treat empty as not defined.
  51340. componentDefined = newData && newData.constructor === Array
  51341. ? newData.length
  51342. : newData !== undefined && newData !== null;
  51343. if (this.isObjectBased) { utils.objectPool.clearObject(nextData); }
  51344. // 1. Gather default values (lowest precendence).
  51345. if (this.isSingleProperty) {
  51346. if (this.isObjectBased) {
  51347. // If object-based single-prop, then copy over the data to our pooled object.
  51348. data = copyData(nextData, schema.default);
  51349. } else {
  51350. // If is plain single-prop, copy by value the default.
  51351. data = isObjectOrArray(schema.default)
  51352. ? utils.clone(schema.default)
  51353. : schema.default;
  51354. }
  51355. } else {
  51356. // Preserve previously set properties if clobber not enabled.
  51357. previousData = !clobber && this.attrValue;
  51358. // Clone default value if object so components don't share object
  51359. data = previousData instanceof Object
  51360. ? copyData(nextData, previousData)
  51361. : nextData;
  51362. // Apply defaults.
  51363. for (key in schema) {
  51364. defaultValue = schema[key].default;
  51365. if (data[key] !== undefined) { continue; }
  51366. // Clone default value if object so components don't share object
  51367. data[key] = isObjectOrArray(defaultValue)
  51368. ? utils.clone(defaultValue)
  51369. : defaultValue;
  51370. }
  51371. }
  51372. // 2. Gather mixin values.
  51373. for (i = 0; i < mixinEls.length; i++) {
  51374. mixinData = mixinEls[i].getAttribute(this.attrName);
  51375. if (!mixinData) { continue; }
  51376. data = extendProperties(data, mixinData, this.isObjectBased);
  51377. }
  51378. // 3. Gather attribute values (highest precendence).
  51379. if (componentDefined) {
  51380. if (this.isSingleProperty) {
  51381. // If object-based, copy the value to not modify the original.
  51382. if (isObject(newData)) {
  51383. copyData(this.parsingAttrValue, newData);
  51384. return parseProperty(this.parsingAttrValue, schema);
  51385. }
  51386. return parseProperty(newData, schema);
  51387. }
  51388. data = extendProperties(data, newData, this.isObjectBased);
  51389. } else {
  51390. // Parse and coerce using the schema.
  51391. if (this.isSingleProperty) { return parseProperty(data, schema); }
  51392. }
  51393. return parseProperties(data, schema, undefined, this.name, silent);
  51394. }
  51395. };
  51396. // For testing.
  51397. if (window.debug) {
  51398. var registrationOrderWarnings = module.exports.registrationOrderWarnings = {};
  51399. }
  51400. /**
  51401. * Registers a component to A-Frame.
  51402. *
  51403. * @param {string} name - Component name.
  51404. * @param {object} definition - Component schema and lifecycle method handlers.
  51405. * @returns {object} Component.
  51406. */
  51407. module.exports.registerComponent = function (name, definition) {
  51408. var NewComponent;
  51409. var propertyName;
  51410. var proto = {};
  51411. var schema;
  51412. var schemaIsSingleProp;
  51413. // Warning if component is statically registered after the scene.
  51414. if (document.currentScript && document.currentScript !== aframeScript) {
  51415. scenes.forEach(function checkPosition (sceneEl) {
  51416. // Okay to register component after the scene at runtime.
  51417. if (sceneEl.hasLoaded) { return; }
  51418. // Check that component is declared before the scene.
  51419. if (document.currentScript.compareDocumentPosition(sceneEl) ===
  51420. Node.DOCUMENT_POSITION_FOLLOWING) { return; }
  51421. warn('The component `' + name + '` was registered in a <script> tag after the scene. ' +
  51422. 'Component <script> tags in an HTML file should be declared *before* the scene ' +
  51423. 'such that the component is available to entities during scene initialization.');
  51424. // For testing.
  51425. if (window.debug) { registrationOrderWarnings[name] = true; }
  51426. });
  51427. }
  51428. if (upperCaseRegExp.test(name) === true) {
  51429. warn('The component name `' + name + '` contains uppercase characters, but ' +
  51430. 'HTML will ignore the capitalization of attribute names. ' +
  51431. 'Change the name to be lowercase: `' + name.toLowerCase() + '`');
  51432. }
  51433. if (name.indexOf('__') !== -1) {
  51434. throw new Error('The component name `' + name + '` is not allowed. ' +
  51435. 'The sequence __ (double underscore) is reserved to specify an id' +
  51436. ' for multiple components of the same type');
  51437. }
  51438. // Format definition object to prototype object.
  51439. Object.keys(definition).forEach(function (key) {
  51440. proto[key] = {
  51441. value: definition[key],
  51442. writable: true
  51443. };
  51444. });
  51445. if (components[name]) {
  51446. throw new Error('The component `' + name + '` has been already registered. ' +
  51447. 'Check that you are not loading two versions of the same component ' +
  51448. 'or two different components of the same name.');
  51449. }
  51450. NewComponent = function (el, attr, id) {
  51451. Component.call(this, el, attr, id);
  51452. };
  51453. NewComponent.prototype = Object.create(Component.prototype, proto);
  51454. NewComponent.prototype.name = name;
  51455. NewComponent.prototype.isPositionRotationScale =
  51456. name === 'position' || name === 'rotation' || name === 'scale';
  51457. NewComponent.prototype.constructor = NewComponent;
  51458. NewComponent.prototype.system = systems && systems.systems[name];
  51459. NewComponent.prototype.play = wrapPlay(NewComponent.prototype.play);
  51460. NewComponent.prototype.pause = wrapPause(NewComponent.prototype.pause);
  51461. NewComponent.prototype.remove = wrapRemove(NewComponent.prototype.remove);
  51462. schema = utils.extend(processSchema(NewComponent.prototype.schema,
  51463. NewComponent.prototype.name));
  51464. schemaIsSingleProp = isSingleProp(NewComponent.prototype.schema);
  51465. // Keep track of keys that may potentially change the schema.
  51466. if (!schemaIsSingleProp) {
  51467. NewComponent.prototype.schemaChangeKeys = [];
  51468. for (propertyName in schema) {
  51469. if (schema[propertyName].schemaChange) {
  51470. NewComponent.prototype.schemaChangeKeys.push(propertyName);
  51471. }
  51472. }
  51473. }
  51474. // Create object pool for class of components.
  51475. objectPools[name] = utils.objectPool.createPool();
  51476. components[name] = {
  51477. Component: NewComponent,
  51478. dependencies: NewComponent.prototype.dependencies,
  51479. isSingleProp: schemaIsSingleProp,
  51480. multiple: NewComponent.prototype.multiple,
  51481. name: name,
  51482. parse: NewComponent.prototype.parse,
  51483. parseAttrValueForCache: NewComponent.prototype.parseAttrValueForCache,
  51484. schema: schema,
  51485. stringify: NewComponent.prototype.stringify,
  51486. type: NewComponent.prototype.type
  51487. };
  51488. return NewComponent;
  51489. };
  51490. /**
  51491. * Clone component data.
  51492. * Clone only the properties that are plain objects while keeping a reference for the rest.
  51493. *
  51494. * @param data - Component data to clone.
  51495. * @returns Cloned data.
  51496. */
  51497. function copyData (dest, sourceData) {
  51498. var parsedProperty;
  51499. var key;
  51500. for (key in sourceData) {
  51501. if (sourceData[key] === undefined) { continue; }
  51502. parsedProperty = sourceData[key];
  51503. dest[key] = isObjectOrArray(parsedProperty)
  51504. ? utils.clone(parsedProperty)
  51505. : parsedProperty;
  51506. }
  51507. return dest;
  51508. }
  51509. /**
  51510. * Object extending with checking for single-property schema.
  51511. *
  51512. * @param dest - Destination object or value.
  51513. * @param source - Source object or value
  51514. * @param {boolean} isObjectBased - Whether values are objects.
  51515. * @returns Overridden object or value.
  51516. */
  51517. function extendProperties (dest, source, isObjectBased) {
  51518. var key;
  51519. if (isObjectBased && source.constructor === Object) {
  51520. for (key in source) {
  51521. if (source[key] === undefined) { continue; }
  51522. if (source[key] && source[key].constructor === Object) {
  51523. dest[key] = utils.clone(source[key]);
  51524. } else {
  51525. dest[key] = source[key];
  51526. }
  51527. }
  51528. return dest;
  51529. }
  51530. return source;
  51531. }
  51532. /**
  51533. * Checks if a component has defined a method that needs to run every frame.
  51534. */
  51535. function hasBehavior (component) {
  51536. return component.tick || component.tock;
  51537. }
  51538. /**
  51539. * Wrapper for defined pause method.
  51540. * Pause component by removing tick behavior and calling user's pause method.
  51541. *
  51542. * @param pauseMethod {function}
  51543. */
  51544. function wrapPause (pauseMethod) {
  51545. return function pause () {
  51546. var sceneEl = this.el.sceneEl;
  51547. if (!this.isPlaying) { return; }
  51548. pauseMethod.call(this);
  51549. this.isPlaying = false;
  51550. // Remove tick behavior.
  51551. if (!hasBehavior(this)) { return; }
  51552. sceneEl.removeBehavior(this);
  51553. };
  51554. }
  51555. /**
  51556. * Wrapper for defined play method.
  51557. * Play component by adding tick behavior and calling user's play method.
  51558. *
  51559. * @param playMethod {function}
  51560. */
  51561. function wrapPlay (playMethod) {
  51562. return function play () {
  51563. var sceneEl = this.el.sceneEl;
  51564. var shouldPlay = this.el.isPlaying && !this.isPlaying;
  51565. if (!this.initialized || !shouldPlay) { return; }
  51566. playMethod.call(this);
  51567. this.isPlaying = true;
  51568. // Add tick behavior.
  51569. if (!hasBehavior(this)) { return; }
  51570. sceneEl.addBehavior(this);
  51571. };
  51572. }
  51573. /**
  51574. * Wrapper for defined remove method.
  51575. * Clean up memory.
  51576. *
  51577. * @param removeMethod {function} - Defined remove method.
  51578. */
  51579. function wrapRemove (removeMethod) {
  51580. return function remove () {
  51581. removeMethod.call(this);
  51582. this.objectPool.recycle(this.attrValue);
  51583. this.objectPool.recycle(this.oldData);
  51584. this.objectPool.recycle(this.parsingAttrValue);
  51585. this.attrValue = this.oldData = this.parsingAttrValue = undefined;
  51586. };
  51587. }
  51588. function isObject (value) {
  51589. return value && value.constructor === Object;
  51590. }
  51591. function isObjectOrArray (value) {
  51592. return value && (value.constructor === Object || value.constructor === Array);
  51593. }
  51594. },{"../utils/":178,"./scene/scenes":112,"./schema":114,"./system":116}],106:[function(_dereq_,module,exports){
  51595. var schema = _dereq_('./schema');
  51596. var processSchema = schema.process;
  51597. var geometries = module.exports.geometries = {}; // Registered geometries.
  51598. var geometryNames = module.exports.geometryNames = []; // Names of registered geometries.
  51599. var THREE = _dereq_('../lib/three');
  51600. /**
  51601. * Geometry class definition.
  51602. *
  51603. * Geometries extend the geometry component API to create and register geometry types.
  51604. */
  51605. var Geometry = module.exports.Geometry = function () {};
  51606. Geometry.prototype = {
  51607. /**
  51608. * Contains the type schema and defaults for the data values.
  51609. * Data is coerced into the types of the values of the defaults.
  51610. */
  51611. schema: {},
  51612. /**
  51613. * Init handler. Similar to attachedCallback.
  51614. * Called during shader initialization and is only run once.
  51615. */
  51616. init: function (data) {
  51617. this.geometry = new THREE.Geometry();
  51618. return this.geometry;
  51619. },
  51620. /**
  51621. * Update handler. Similar to attributeChangedCallback.
  51622. * Called whenever the associated geometry data changes.
  51623. *
  51624. * @param {object} data - New geometry data.
  51625. */
  51626. update: function (data) { /* no-op */ }
  51627. };
  51628. /**
  51629. * Registers a geometry to A-Frame.
  51630. *
  51631. * @param {string} name - Geometry name.
  51632. * @param {object} definition - Geometry property and methods.
  51633. * @returns {object} Geometry.
  51634. */
  51635. module.exports.registerGeometry = function (name, definition) {
  51636. var NewGeometry;
  51637. var proto = {};
  51638. // Format definition object to prototype object.
  51639. Object.keys(definition).forEach(function expandDefinition (key) {
  51640. proto[key] = {
  51641. value: definition[key],
  51642. writable: true
  51643. };
  51644. });
  51645. if (geometries[name]) {
  51646. throw new Error('The geometry `' + name + '` has been already registered');
  51647. }
  51648. NewGeometry = function () { Geometry.call(this); };
  51649. NewGeometry.prototype = Object.create(Geometry.prototype, proto);
  51650. NewGeometry.prototype.name = name;
  51651. NewGeometry.prototype.constructor = NewGeometry;
  51652. geometries[name] = {
  51653. Geometry: NewGeometry,
  51654. schema: processSchema(NewGeometry.prototype.schema)
  51655. };
  51656. geometryNames.push(name);
  51657. return NewGeometry;
  51658. };
  51659. },{"../lib/three":154,"./schema":114}],107:[function(_dereq_,module,exports){
  51660. var coordinates = _dereq_('../utils/coordinates');
  51661. var debug = _dereq_('debug');
  51662. var error = debug('core:propertyTypes:warn');
  51663. var warn = debug('core:propertyTypes:warn');
  51664. var propertyTypes = module.exports.propertyTypes = {};
  51665. var nonCharRegex = /[,> .[\]:]/;
  51666. var urlRegex = /\url\((.+)\)/;
  51667. // Built-in property types.
  51668. registerPropertyType('audio', '', assetParse);
  51669. registerPropertyType('array', [], arrayParse, arrayStringify);
  51670. registerPropertyType('asset', '', assetParse);
  51671. registerPropertyType('boolean', false, boolParse);
  51672. registerPropertyType('color', '#FFF', defaultParse, defaultStringify);
  51673. registerPropertyType('int', 0, intParse);
  51674. registerPropertyType('number', 0, numberParse);
  51675. registerPropertyType('map', '', assetParse);
  51676. registerPropertyType('model', '', assetParse);
  51677. registerPropertyType('selector', null, selectorParse, selectorStringify);
  51678. registerPropertyType('selectorAll', null, selectorAllParse, selectorAllStringify);
  51679. registerPropertyType('src', '', srcParse);
  51680. registerPropertyType('string', '', defaultParse, defaultStringify);
  51681. registerPropertyType('time', 0, intParse);
  51682. registerPropertyType('vec2', {x: 0, y: 0}, vecParse, coordinates.stringify);
  51683. registerPropertyType('vec3', {x: 0, y: 0, z: 0}, vecParse, coordinates.stringify);
  51684. registerPropertyType('vec4', {x: 0, y: 0, z: 0, w: 1}, vecParse, coordinates.stringify);
  51685. /**
  51686. * Register a parser for re-use such that when someone uses `type` in the schema,
  51687. * `schema.process` will set the property `parse` and `stringify`.
  51688. *
  51689. * @param {string} type - Type name.
  51690. * @param [defaultValue=null] -
  51691. * Default value to use if component does not define default value.
  51692. * @param {function} [parse=defaultParse] - Parse string function.
  51693. * @param {function} [stringify=defaultStringify] - Stringify to DOM function.
  51694. */
  51695. function registerPropertyType (type, defaultValue, parse, stringify) {
  51696. if ('type' in propertyTypes) {
  51697. error('Property type ' + type + ' is already registered.');
  51698. return;
  51699. }
  51700. propertyTypes[type] = {
  51701. default: defaultValue,
  51702. parse: parse || defaultParse,
  51703. stringify: stringify || defaultStringify
  51704. };
  51705. }
  51706. module.exports.registerPropertyType = registerPropertyType;
  51707. function arrayParse (value) {
  51708. if (Array.isArray(value)) { return value; }
  51709. if (!value || typeof value !== 'string') { return []; }
  51710. return value.split(',').map(trim);
  51711. function trim (str) { return str.trim(); }
  51712. }
  51713. function arrayStringify (value) {
  51714. return value.join(', ');
  51715. }
  51716. /**
  51717. * For general assets.
  51718. *
  51719. * @param {string} value - Can either be `url(<value>)`, an ID selector to an asset, or
  51720. * just string.
  51721. * @returns {string} Parsed value from `url(<value>)`, src from `<someasset src>`, or
  51722. * just string.
  51723. */
  51724. function assetParse (value) {
  51725. var el;
  51726. var parsedUrl;
  51727. // If an element was provided (e.g. canvas or video), just return it.
  51728. if (typeof value !== 'string') { return value; }
  51729. // Wrapped `url()` in case of data URI.
  51730. parsedUrl = value.match(urlRegex);
  51731. if (parsedUrl) { return parsedUrl[1]; }
  51732. // ID.
  51733. if (value.charAt(0) === '#') {
  51734. el = document.getElementById(value.substring(1));
  51735. if (el) {
  51736. // Pass through media elements. If we have the elements, we don't have to call
  51737. // three.js loaders which would re-request the assets.
  51738. if (el.tagName === 'CANVAS' || el.tagName === 'VIDEO' || el.tagName === 'IMG') {
  51739. return el;
  51740. }
  51741. return el.getAttribute('src');
  51742. }
  51743. warn('"' + value + '" asset not found.');
  51744. return;
  51745. }
  51746. // Non-wrapped url().
  51747. return value;
  51748. }
  51749. function defaultParse (value) {
  51750. return value;
  51751. }
  51752. function defaultStringify (value) {
  51753. if (value === null) { return 'null'; }
  51754. return value.toString();
  51755. }
  51756. function boolParse (value) {
  51757. return value !== 'false' && value !== false;
  51758. }
  51759. function intParse (value) {
  51760. return parseInt(value, 10);
  51761. }
  51762. function numberParse (value) {
  51763. return parseFloat(value, 10);
  51764. }
  51765. function selectorParse (value) {
  51766. if (!value) { return null; }
  51767. if (typeof value !== 'string') { return value; }
  51768. if (value[0] === '#' && !nonCharRegex.test(value)) {
  51769. // When selecting element by ID only, use getElementById for better performance.
  51770. // Don't match like #myId .child.
  51771. return document.getElementById(value.substring(1));
  51772. }
  51773. return document.querySelector(value);
  51774. }
  51775. function selectorAllParse (value) {
  51776. if (!value) { return null; }
  51777. if (typeof value !== 'string') { return value; }
  51778. return Array.prototype.slice.call(document.querySelectorAll(value), 0);
  51779. }
  51780. function selectorStringify (value) {
  51781. if (value.getAttribute) {
  51782. return '#' + value.getAttribute('id');
  51783. }
  51784. return defaultStringify(value);
  51785. }
  51786. function selectorAllStringify (value) {
  51787. if (value instanceof Array) {
  51788. return value.map(function (element) {
  51789. return '#' + element.getAttribute('id');
  51790. }).join(', ');
  51791. }
  51792. return defaultStringify(value);
  51793. }
  51794. function srcParse (value) {
  51795. warn('`src` property type is deprecated. Use `asset` instead.');
  51796. return assetParse(value);
  51797. }
  51798. function vecParse (value) {
  51799. return coordinates.parse(value, this.default);
  51800. }
  51801. /**
  51802. * Validate the default values in a schema to match their type.
  51803. *
  51804. * @param {string} type - Property type name.
  51805. * @param defaultVal - Property type default value.
  51806. * @returns {boolean} Whether default value is accurate given the type.
  51807. */
  51808. function isValidDefaultValue (type, defaultVal) {
  51809. if (type === 'audio' && typeof defaultVal !== 'string') { return false; }
  51810. if (type === 'array' && !Array.isArray(defaultVal)) { return false; }
  51811. if (type === 'asset' && typeof defaultVal !== 'string') { return false; }
  51812. if (type === 'boolean' && typeof defaultVal !== 'boolean') { return false; }
  51813. if (type === 'color' && typeof defaultVal !== 'string') { return false; }
  51814. if (type === 'int' && typeof defaultVal !== 'number') { return false; }
  51815. if (type === 'number' && typeof defaultVal !== 'number') { return false; }
  51816. if (type === 'map' && typeof defaultVal !== 'string') { return false; }
  51817. if (type === 'model' && typeof defaultVal !== 'string') { return false; }
  51818. if (type === 'selector' && typeof defaultVal !== 'string' &&
  51819. defaultVal !== null) { return false; }
  51820. if (type === 'selectorAll' && typeof defaultVal !== 'string' &&
  51821. defaultVal !== null) { return false; }
  51822. if (type === 'src' && typeof defaultVal !== 'string') { return false; }
  51823. if (type === 'string' && typeof defaultVal !== 'string') { return false; }
  51824. if (type === 'time' && typeof defaultVal !== 'number') { return false; }
  51825. if (type === 'vec2') { return isValidDefaultCoordinate(defaultVal, 2); }
  51826. if (type === 'vec3') { return isValidDefaultCoordinate(defaultVal, 3); }
  51827. if (type === 'vec4') { return isValidDefaultCoordinate(defaultVal, 4); }
  51828. return true;
  51829. }
  51830. module.exports.isValidDefaultValue = isValidDefaultValue;
  51831. /**
  51832. * Checks if default coordinates are valid.
  51833. *
  51834. * @param possibleCoordinates
  51835. * @param {number} dimensions - 2 for 2D Vector, 3 for 3D vector.
  51836. * @returns {boolean} Whether coordinates are parsed correctly.
  51837. */
  51838. function isValidDefaultCoordinate (possibleCoordinates, dimensions) {
  51839. if (possibleCoordinates === null) { return true; }
  51840. if (typeof possibleCoordinates !== 'object') { return false; }
  51841. if (Object.keys(possibleCoordinates).length !== dimensions) {
  51842. return false;
  51843. } else {
  51844. var x = possibleCoordinates.x;
  51845. var y = possibleCoordinates.y;
  51846. var z = possibleCoordinates.z;
  51847. var w = possibleCoordinates.w;
  51848. if (typeof x !== 'number' || typeof y !== 'number') { return false; }
  51849. if (dimensions > 2 && typeof z !== 'number') { return false; }
  51850. if (dimensions > 3 && typeof w !== 'number') { return false; }
  51851. }
  51852. return true;
  51853. }
  51854. module.exports.isValidDefaultCoordinate = isValidDefaultCoordinate;
  51855. },{"../utils/coordinates":173,"debug":8}],108:[function(_dereq_,module,exports){
  51856. /* global Promise, screen */
  51857. var initMetaTags = _dereq_('./metaTags').inject;
  51858. var initWakelock = _dereq_('./wakelock');
  51859. var loadingScreen = _dereq_('./loadingScreen');
  51860. var re = _dereq_('../a-register-element');
  51861. var scenes = _dereq_('./scenes');
  51862. var systems = _dereq_('../system').systems;
  51863. var THREE = _dereq_('../../lib/three');
  51864. var utils = _dereq_('../../utils/');
  51865. // Require after.
  51866. var AEntity = _dereq_('../a-entity');
  51867. var ANode = _dereq_('../a-node');
  51868. var initPostMessageAPI = _dereq_('./postMessage');
  51869. var bind = utils.bind;
  51870. var isIOS = utils.device.isIOS();
  51871. var isMobile = utils.device.isMobile();
  51872. var isWebXRAvailable = utils.device.isWebXRAvailable;
  51873. var registerElement = re.registerElement;
  51874. var warn = utils.debug('core:a-scene:warn');
  51875. /**
  51876. * Scene element, holds all entities.
  51877. *
  51878. * @member {array} behaviors - Component instances that have registered themselves to be
  51879. updated on every tick.
  51880. * @member {object} camera - three.js Camera object.
  51881. * @member {object} canvas
  51882. * @member {bool} isScene - Differentiates as scene entity as opposed to other entites.
  51883. * @member {bool} isMobile - Whether browser is mobile (via UA detection).
  51884. * @member {object} object3D - Root three.js Scene object.
  51885. * @member {object} renderer
  51886. * @member {bool} renderStarted
  51887. * @member {object} systems - Registered instantiated systems.
  51888. * @member {number} time
  51889. */
  51890. module.exports.AScene = registerElement('a-scene', {
  51891. prototype: Object.create(AEntity.prototype, {
  51892. createdCallback: {
  51893. value: function () {
  51894. this.isIOS = isIOS;
  51895. this.isMobile = isMobile;
  51896. this.hasWebXR = isWebXRAvailable;
  51897. this.isScene = true;
  51898. this.object3D = new THREE.Scene();
  51899. var self = this;
  51900. this.object3D.onAfterRender = function (renderer, scene, camera) {
  51901. // THREE may swap the camera used for the rendering if in VR, so we pass it to tock
  51902. if (self.isPlaying) { self.tock(self.time, self.delta, camera); }
  51903. };
  51904. this.render = bind(this.render, this);
  51905. this.systems = {};
  51906. this.systemNames = [];
  51907. this.time = this.delta = 0;
  51908. this.behaviors = {tick: [], tock: []};
  51909. this.hasLoaded = false;
  51910. this.isPlaying = false;
  51911. this.originalHTML = this.innerHTML;
  51912. this.renderTarget = null;
  51913. // Default components.
  51914. this.setAttribute('inspector', '');
  51915. this.setAttribute('keyboard-shortcuts', '');
  51916. this.setAttribute('screenshot', '');
  51917. this.setAttribute('vr-mode-ui', '');
  51918. }
  51919. },
  51920. addFullScreenStyles: {
  51921. value: function () {
  51922. document.documentElement.classList.add('a-fullscreen');
  51923. }
  51924. },
  51925. removeFullScreenStyles: {
  51926. value: function () {
  51927. document.documentElement.classList.remove('a-fullscreen');
  51928. }
  51929. },
  51930. attachedCallback: {
  51931. value: function () {
  51932. var self = this;
  51933. // Renderer initialization
  51934. setupCanvas(this);
  51935. this.setupRenderer();
  51936. this.resize();
  51937. this.addFullScreenStyles();
  51938. initPostMessageAPI(this);
  51939. initMetaTags(this);
  51940. initWakelock(this);
  51941. // Camera set up by camera system.
  51942. this.addEventListener('cameraready', function () {
  51943. self.attachedCallbackPostCamera();
  51944. });
  51945. this.initSystems();
  51946. }
  51947. },
  51948. attachedCallbackPostCamera: {
  51949. value: function () {
  51950. var resize;
  51951. var self = this;
  51952. resize = bind(this.resize, this);
  51953. window.addEventListener('load', resize);
  51954. window.addEventListener('resize', function () {
  51955. // Workaround for a Webkit bug (https://bugs.webkit.org/show_bug.cgi?id=170595)
  51956. // where the window does not contain the correct viewport size
  51957. // after an orientation change. The window size is correct if the operation
  51958. // is postponed a few milliseconds.
  51959. // self.resize can be called directly once the bug above is fixed.
  51960. if (self.isIOS) {
  51961. setTimeout(resize, 100);
  51962. } else {
  51963. resize();
  51964. }
  51965. });
  51966. this.play();
  51967. // Add to scene index.
  51968. scenes.push(this);
  51969. // Handler to exit VR (e.g., Oculus Browser back button).
  51970. this.onVRPresentChangeBound = bind(this.onVRPresentChange, this);
  51971. window.addEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  51972. // bind functions
  51973. this.enterVRBound = function () { self.enterVR(); };
  51974. this.exitVRBound = function () { self.exitVR(); };
  51975. this.exitVRTrueBound = function () { self.exitVR(true); };
  51976. this.pointerRestrictedBound = function () { self.pointerRestricted(); };
  51977. this.pointerUnrestrictedBound = function () { self.pointerUnrestricted(); };
  51978. // Enter VR on `vrdisplayactivate` (e.g. putting on Rift headset).
  51979. window.addEventListener('vrdisplayactivate', this.enterVRBound);
  51980. // Exit VR on `vrdisplaydeactivate` (e.g. taking off Rift headset).
  51981. window.addEventListener('vrdisplaydeactivate', this.exitVRBound);
  51982. // Exit VR on `vrdisplaydisconnect` (e.g. unplugging Rift headset).
  51983. window.addEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  51984. // Register for mouse restricted events while in VR
  51985. // (e.g. mouse no longer available on desktop 2D view)
  51986. window.addEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  51987. // Register for mouse unrestricted events while in VR
  51988. // (e.g. mouse once again available on desktop 2D view)
  51989. window.addEventListener('vrdisplaypointerunrestricted', this.pointerUnrestrictedBound);
  51990. },
  51991. writable: window.debug
  51992. },
  51993. /**
  51994. * Initialize all systems.
  51995. */
  51996. initSystems: {
  51997. value: function () {
  51998. var name;
  51999. // Initialize camera system first.
  52000. this.initSystem('camera');
  52001. for (name in systems) {
  52002. if (name === 'camera') { continue; }
  52003. this.initSystem(name);
  52004. }
  52005. }
  52006. },
  52007. /**
  52008. * Initialize a system.
  52009. */
  52010. initSystem: {
  52011. value: function (name) {
  52012. if (this.systems[name]) { return; }
  52013. this.systems[name] = new systems[name](this);
  52014. this.systemNames.push(name);
  52015. }
  52016. },
  52017. /**
  52018. * Shut down scene on detach.
  52019. */
  52020. detachedCallback: {
  52021. value: function () {
  52022. // Remove from scene index.
  52023. var sceneIndex = scenes.indexOf(this);
  52024. scenes.splice(sceneIndex, 1);
  52025. window.removeEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  52026. window.removeEventListener('vrdisplayactivate', this.enterVRBound);
  52027. window.removeEventListener('vrdisplaydeactivate', this.exitVRBound);
  52028. window.removeEventListener('vrdisplayconnect', this.enterVRBound);
  52029. window.removeEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  52030. window.removeEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  52031. window.removeEventListener('vrdisplaypointerunrestricted', this.pointerUnrestrictedBound);
  52032. }
  52033. },
  52034. /**
  52035. * Add ticks and tocks.
  52036. *
  52037. * @param {object} behavior - A component.
  52038. */
  52039. addBehavior: {
  52040. value: function (behavior) {
  52041. var behaviorArr;
  52042. var behaviors = this.behaviors;
  52043. var behaviorType;
  52044. // Check if behavior has tick and/or tock and add the behavior to the appropriate list.
  52045. for (behaviorType in behaviors) {
  52046. if (!behavior[behaviorType]) { continue; }
  52047. behaviorArr = this.behaviors[behaviorType];
  52048. if (behaviorArr.indexOf(behavior) === -1) {
  52049. behaviorArr.push(behavior);
  52050. }
  52051. }
  52052. }
  52053. },
  52054. /**
  52055. * For tests.
  52056. */
  52057. getPointerLockElement: {
  52058. value: function () {
  52059. return document.pointerLockElement;
  52060. },
  52061. writable: window.debug
  52062. },
  52063. /**
  52064. * For tests.
  52065. */
  52066. checkHeadsetConnected: {
  52067. value: utils.device.checkHeadsetConnected,
  52068. writable: window.debug
  52069. },
  52070. /**
  52071. * Call `requestPresent` if WebVR or WebVR polyfill.
  52072. * Call `requestFullscreen` on desktop.
  52073. * Handle events, states, fullscreen styles.
  52074. *
  52075. * @returns {Promise}
  52076. */
  52077. enterVR: {
  52078. value: function () {
  52079. var self = this;
  52080. var vrDisplay;
  52081. var vrManager = self.renderer.vr;
  52082. // Don't enter VR if already in VR.
  52083. if (this.is('vr-mode')) { return Promise.resolve('Already in VR.'); }
  52084. // Enter VR via WebVR API.
  52085. if (this.checkHeadsetConnected() || this.isMobile) {
  52086. vrDisplay = utils.device.getVRDisplay();
  52087. vrManager.setDevice(vrDisplay);
  52088. vrManager.enabled = true;
  52089. if (this.hasWebXR) {
  52090. if (this.xrSession) { this.xrSession.removeEventListener('end', this.exitVRBound); }
  52091. vrDisplay.requestSession({immersive: true, exclusive: true}).then(enterXRSuccess);
  52092. } else {
  52093. if (vrDisplay.isPresenting) {
  52094. enterVRSuccess();
  52095. return Promise.resolve();
  52096. }
  52097. return vrDisplay.requestPresent([{source: this.canvas}]).then(enterVRSuccess, enterVRFailure);
  52098. }
  52099. return Promise.resolve();
  52100. }
  52101. enterVRSuccess();
  52102. return Promise.resolve();
  52103. function enterXRSuccess (xrSession) {
  52104. self.xrSession = xrSession;
  52105. vrManager.setSession(xrSession);
  52106. xrSession.addEventListener('end', self.exitVRBound);
  52107. xrSession.requestFrameOfReference('stage').then(function (frameOfReference) {
  52108. self.frameOfReference = frameOfReference;
  52109. });
  52110. self.addState('vr-mode');
  52111. self.emit('enter-vr', {target: self});
  52112. // Lock to landscape orientation on mobile.
  52113. if (self.isMobile && screen.orientation && screen.orientation.lock) {
  52114. screen.orientation.lock('landscape');
  52115. }
  52116. self.addFullScreenStyles();
  52117. // On mobile, the polyfill handles fullscreen.
  52118. // TODO: 07/16 Chromium builds break when `requestFullscreen`ing on a canvas
  52119. // that we are also `requestPresent`ing. Until then, don't fullscreen if headset
  52120. // connected.
  52121. if (!self.isMobile && !self.checkHeadsetConnected()) {
  52122. requestFullscreen(self.canvas);
  52123. }
  52124. self.resize();
  52125. }
  52126. function enterVRSuccess () {
  52127. self.addState('vr-mode');
  52128. self.emit('enter-vr', {target: self});
  52129. // Lock to landscape orientation on mobile.
  52130. if (self.isMobile && screen.orientation && screen.orientation.lock) {
  52131. screen.orientation.lock('landscape');
  52132. }
  52133. self.addFullScreenStyles();
  52134. // On mobile, the polyfill handles fullscreen.
  52135. // TODO: 07/16 Chromium builds break when `requestFullscreen`ing on a canvas
  52136. // that we are also `requestPresent`ing. Until then, don't fullscreen if headset
  52137. // connected.
  52138. if (!self.isMobile && !self.checkHeadsetConnected()) {
  52139. requestFullscreen(self.canvas);
  52140. }
  52141. self.resize();
  52142. }
  52143. function enterVRFailure (err) {
  52144. if (err && err.message) {
  52145. throw new Error('Failed to enter VR mode (`requestPresent`): ' + err.message);
  52146. } else {
  52147. throw new Error('Failed to enter VR mode (`requestPresent`).');
  52148. }
  52149. }
  52150. },
  52151. writable: true
  52152. },
  52153. /**
  52154. * Call `exitPresent` if WebVR / WebXR or WebVR polyfill.
  52155. * Handle events, states, fullscreen styles.
  52156. *
  52157. * @returns {Promise}
  52158. */
  52159. exitVR: {
  52160. value: function () {
  52161. var self = this;
  52162. var vrDisplay;
  52163. var vrManager = this.renderer.vr;
  52164. // Don't exit VR if not in VR.
  52165. if (!this.is('vr-mode')) { return Promise.resolve('Not in VR.'); }
  52166. // Handle exiting VR if not yet already and in a headset or polyfill.
  52167. if (this.checkHeadsetConnected() || this.isMobile) {
  52168. vrManager.enabled = false;
  52169. vrDisplay = utils.device.getVRDisplay();
  52170. if (this.hasWebXR) {
  52171. this.xrSession.removeEventListener('end', this.exitVRBound);
  52172. this.xrSession.end();
  52173. vrManager.setSession(null);
  52174. } else {
  52175. if (vrDisplay.isPresenting) {
  52176. return vrDisplay.exitPresent().then(exitVRSuccess, exitVRFailure);
  52177. }
  52178. }
  52179. } else {
  52180. exitFullscreen();
  52181. }
  52182. // Handle exiting VR in all other cases (2D fullscreen, external exit VR event).
  52183. exitVRSuccess();
  52184. return Promise.resolve();
  52185. function exitVRSuccess () {
  52186. self.removeState('vr-mode');
  52187. // Lock to landscape orientation on mobile.
  52188. if (self.isMobile && screen.orientation && screen.orientation.unlock) {
  52189. screen.orientation.unlock();
  52190. }
  52191. // Exiting VR in embedded mode, no longer need fullscreen styles.
  52192. if (self.hasAttribute('embedded')) { self.removeFullScreenStyles(); }
  52193. self.resize();
  52194. if (self.isIOS) { utils.forceCanvasResizeSafariMobile(self.canvas); }
  52195. self.emit('exit-vr', {target: self});
  52196. }
  52197. function exitVRFailure (err) {
  52198. if (err && err.message) {
  52199. throw new Error('Failed to exit VR mode (`exitPresent`): ' + err.message);
  52200. } else {
  52201. throw new Error('Failed to exit VR mode (`exitPresent`).');
  52202. }
  52203. }
  52204. },
  52205. writable: true
  52206. },
  52207. pointerRestricted: {
  52208. value: function () {
  52209. if (this.canvas) {
  52210. var pointerLockElement = this.getPointerLockElement();
  52211. if (pointerLockElement && pointerLockElement !== this.canvas && document.exitPointerLock) {
  52212. // Recreate pointer lock on the canvas, if taken on another element.
  52213. document.exitPointerLock();
  52214. }
  52215. if (this.canvas.requestPointerLock) {
  52216. this.canvas.requestPointerLock();
  52217. }
  52218. }
  52219. }
  52220. },
  52221. pointerUnrestricted: {
  52222. value: function () {
  52223. var pointerLockElement = this.getPointerLockElement();
  52224. if (pointerLockElement && pointerLockElement === this.canvas && document.exitPointerLock) {
  52225. document.exitPointerLock();
  52226. }
  52227. }
  52228. },
  52229. /**
  52230. * Handle `vrdisplaypresentchange` event for exiting VR through other means than
  52231. * `<ESC>` key. For example, GearVR back button on Oculus Browser.
  52232. */
  52233. onVRPresentChange: {
  52234. value: function (evt) {
  52235. // Polyfill places display inside the detail property
  52236. var display = evt.display || evt.detail.display;
  52237. // Entering VR.
  52238. if (display.isPresenting) {
  52239. this.enterVR();
  52240. return;
  52241. }
  52242. // Exiting VR.
  52243. this.exitVR();
  52244. }
  52245. },
  52246. /**
  52247. * Wraps Entity.getAttribute to take into account for systems.
  52248. * If system exists, then return system data rather than possible component data.
  52249. */
  52250. getAttribute: {
  52251. value: function (attr) {
  52252. var system = this.systems[attr];
  52253. if (system) { return system.data; }
  52254. return AEntity.prototype.getAttribute.call(this, attr);
  52255. }
  52256. },
  52257. /**
  52258. * `getAttribute` used to be `getDOMAttribute` and `getComputedAttribute` used to be
  52259. * what `getAttribute` is now. Now legacy code.
  52260. */
  52261. getComputedAttribute: {
  52262. value: function (attr) {
  52263. warn('`getComputedAttribute` is deprecated. Use `getAttribute` instead.');
  52264. this.getAttribute(attr);
  52265. }
  52266. },
  52267. /**
  52268. * Wraps Entity.getDOMAttribute to take into account for systems.
  52269. * If system exists, then return system data rather than possible component data.
  52270. */
  52271. getDOMAttribute: {
  52272. value: function (attr) {
  52273. var system = this.systems[attr];
  52274. if (system) { return system.data; }
  52275. return AEntity.prototype.getDOMAttribute.call(this, attr);
  52276. }
  52277. },
  52278. /**
  52279. * Wrap Entity.setAttribute to take into account for systems.
  52280. * If system exists, then skip component initialization checks and do a normal
  52281. * setAttribute.
  52282. */
  52283. setAttribute: {
  52284. value: function (attr, value, componentPropValue) {
  52285. var system = this.systems[attr];
  52286. if (system) {
  52287. ANode.prototype.setAttribute.call(this, attr, value);
  52288. system.updateProperties(value);
  52289. return;
  52290. }
  52291. AEntity.prototype.setAttribute.call(this, attr, value, componentPropValue);
  52292. }
  52293. },
  52294. /**
  52295. * @param {object} behavior - A component.
  52296. */
  52297. removeBehavior: {
  52298. value: function (behavior) {
  52299. var behaviorArr;
  52300. var behaviorType;
  52301. var behaviors = this.behaviors;
  52302. var index;
  52303. // Check if behavior has tick and/or tock and remove the behavior from the appropriate
  52304. // array.
  52305. for (behaviorType in behaviors) {
  52306. if (!behavior[behaviorType]) { continue; }
  52307. behaviorArr = this.behaviors[behaviorType];
  52308. index = behaviorArr.indexOf(behavior);
  52309. if (index !== -1) { behaviorArr.splice(index, 1); }
  52310. }
  52311. }
  52312. },
  52313. resize: {
  52314. value: function () {
  52315. var camera = this.camera;
  52316. var canvas = this.canvas;
  52317. var embedded;
  52318. var isVRPresenting;
  52319. var size;
  52320. var vrDevice;
  52321. vrDevice = this.renderer.vr.getDevice();
  52322. isVRPresenting = this.renderer.vr.enabled && vrDevice && vrDevice.isPresenting;
  52323. // Do not update renderer, if a camera or a canvas have not been injected.
  52324. // In VR mode, three handles canvas resize based on the dimensions returned by
  52325. // the getEyeParameters function of the WebVR API. These dimensions are independent of
  52326. // the window size, therefore should not be overwritten with the window's width and
  52327. // height, // except when in fullscreen mode.
  52328. if (!camera || !canvas || (this.is('vr-mode') && (this.isMobile || isVRPresenting))) {
  52329. return;
  52330. }
  52331. // Update camera.
  52332. embedded = this.getAttribute('embedded') && !this.is('vr-mode');
  52333. size = getCanvasSize(canvas, embedded, this.maxCanvasSize, this.is('vr-mode'));
  52334. camera.aspect = size.width / size.height;
  52335. camera.updateProjectionMatrix();
  52336. // Notify renderer of size change.
  52337. this.renderer.setSize(size.width, size.height, false);
  52338. this.emit('rendererresize', null, false);
  52339. },
  52340. writable: true
  52341. },
  52342. setupRenderer: {
  52343. value: function () {
  52344. var self = this;
  52345. var renderer;
  52346. var rendererAttr;
  52347. var rendererAttrString;
  52348. var rendererConfig;
  52349. rendererConfig = {alpha: true, antialias: !isMobile, canvas: this.canvas, logarithmicDepthBuffer: false};
  52350. if (this.hasAttribute('antialias')) {
  52351. rendererConfig.antialias = this.getAttribute('antialias') === 'true';
  52352. }
  52353. if (this.hasAttribute('logarithmicDepthBuffer')) {
  52354. rendererConfig.logarithmicDepthBuffer = this.getAttribute('logarithmicDepthBuffer') === 'true';
  52355. }
  52356. this.maxCanvasSize = {height: 1920, width: 1920};
  52357. if (this.hasAttribute('renderer')) {
  52358. rendererAttrString = this.getAttribute('renderer');
  52359. rendererAttr = utils.styleParser.parse(rendererAttrString);
  52360. if (rendererAttr.antialias && rendererAttr.antialias !== 'auto') {
  52361. rendererConfig.antialias = rendererAttr.antialias === 'true';
  52362. }
  52363. this.maxCanvasSize = {
  52364. width: rendererAttr.maxCanvasWidth
  52365. ? parseInt(rendererAttr.maxCanvasWidth)
  52366. : this.maxCanvasSize.width,
  52367. height: rendererAttr.maxCanvasHeight
  52368. ? parseInt(rendererAttr.maxCanvasHeight)
  52369. : this.maxCanvasSize.height
  52370. };
  52371. }
  52372. renderer = this.renderer = new THREE.WebGLRenderer(rendererConfig);
  52373. renderer.setPixelRatio(window.devicePixelRatio);
  52374. renderer.sortObjects = false;
  52375. if (this.camera) { renderer.vr.setPoseTarget(this.camera.el.object3D); }
  52376. this.addEventListener('camera-set-active', function () {
  52377. renderer.vr.setPoseTarget(self.camera.el.object3D);
  52378. });
  52379. loadingScreen.setup(this, getCanvasSize);
  52380. },
  52381. writable: window.debug
  52382. },
  52383. /**
  52384. * Handler attached to elements to help scene know when to kick off.
  52385. * Scene waits for all entities to load.
  52386. */
  52387. play: {
  52388. value: function () {
  52389. var self = this;
  52390. var sceneEl = this;
  52391. if (this.renderStarted) {
  52392. AEntity.prototype.play.call(this);
  52393. return;
  52394. }
  52395. this.addEventListener('loaded', function () {
  52396. AEntity.prototype.play.call(this); // .play() *before* render.
  52397. if (sceneEl.renderStarted) { return; }
  52398. sceneEl.resize();
  52399. // Kick off render loop.
  52400. if (sceneEl.renderer) {
  52401. if (window.performance) { window.performance.mark('render-started'); }
  52402. sceneEl.clock = new THREE.Clock();
  52403. loadingScreen.remove();
  52404. sceneEl.renderer.setAnimationLoop(this.render);
  52405. sceneEl.render();
  52406. sceneEl.renderStarted = true;
  52407. sceneEl.emit('renderstart');
  52408. }
  52409. });
  52410. // setTimeout to wait for all nodes to attach and run their callbacks.
  52411. setTimeout(function () {
  52412. AEntity.prototype.load.call(self);
  52413. });
  52414. }
  52415. },
  52416. /**
  52417. * Wrap `updateComponent` to not initialize the component if the component has a system
  52418. * (aframevr/aframe#2365).
  52419. */
  52420. updateComponent: {
  52421. value: function (componentName) {
  52422. if (componentName in systems) { return; }
  52423. AEntity.prototype.updateComponent.apply(this, arguments);
  52424. }
  52425. },
  52426. /**
  52427. * Behavior-updater meant to be called from scene render.
  52428. * Abstracted to a different function to facilitate unit testing (`scene.tick()`) without
  52429. * needing to render.
  52430. */
  52431. tick: {
  52432. value: function (time, timeDelta) {
  52433. var i;
  52434. var systems = this.systems;
  52435. // Components.
  52436. for (i = 0; i < this.behaviors.tick.length; i++) {
  52437. if (!this.behaviors.tick[i].el.isPlaying) { continue; }
  52438. this.behaviors.tick[i].tick(time, timeDelta);
  52439. }
  52440. // Systems.
  52441. for (i = 0; i < this.systemNames.length; i++) {
  52442. if (!systems[this.systemNames[i]].tick) { continue; }
  52443. systems[this.systemNames[i]].tick(time, timeDelta);
  52444. }
  52445. }
  52446. },
  52447. /**
  52448. * Behavior-updater meant to be called after scene render for post processing purposes.
  52449. * Abstracted to a different function to facilitate unit testing (`scene.tock()`) without
  52450. * needing to render.
  52451. */
  52452. tock: {
  52453. value: function (time, timeDelta, camera) {
  52454. var i;
  52455. var systems = this.systems;
  52456. // Components.
  52457. for (i = 0; i < this.behaviors.tock.length; i++) {
  52458. if (!this.behaviors.tock[i].el.isPlaying) { continue; }
  52459. this.behaviors.tock[i].tock(time, timeDelta, camera);
  52460. }
  52461. // Systems.
  52462. for (i = 0; i < this.systemNames.length; i++) {
  52463. if (!systems[this.systemNames[i]].tock) { continue; }
  52464. systems[this.systemNames[i]].tock(time, timeDelta, camera);
  52465. }
  52466. }
  52467. },
  52468. /**
  52469. * The render loop.
  52470. *
  52471. * Updates animations.
  52472. * Updates behaviors.
  52473. * Renders with request animation frame.
  52474. */
  52475. render: {
  52476. value: function (time, frame) {
  52477. var renderer = this.renderer;
  52478. this.frame = frame;
  52479. this.delta = this.clock.getDelta() * 1000;
  52480. this.time = this.clock.elapsedTime * 1000;
  52481. if (this.isPlaying) { this.tick(this.time, this.delta); }
  52482. renderer.render(this.object3D, this.camera, this.renderTarget);
  52483. },
  52484. writable: true
  52485. }
  52486. })
  52487. });
  52488. /**
  52489. * Return the canvas size where the scene will be rendered.
  52490. * Will be always the window size except when the scene is embedded.
  52491. * The parent size (less than max size) will be returned in that case.
  52492. *
  52493. * @param {object} canvasEl - the canvas element
  52494. * @param {boolean} embedded - Is the scene embedded?
  52495. * @param {object} max - Max size parameters
  52496. * @param {boolean} isVR - If in VR
  52497. */
  52498. function getCanvasSize (canvasEl, embedded, maxSize, isVR) {
  52499. if (embedded) {
  52500. return {
  52501. height: canvasEl.parentElement.offsetHeight,
  52502. width: canvasEl.parentElement.offsetWidth
  52503. };
  52504. }
  52505. return getMaxSize(maxSize, isVR);
  52506. }
  52507. /**
  52508. * Return the canvas size. Will be the window size unless that size is greater than the
  52509. * maximum size (1920x1920 by default). The constrained size will be returned in that case,
  52510. * maintaining aspect ratio
  52511. *
  52512. * @param {object} maxSize - Max size parameters (width and height).
  52513. * @param {boolean} isVR - If in VR.
  52514. * @returns {object} Width and height.
  52515. */
  52516. function getMaxSize (maxSize, isVR) {
  52517. var aspectRatio;
  52518. var size;
  52519. var pixelRatio = window.devicePixelRatio;
  52520. size = {height: document.body.offsetHeight, width: document.body.offsetWidth};
  52521. if (!maxSize || isVR || (maxSize.width === -1 && maxSize.height === -1)) {
  52522. return size;
  52523. }
  52524. if (size.width * pixelRatio < maxSize.width &&
  52525. size.height * pixelRatio < maxSize.height) {
  52526. return size;
  52527. }
  52528. aspectRatio = size.width / size.height;
  52529. if ((size.width * pixelRatio) > maxSize.width && maxSize.width !== -1) {
  52530. size.width = Math.round(maxSize.width / pixelRatio);
  52531. size.height = Math.round(maxSize.width / aspectRatio / pixelRatio);
  52532. }
  52533. if ((size.height * pixelRatio) > maxSize.height && maxSize.height !== -1) {
  52534. size.height = Math.round(maxSize.height / pixelRatio);
  52535. size.width = Math.round(maxSize.height * aspectRatio / pixelRatio);
  52536. }
  52537. return size;
  52538. }
  52539. function requestFullscreen (canvas) {
  52540. var requestFullscreen =
  52541. canvas.requestFullscreen ||
  52542. canvas.webkitRequestFullscreen ||
  52543. canvas.mozRequestFullScreen || // The capitalized `S` is not a typo.
  52544. canvas.msRequestFullscreen;
  52545. requestFullscreen.apply(canvas);
  52546. }
  52547. function exitFullscreen () {
  52548. if (document.exitFullscreen) {
  52549. document.exitFullscreen();
  52550. } else if (document.mozCancelFullScreen) {
  52551. document.mozCancelFullScreen();
  52552. } else if (document.webkitExitFullscreen) {
  52553. document.webkitExitFullscreen();
  52554. }
  52555. }
  52556. function setupCanvas (sceneEl) {
  52557. var canvasEl;
  52558. canvasEl = document.createElement('canvas');
  52559. canvasEl.classList.add('a-canvas');
  52560. // Mark canvas as provided/injected by A-Frame.
  52561. canvasEl.dataset.aframeCanvas = true;
  52562. sceneEl.appendChild(canvasEl);
  52563. document.addEventListener('fullscreenchange', onFullScreenChange);
  52564. document.addEventListener('mozfullscreenchange', onFullScreenChange);
  52565. document.addEventListener('webkitfullscreenchange', onFullScreenChange);
  52566. // Prevent overscroll on mobile.
  52567. canvasEl.addEventListener('touchmove', function (event) { event.preventDefault(); });
  52568. // Set canvas on scene.
  52569. sceneEl.canvas = canvasEl;
  52570. sceneEl.emit('render-target-loaded', {target: canvasEl});
  52571. // For unknown reasons a synchronous resize does not work on desktop when
  52572. // entering/exiting fullscreen.
  52573. setTimeout(bind(sceneEl.resize, sceneEl), 0);
  52574. function onFullScreenChange () {
  52575. var fullscreenEl =
  52576. document.fullscreenElement ||
  52577. document.mozFullScreenElement ||
  52578. document.webkitFullscreenElement;
  52579. // No fullscren element === exit fullscreen
  52580. if (!fullscreenEl) { sceneEl.exitVR(); }
  52581. document.activeElement.blur();
  52582. document.body.focus();
  52583. }
  52584. }
  52585. module.exports.setupCanvas = setupCanvas; // For testing.
  52586. },{"../../lib/three":154,"../../utils/":178,"../a-entity":101,"../a-node":103,"../a-register-element":104,"../system":116,"./loadingScreen":109,"./metaTags":110,"./postMessage":111,"./scenes":112,"./wakelock":113}],109:[function(_dereq_,module,exports){
  52587. /* global THREE */
  52588. var utils = _dereq_('../../utils/');
  52589. var styleParser = utils.styleParser;
  52590. var sceneEl;
  52591. var titleEl;
  52592. var getSceneCanvasSize;
  52593. var ATTR_NAME = 'loading-screen';
  52594. var LOADER_TITLE_CLASS = 'a-loader-title';
  52595. // It catches vrdisplayactivate early to ensure we can enter VR mode after the scene loads.
  52596. window.addEventListener('vrdisplayactivate', function () {
  52597. var vrManager = sceneEl.renderer.vr;
  52598. var vrDisplay = utils.device.getVRDisplay();
  52599. vrManager.setDevice(vrDisplay);
  52600. vrManager.enabled = true;
  52601. if (!vrDisplay.isPresenting) {
  52602. return vrDisplay.requestPresent([{source: sceneEl.canvas}]).then(function () {}, function () {});
  52603. }
  52604. });
  52605. module.exports.setup = function setup (el, getCanvasSize) {
  52606. sceneEl = el;
  52607. getSceneCanvasSize = getCanvasSize;
  52608. var loaderAttribute = sceneEl.hasAttribute(ATTR_NAME) ? styleParser.parse(sceneEl.getAttribute(ATTR_NAME)) : undefined;
  52609. var dotsColor = loaderAttribute && loaderAttribute.dotsColor || 'white';
  52610. var backgroundColor = loaderAttribute && loaderAttribute.backgroundColor || '#24CAFF';
  52611. var loaderEnabled = loaderAttribute === undefined || loaderAttribute.enabled === true || loaderAttribute.enabled === undefined; // true default
  52612. var loaderScene;
  52613. var sphereGeometry;
  52614. var sphereMaterial;
  52615. var sphereMesh1;
  52616. var sphereMesh2;
  52617. var sphereMesh3;
  52618. var camera;
  52619. var clock;
  52620. var time;
  52621. var render;
  52622. if (!loaderEnabled) { return; }
  52623. // Setup Scene.
  52624. loaderScene = new THREE.Scene();
  52625. sphereGeometry = new THREE.SphereGeometry(0.20, 36, 18, 0, 2 * Math.PI, 0, Math.PI);
  52626. sphereMaterial = new THREE.MeshBasicMaterial({color: dotsColor});
  52627. sphereMesh1 = new THREE.Mesh(sphereGeometry, sphereMaterial);
  52628. sphereMesh2 = sphereMesh1.clone();
  52629. sphereMesh3 = sphereMesh1.clone();
  52630. camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 0.0005, 10000);
  52631. clock = new THREE.Clock();
  52632. time = 0;
  52633. render = function () {
  52634. sceneEl.renderer.render(loaderScene, camera);
  52635. time = clock.getElapsedTime() % 4;
  52636. sphereMesh1.visible = time >= 1;
  52637. sphereMesh2.visible = time >= 2;
  52638. sphereMesh3.visible = time >= 3;
  52639. };
  52640. loaderScene.background = new THREE.Color(backgroundColor);
  52641. loaderScene.add(camera);
  52642. sphereMesh1.position.set(-1, 0, -15);
  52643. sphereMesh2.position.set(0, 0, -15);
  52644. sphereMesh3.position.set(1, 0, -15);
  52645. camera.add(sphereMesh1);
  52646. camera.add(sphereMesh2);
  52647. camera.add(sphereMesh3);
  52648. setupTitle();
  52649. // Delay 200ms to avoid loader flashes.
  52650. setTimeout(function () {
  52651. if (sceneEl.hasLoaded) { return; }
  52652. resize(camera);
  52653. titleEl.style.display = 'block';
  52654. window.addEventListener('resize', function () { resize(camera); });
  52655. sceneEl.renderer.setAnimationLoop(render);
  52656. }, 200);
  52657. };
  52658. module.exports.remove = function remove () {
  52659. window.removeEventListener('resize', resize);
  52660. if (!titleEl) { return; }
  52661. // Hide title.
  52662. titleEl.style.display = 'none';
  52663. };
  52664. function resize (camera) {
  52665. var size = getSceneCanvasSize(sceneEl.canvas, false, sceneEl.maxCanvasSize, sceneEl.is('vr-mode'));
  52666. camera.aspect = size.width / size.height;
  52667. camera.updateProjectionMatrix();
  52668. // Notify renderer of size change.
  52669. sceneEl.renderer.setSize(size.width, size.height, false);
  52670. }
  52671. function setupTitle () {
  52672. titleEl = document.createElement('div');
  52673. titleEl.className = LOADER_TITLE_CLASS;
  52674. titleEl.innerHTML = document.title;
  52675. titleEl.style.display = 'none';
  52676. sceneEl.appendChild(titleEl);
  52677. }
  52678. },{"../../utils/":178}],110:[function(_dereq_,module,exports){
  52679. var constants = _dereq_('../../constants/');
  52680. var extend = _dereq_('../../utils').extend;
  52681. var MOBILE_HEAD_TAGS = module.exports.MOBILE_HEAD_TAGS = [
  52682. Meta({name: 'viewport', content: 'width=device-width,initial-scale=1,maximum-scale=1,shrink-to-fit=no,user-scalable=no,minimal-ui'}),
  52683. // W3C-standardised meta tags.
  52684. Meta({name: 'mobile-web-app-capable', content: 'yes'}),
  52685. Meta({name: 'theme-color', content: 'black'})
  52686. ];
  52687. var MOBILE_IOS_HEAD_TAGS = [
  52688. // iOS-specific meta tags for fullscreen when pinning to homescreen.
  52689. Meta({name: 'apple-mobile-web-app-capable', content: 'yes'}),
  52690. Meta({name: 'apple-mobile-web-app-status-bar-style', content: 'black'}),
  52691. Link({rel: 'apple-touch-icon', href: 'https://aframe.io/images/aframe-logo-152.png'})
  52692. ];
  52693. function Meta (attrs) {
  52694. return {
  52695. tagName: 'meta',
  52696. attributes: attrs,
  52697. exists: function () { return document.querySelector('meta[name="' + attrs.name + '"]'); }
  52698. };
  52699. }
  52700. function Link (attrs) {
  52701. return {
  52702. tagName: 'link',
  52703. attributes: attrs,
  52704. exists: function () { return document.querySelector('link[rel="' + attrs.rel + '"]'); }
  52705. };
  52706. }
  52707. /**
  52708. * Injects the necessary metatags in the document for mobile support:
  52709. * 1. Prevent the user to zoom in the document.
  52710. * 2. Ensure that window.innerWidth and window.innerHeight have the correct
  52711. * values and the canvas is properly scaled.
  52712. * 3. To allow fullscreen mode when pinning a web app on the home screen on
  52713. * iOS.
  52714. * Adapted from https://www.reddit.com/r/web_design/comments/3la04p/
  52715. *
  52716. * @param {object} scene - Scene element
  52717. * @returns {Array}
  52718. */
  52719. module.exports.inject = function injectHeadTags (scene) {
  52720. var headEl = document.head;
  52721. var headScriptEl = headEl.querySelector('script');
  52722. var tag;
  52723. var headTags = [];
  52724. MOBILE_HEAD_TAGS.forEach(createAndInjectTag);
  52725. if (scene.isIOS) {
  52726. MOBILE_IOS_HEAD_TAGS.forEach(createAndInjectTag);
  52727. }
  52728. return headTags;
  52729. function createAndInjectTag (tagObj) {
  52730. if (!tagObj || tagObj.exists()) { return; }
  52731. tag = createTag(tagObj);
  52732. if (!tag) { return; }
  52733. if (headScriptEl) {
  52734. headScriptEl.parentNode.insertBefore(tag, headScriptEl);
  52735. } else {
  52736. headEl.appendChild(tag);
  52737. }
  52738. headTags.push(tag);
  52739. }
  52740. };
  52741. function createTag (tagObj) {
  52742. if (!tagObj || !tagObj.tagName) { return; }
  52743. var meta = document.createElement(tagObj.tagName);
  52744. meta.setAttribute(constants.AFRAME_INJECTED, '');
  52745. return extend(meta, tagObj.attributes);
  52746. }
  52747. },{"../../constants/":97,"../../utils":178}],111:[function(_dereq_,module,exports){
  52748. var bind = _dereq_('../../utils/bind');
  52749. var isIframed = _dereq_('../../utils/').isIframed;
  52750. /**
  52751. * Provides a post message API for scenes contained
  52752. * in an iframe.
  52753. */
  52754. module.exports = function initPostMessageAPI (scene) {
  52755. // Handles fullscreen behavior when inside an iframe.
  52756. if (!isIframed()) { return; }
  52757. // postMessage API handler
  52758. window.addEventListener('message', bind(postMessageAPIHandler, scene));
  52759. };
  52760. function postMessageAPIHandler (event) {
  52761. var scene = this;
  52762. if (!event.data) { return; }
  52763. switch (event.data.type) {
  52764. case 'vr': {
  52765. switch (event.data.data) {
  52766. case 'enter':
  52767. scene.enterVR();
  52768. break;
  52769. case 'exit':
  52770. scene.exitVR();
  52771. break;
  52772. }
  52773. }
  52774. }
  52775. }
  52776. },{"../../utils/":178,"../../utils/bind":172}],112:[function(_dereq_,module,exports){
  52777. /*
  52778. Scene index for keeping track of created scenes.
  52779. */
  52780. module.exports = [];
  52781. },{}],113:[function(_dereq_,module,exports){
  52782. var Wakelock = _dereq_('../../../vendor/wakelock/wakelock');
  52783. module.exports = function initWakelock (scene) {
  52784. if (!scene.isMobile) { return; }
  52785. var wakelock = scene.wakelock = new Wakelock();
  52786. scene.addEventListener('enter-vr', function () { wakelock.request(); });
  52787. scene.addEventListener('exit-vr', function () { wakelock.release(); });
  52788. };
  52789. },{"../../../vendor/wakelock/wakelock":189}],114:[function(_dereq_,module,exports){
  52790. var utils = _dereq_('../utils/');
  52791. var PropertyTypes = _dereq_('./propertyTypes');
  52792. var debug = utils.debug;
  52793. var isValidDefaultValue = PropertyTypes.isValidDefaultValue;
  52794. var propertyTypes = PropertyTypes.propertyTypes;
  52795. var warn = debug('core:schema:warn');
  52796. /**
  52797. * A schema is classified as a schema for a single property if:
  52798. * - `type` is defined on the schema as a string.
  52799. * - OR `default` is defined on the schema, as a reserved keyword.
  52800. * - OR schema is empty.
  52801. */
  52802. function isSingleProperty (schema) {
  52803. if ('type' in schema) {
  52804. return typeof schema.type === 'string';
  52805. }
  52806. return 'default' in schema;
  52807. }
  52808. module.exports.isSingleProperty = isSingleProperty;
  52809. /**
  52810. * Build step to schema to use `type` to inject default value, parser, and stringifier.
  52811. *
  52812. * @param {object} schema
  52813. * @param {string} componentName
  52814. * @returns {object} Schema.
  52815. */
  52816. module.exports.process = function (schema, componentName) {
  52817. var propName;
  52818. // For single property schema, run processPropDefinition over the whole schema.
  52819. if (isSingleProperty(schema)) {
  52820. return processPropertyDefinition(schema, componentName);
  52821. }
  52822. // For multi-property schema, run processPropDefinition over each property definition.
  52823. for (propName in schema) {
  52824. schema[propName] = processPropertyDefinition(schema[propName], componentName);
  52825. }
  52826. return schema;
  52827. };
  52828. /**
  52829. * Inject default value, parser, stringifier for single property.
  52830. *
  52831. * @param {object} propDefinition
  52832. * @param {string} componentName
  52833. */
  52834. function processPropertyDefinition (propDefinition, componentName) {
  52835. var defaultVal = propDefinition.default;
  52836. var isCustomType;
  52837. var propType;
  52838. var typeName = propDefinition.type;
  52839. // Type inference.
  52840. if (!propDefinition.type) {
  52841. if (defaultVal !== undefined &&
  52842. (typeof defaultVal === 'boolean' || typeof defaultVal === 'number')) {
  52843. // Type inference.
  52844. typeName = typeof defaultVal;
  52845. } else if (Array.isArray(defaultVal)) {
  52846. typeName = 'array';
  52847. } else {
  52848. // Fall back to string.
  52849. typeName = 'string';
  52850. }
  52851. } else if (propDefinition.type === 'bool') {
  52852. typeName = 'boolean';
  52853. } else if (propDefinition.type === 'float') {
  52854. typeName = 'number';
  52855. }
  52856. propType = propertyTypes[typeName];
  52857. if (!propType) {
  52858. warn('Unknown property type for component `' + componentName + '`: ' + typeName);
  52859. }
  52860. // Fill in parse and stringify using property types.
  52861. isCustomType = !!propDefinition.parse;
  52862. propDefinition.parse = propDefinition.parse || propType.parse;
  52863. propDefinition.stringify = propDefinition.stringify || propType.stringify;
  52864. // Fill in type name.
  52865. propDefinition.type = typeName;
  52866. // Check that default value exists.
  52867. if ('default' in propDefinition) {
  52868. // Check that default values are valid.
  52869. if (!isCustomType && !isValidDefaultValue(typeName, defaultVal)) {
  52870. warn('Default value `' + defaultVal + '` does not match type `' + typeName +
  52871. '` in component `' + componentName + '`');
  52872. }
  52873. } else {
  52874. // Fill in default value.
  52875. propDefinition.default = propType.default;
  52876. }
  52877. return propDefinition;
  52878. }
  52879. module.exports.processPropertyDefinition = processPropertyDefinition;
  52880. /**
  52881. * Parse propData using schema. Use default values if not existing in propData.
  52882. *
  52883. * @param {object} propData - Unparsed properties.
  52884. * @param {object} schema - Property types definition.
  52885. * @param {boolean} getPartialData - Whether to return full component data or just the data
  52886. * with keys in `propData`.
  52887. * @param {string } componentName - Name of the component, used for the property warning.
  52888. * @param {boolean} silent - Suppress warning messages.
  52889. */
  52890. module.exports.parseProperties = (function () {
  52891. var propNames = [];
  52892. return function (propData, schema, getPartialData, componentName, silent) {
  52893. var i;
  52894. var propName;
  52895. var propDefinition;
  52896. var propValue;
  52897. propNames.length = 0;
  52898. for (propName in (getPartialData ? propData : schema)) {
  52899. if (getPartialData && propData[propName] === undefined) { continue; }
  52900. propNames.push(propName);
  52901. }
  52902. if (propData === null || typeof propData !== 'object') { return propData; }
  52903. // Validation errors.
  52904. for (propName in propData) {
  52905. if (propData[propName] !== undefined && !schema[propName] && !silent) {
  52906. warn('Unknown property `' + propName +
  52907. '` for component/system `' + componentName + '`.');
  52908. }
  52909. }
  52910. for (i = 0; i < propNames.length; i++) {
  52911. propName = propNames[i];
  52912. propDefinition = schema[propName];
  52913. propValue = propData[propName];
  52914. if (!(schema[propName])) { return; }
  52915. propData[propName] = parseProperty(propValue, propDefinition);
  52916. }
  52917. return propData;
  52918. };
  52919. })();
  52920. /**
  52921. * Deserialize a single property.
  52922. */
  52923. function parseProperty (value, propDefinition) {
  52924. // Use default value if value is falsy.
  52925. if (value === undefined || value === null || value === '') {
  52926. value = propDefinition.default;
  52927. if (Array.isArray(value)) { value = value.slice(); }
  52928. }
  52929. // Invoke property type parser.
  52930. return propDefinition.parse(value, propDefinition.default);
  52931. }
  52932. module.exports.parseProperty = parseProperty;
  52933. /**
  52934. * Serialize a group of properties.
  52935. */
  52936. module.exports.stringifyProperties = function (propData, schema) {
  52937. var propName;
  52938. var propDefinition;
  52939. var propValue;
  52940. var stringifiedData = {};
  52941. var value;
  52942. for (propName in propData) {
  52943. propDefinition = schema[propName];
  52944. propValue = propData[propName];
  52945. value = propValue;
  52946. if (typeof value === 'object') {
  52947. value = stringifyProperty(propValue, propDefinition);
  52948. if (!propDefinition) { warn('Unknown component property: ' + propName); }
  52949. }
  52950. stringifiedData[propName] = value;
  52951. }
  52952. return stringifiedData;
  52953. };
  52954. /**
  52955. * Serialize a single property.
  52956. */
  52957. function stringifyProperty (value, propDefinition) {
  52958. // This function stringifies but it's used in a context where
  52959. // there's always second stringification pass. By returning the original
  52960. // value when it's not an object we save one unnecessary call
  52961. // to JSON.stringify.
  52962. if (typeof value !== 'object') { return value; }
  52963. // if there's no schema for the property we use standar JSON stringify
  52964. if (!propDefinition || value === null) { return JSON.stringify(value); }
  52965. return propDefinition.stringify(value);
  52966. }
  52967. module.exports.stringifyProperty = stringifyProperty;
  52968. },{"../utils/":178,"./propertyTypes":107}],115:[function(_dereq_,module,exports){
  52969. var schema = _dereq_('./schema');
  52970. var processSchema = schema.process;
  52971. var shaders = module.exports.shaders = {}; // Keep track of registered shaders.
  52972. var shaderNames = module.exports.shaderNames = []; // Keep track of the names of registered shaders.
  52973. var THREE = _dereq_('../lib/three');
  52974. var utils = _dereq_('../utils');
  52975. // A-Frame properties to three.js uniform types.
  52976. var propertyToThreeMapping = {
  52977. array: 'v3',
  52978. color: 'v3',
  52979. int: 'i',
  52980. number: 'f',
  52981. map: 't',
  52982. time: 'f',
  52983. vec2: 'v2',
  52984. vec3: 'v3',
  52985. vec4: 'v4'
  52986. };
  52987. /**
  52988. * Shader class definition.
  52989. *
  52990. * Shaders extend the material component API so you can create your own library
  52991. * of customized materials
  52992. *
  52993. */
  52994. var Shader = module.exports.Shader = function () {};
  52995. Shader.prototype = {
  52996. /**
  52997. * Contains the type schema and defaults for the data values.
  52998. * Data is coerced into the types of the values of the defaults.
  52999. */
  53000. schema: {},
  53001. vertexShader:
  53002. 'void main() {' +
  53003. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);' +
  53004. '}',
  53005. fragmentShader:
  53006. 'void main() {' +
  53007. 'gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);' +
  53008. '}',
  53009. /**
  53010. * Init handler. Similar to attachedCallback.
  53011. * Called during shader initialization and is only run once.
  53012. */
  53013. init: function (data) {
  53014. this.attributes = this.initVariables(data, 'attribute');
  53015. this.uniforms = this.initVariables(data, 'uniform');
  53016. this.material = new (this.raw ? THREE.RawShaderMaterial : THREE.ShaderMaterial)({
  53017. // attributes: this.attributes,
  53018. uniforms: this.uniforms,
  53019. vertexShader: this.vertexShader,
  53020. fragmentShader: this.fragmentShader
  53021. });
  53022. return this.material;
  53023. },
  53024. initVariables: function (data, type) {
  53025. var key;
  53026. var schema = this.schema;
  53027. var variables = {};
  53028. var varType;
  53029. for (key in schema) {
  53030. if (schema[key].is !== type) { continue; }
  53031. varType = propertyToThreeMapping[schema[key].type];
  53032. variables[key] = {
  53033. type: varType,
  53034. value: undefined // Let updateVariables handle setting these.
  53035. };
  53036. }
  53037. return variables;
  53038. },
  53039. /**
  53040. * Update handler. Similar to attributeChangedCallback.
  53041. * Called whenever the associated material data changes.
  53042. *
  53043. * @param {object} data - New material data.
  53044. */
  53045. update: function (data) {
  53046. this.updateVariables(data, 'attribute');
  53047. this.updateVariables(data, 'uniform');
  53048. },
  53049. updateVariables: function (data, type) {
  53050. var key;
  53051. var materialKey;
  53052. var schema = this.schema;
  53053. var variables;
  53054. variables = type === 'uniform' ? this.uniforms : this.attributes;
  53055. for (key in data) {
  53056. if (!schema[key] || schema[key].is !== type) { continue; }
  53057. if (schema[key].type === 'map') {
  53058. // If data unchanged, get out early.
  53059. if (!variables[key] || variables[key].value === data[key]) { continue; }
  53060. // Special handling is needed for textures.
  53061. materialKey = '_texture_' + key;
  53062. // We can't actually set the variable correctly until we've loaded the texture.
  53063. this.setMapOnTextureLoad(variables, key, materialKey);
  53064. // Kick off the texture update now that handler is added.
  53065. utils.material.updateMapMaterialFromData(materialKey, key, this, data);
  53066. continue;
  53067. }
  53068. variables[key].value = this.parseValue(schema[key].type, data[key]);
  53069. variables[key].needsUpdate = true;
  53070. }
  53071. },
  53072. parseValue: function (type, value) {
  53073. var color;
  53074. switch (type) {
  53075. case 'vec2': {
  53076. return new THREE.Vector2(value.x, value.y);
  53077. }
  53078. case 'vec3': {
  53079. return new THREE.Vector3(value.x, value.y, value.z);
  53080. }
  53081. case 'vec4': {
  53082. return new THREE.Vector4(value.x, value.y, value.z, value.w);
  53083. }
  53084. case 'color': {
  53085. color = new THREE.Color(value);
  53086. return new THREE.Vector3(color.r, color.g, color.b);
  53087. }
  53088. case 'map': {
  53089. return THREE.ImageUtils.loadTexture(value);
  53090. }
  53091. default: {
  53092. return value;
  53093. }
  53094. }
  53095. },
  53096. setMapOnTextureLoad: function (variables, key, materialKey) {
  53097. var self = this;
  53098. this.el.addEventListener('materialtextureloaded', function () {
  53099. variables[key].value = self.material[materialKey];
  53100. variables[key].needsUpdate = true;
  53101. });
  53102. }
  53103. };
  53104. /**
  53105. * Registers a shader to A-Frame.
  53106. *
  53107. * @param {string} name - shader name.
  53108. * @param {object} definition - shader property and methods.
  53109. * @returns {object} Shader.
  53110. */
  53111. module.exports.registerShader = function (name, definition) {
  53112. var NewShader;
  53113. var proto = {};
  53114. // Format definition object to prototype object.
  53115. Object.keys(definition).forEach(function (key) {
  53116. proto[key] = {
  53117. value: definition[key],
  53118. writable: true
  53119. };
  53120. });
  53121. if (shaders[name]) {
  53122. throw new Error('The shader ' + name + ' has been already registered');
  53123. }
  53124. NewShader = function () { Shader.call(this); };
  53125. NewShader.prototype = Object.create(Shader.prototype, proto);
  53126. NewShader.prototype.name = name;
  53127. NewShader.prototype.constructor = NewShader;
  53128. shaders[name] = {
  53129. Shader: NewShader,
  53130. schema: processSchema(NewShader.prototype.schema)
  53131. };
  53132. shaderNames.push(name);
  53133. return NewShader;
  53134. };
  53135. },{"../lib/three":154,"../utils":178,"./schema":114}],116:[function(_dereq_,module,exports){
  53136. var components = _dereq_('./component');
  53137. var schema = _dereq_('./schema');
  53138. var utils = _dereq_('../utils/');
  53139. var parseProperties = schema.parseProperties;
  53140. var parseProperty = schema.parseProperty;
  53141. var processSchema = schema.process;
  53142. var isSingleProp = schema.isSingleProperty;
  53143. var styleParser = utils.styleParser;
  53144. var systems = module.exports.systems = {}; // Keep track of registered systems.
  53145. /**
  53146. * System class definition.
  53147. *
  53148. * Systems provide global scope and services to a group of instantiated components of the
  53149. * same class. They can also help abstract logic away from components such that components
  53150. * only have to worry about data.
  53151. *
  53152. * For example, a physics component that creates a physics world that oversees
  53153. * all entities with a physics or rigid body component.
  53154. *
  53155. * TODO: Have the System prototype reuse the Component prototype. Most code is copied
  53156. * and some pieces are missing from the Component facilities (e.g., attribute caching,
  53157. * setAttribute behavior).
  53158. *
  53159. * @member {string} name - Name that system is registered under.
  53160. * @member {Element} sceneEl - Handle to the scene element where system applies to.
  53161. */
  53162. var System = module.exports.System = function (sceneEl) {
  53163. var component = components && components.components[this.name];
  53164. // Set reference to scene.
  53165. this.el = sceneEl;
  53166. this.sceneEl = sceneEl;
  53167. // Set reference to matching component (if exists).
  53168. if (component) { component.Component.prototype.system = this; }
  53169. // Process system configuration.
  53170. this.buildData();
  53171. this.init();
  53172. this.update({});
  53173. };
  53174. System.prototype = {
  53175. /**
  53176. * Schema to configure system.
  53177. */
  53178. schema: {},
  53179. /**
  53180. * Init handler. Called during scene initialization and is only run once.
  53181. * Systems can use this to set initial state.
  53182. */
  53183. init: function () { /* no-op */ },
  53184. /**
  53185. * Update handler. Called during scene attribute updates.
  53186. * Systems can use this to dynamically update their state.
  53187. */
  53188. update: function (oldData) { /* no-op */ },
  53189. /**
  53190. * Build data and call update handler.
  53191. *
  53192. * @private
  53193. */
  53194. updateProperties: function (rawData) {
  53195. var oldData = this.data;
  53196. if (!Object.keys(schema).length) { return; }
  53197. this.buildData(rawData);
  53198. this.update(oldData);
  53199. },
  53200. /**
  53201. * Parse data.
  53202. */
  53203. buildData: function (rawData) {
  53204. var schema = this.schema;
  53205. if (!Object.keys(schema).length) { return; }
  53206. rawData = rawData || window.HTMLElement.prototype.getAttribute.call(this.sceneEl, this.name);
  53207. if (isSingleProp(schema)) {
  53208. this.data = parseProperty(rawData, schema);
  53209. } else {
  53210. this.data = parseProperties(styleParser.parse(rawData) || {}, schema);
  53211. }
  53212. },
  53213. /**
  53214. * Tick handler.
  53215. * Called on each tick of the scene render loop.
  53216. * Affected by play and pause.
  53217. *
  53218. * @param {number} time - Scene tick time.
  53219. * @param {number} timeDelta - Difference in current render time and previous render time.
  53220. */
  53221. tick: undefined,
  53222. /**
  53223. * Tock handler.
  53224. * Called on each tock of the scene render loop.
  53225. * Affected by play and pause.
  53226. *
  53227. * @param {number} time - Scene tick time.
  53228. * @param {number} timeDelta - Difference in current render time and previous render time.
  53229. */
  53230. tock: undefined,
  53231. /**
  53232. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  53233. */
  53234. play: function () { /* no-op */ },
  53235. /**
  53236. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  53237. */
  53238. pause: function () { /* no-op */ }
  53239. };
  53240. /**
  53241. * Registers a system to A-Frame.
  53242. *
  53243. * @param {string} name - Component name.
  53244. * @param {object} definition - Component property and methods.
  53245. * @returns {object} Component.
  53246. */
  53247. module.exports.registerSystem = function (name, definition) {
  53248. var i;
  53249. var NewSystem;
  53250. var proto = {};
  53251. var scenes = utils.findAllScenes(document);
  53252. // Format definition object to prototype object.
  53253. Object.keys(definition).forEach(function (key) {
  53254. proto[key] = {
  53255. value: definition[key],
  53256. writable: true
  53257. };
  53258. });
  53259. if (systems[name]) {
  53260. throw new Error('The system `' + name + '` has been already registered. ' +
  53261. 'Check that you are not loading two versions of the same system ' +
  53262. 'or two different systems of the same name.');
  53263. }
  53264. NewSystem = function (sceneEl) { System.call(this, sceneEl); };
  53265. NewSystem.prototype = Object.create(System.prototype, proto);
  53266. NewSystem.prototype.name = name;
  53267. NewSystem.prototype.constructor = NewSystem;
  53268. NewSystem.prototype.schema = utils.extend(processSchema(NewSystem.prototype.schema));
  53269. systems[name] = NewSystem;
  53270. // Initialize systems for existing scenes
  53271. for (i = 0; i < scenes.length; i++) { scenes[i].initSystem(name); }
  53272. };
  53273. },{"../utils/":178,"./component":105,"./schema":114}],117:[function(_dereq_,module,exports){
  53274. _dereq_('./pivot');
  53275. },{"./pivot":118}],118:[function(_dereq_,module,exports){
  53276. var registerComponent = _dereq_('../../core/component').registerComponent;
  53277. var THREE = _dereq_('../../lib/three');
  53278. var originalPosition = new THREE.Vector3();
  53279. var originalRotation = new THREE.Vector3();
  53280. /**
  53281. * Wrap el.object3D within an outer group. Apply pivot to el.object3D as position.
  53282. */
  53283. registerComponent('pivot', {
  53284. dependencies: ['position'],
  53285. schema: {type: 'vec3'},
  53286. init: function () {
  53287. var data = this.data;
  53288. var el = this.el;
  53289. var originalParent = el.object3D.parent;
  53290. var originalGroup = el.object3D;
  53291. var outerGroup = new THREE.Group();
  53292. originalPosition.copy(originalGroup.position);
  53293. originalRotation.copy(originalGroup.rotation);
  53294. // Detach current group from parent.
  53295. originalParent.remove(originalGroup);
  53296. outerGroup.add(originalGroup);
  53297. // Set new group as the outer group.
  53298. originalParent.add(outerGroup);
  53299. // Set outer group as new object3D.
  53300. el.object3D = outerGroup;
  53301. // Apply pivot to original group.
  53302. originalGroup.position.set(-1 * data.x, -1 * data.y, -1 * data.z);
  53303. // Offset the pivot so that world position not affected.
  53304. // And restore position onto outer group.
  53305. outerGroup.position.set(data.x + originalPosition.x, data.y + originalPosition.y,
  53306. data.z + originalPosition.z);
  53307. // Transfer rotation to outer group.
  53308. outerGroup.rotation.copy(originalGroup.rotation);
  53309. originalGroup.rotation.set(0, 0, 0);
  53310. }
  53311. });
  53312. },{"../../core/component":105,"../../lib/three":154}],119:[function(_dereq_,module,exports){
  53313. /**
  53314. * Common mesh defaults, mappings, and transforms.
  53315. */
  53316. var components = _dereq_('../../core/component').components;
  53317. var shaders = _dereq_('../../core/shader').shaders;
  53318. var utils = _dereq_('../../utils/');
  53319. var materialMappings = {};
  53320. Object.keys(components.material.schema).forEach(addMapping);
  53321. Object.keys(shaders.standard.schema).forEach(addMapping);
  53322. function addMapping (prop) {
  53323. // To hyphenated.
  53324. var htmlAttrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  53325. if (prop === 'fog') { htmlAttrName = 'material-fog'; }
  53326. if (prop === 'visible') { htmlAttrName = 'material-visible'; }
  53327. materialMappings[htmlAttrName] = 'material.' + prop;
  53328. }
  53329. module.exports = function getMeshMixin () {
  53330. return {
  53331. defaultComponents: {material: {}},
  53332. mappings: utils.extend({}, materialMappings)
  53333. };
  53334. };
  53335. },{"../../core/component":105,"../../core/shader":115,"../../utils/":178}],120:[function(_dereq_,module,exports){
  53336. _dereq_('./primitives/a-camera');
  53337. _dereq_('./primitives/a-collada-model');
  53338. _dereq_('./primitives/a-cursor');
  53339. _dereq_('./primitives/a-curvedimage');
  53340. _dereq_('./primitives/a-gltf-model');
  53341. _dereq_('./primitives/a-image');
  53342. _dereq_('./primitives/a-light');
  53343. _dereq_('./primitives/a-link');
  53344. _dereq_('./primitives/a-obj-model');
  53345. _dereq_('./primitives/a-sky');
  53346. _dereq_('./primitives/a-sound');
  53347. _dereq_('./primitives/a-text');
  53348. _dereq_('./primitives/a-video');
  53349. _dereq_('./primitives/a-videosphere');
  53350. _dereq_('./primitives/meshPrimitives');
  53351. },{"./primitives/a-camera":122,"./primitives/a-collada-model":123,"./primitives/a-cursor":124,"./primitives/a-curvedimage":125,"./primitives/a-gltf-model":126,"./primitives/a-image":127,"./primitives/a-light":128,"./primitives/a-link":129,"./primitives/a-obj-model":130,"./primitives/a-sky":131,"./primitives/a-sound":132,"./primitives/a-text":133,"./primitives/a-video":134,"./primitives/a-videosphere":135,"./primitives/meshPrimitives":136}],121:[function(_dereq_,module,exports){
  53352. var AEntity = _dereq_('../../core/a-entity');
  53353. var components = _dereq_('../../core/component').components;
  53354. var registerElement = _dereq_('../../core/a-register-element').registerElement;
  53355. var utils = _dereq_('../../utils/');
  53356. var debug = utils.debug;
  53357. var setComponentProperty = utils.entity.setComponentProperty;
  53358. var log = debug('extras:primitives:debug');
  53359. var warn = debug('extras:primitives:warn');
  53360. var primitives = module.exports.primitives = {};
  53361. module.exports.registerPrimitive = function registerPrimitive (name, definition) {
  53362. name = name.toLowerCase();
  53363. log('Registering <%s>', name);
  53364. // Deprecation warning for defaultAttributes usage.
  53365. if (definition.defaultAttributes) {
  53366. warn("The 'defaultAttributes' object is deprecated. Use 'defaultComponents' instead.");
  53367. }
  53368. var primitive = registerElement(name, {
  53369. prototype: Object.create(AEntity.prototype, {
  53370. defaultComponentsFromPrimitive: {
  53371. value: definition.defaultComponents || definition.defaultAttributes || {}
  53372. },
  53373. deprecated: {value: definition.deprecated || null},
  53374. deprecatedMappings: {value: definition.deprecatedMappings || {}},
  53375. mappings: {value: definition.mappings || {}},
  53376. createdCallback: {
  53377. value: function () {
  53378. if (definition.deprecated) { console.warn(definition.deprecated); }
  53379. this.resolveMappingCollisions();
  53380. }
  53381. },
  53382. /**
  53383. * If a mapping collides with a registered component name
  53384. * it renames the mapping to componentname-property
  53385. */
  53386. resolveMappingCollisions: {
  53387. value: function () {
  53388. var mappings = this.mappings;
  53389. var self = this;
  53390. Object.keys(mappings).forEach(function resolveCollision (key) {
  53391. var newAttribute;
  53392. if (key !== key.toLowerCase()) { warn('Mapping keys should be specified in lower case. The mapping key ' + key + ' may not be recognized'); }
  53393. if (components[key]) {
  53394. newAttribute = mappings[key].replace('.', '-');
  53395. mappings[newAttribute] = mappings[key];
  53396. delete mappings[key];
  53397. console.warn('The primitive ' + self.tagName.toLowerCase() + ' has a mapping collision. ' +
  53398. 'The attribute ' + key + ' has the same name as a registered component and' +
  53399. ' has been renamed to ' + newAttribute);
  53400. }
  53401. });
  53402. }
  53403. },
  53404. getExtraComponents: {
  53405. value: function () {
  53406. var attr;
  53407. var data;
  53408. var i;
  53409. var mapping;
  53410. var mixins;
  53411. var path;
  53412. var self = this;
  53413. // Gather component data from default components.
  53414. data = utils.clone(this.defaultComponentsFromPrimitive);
  53415. // Factor in mixins to overwrite default components.
  53416. mixins = this.getAttribute('mixin');
  53417. if (mixins) {
  53418. mixins = mixins.trim().split(' ');
  53419. mixins.forEach(function applyMixin (mixinId) {
  53420. var mixinComponents = self.sceneEl.querySelector('#' + mixinId).componentCache;
  53421. Object.keys(mixinComponents).forEach(function setComponent (name) {
  53422. data[name] = extend(data[name], mixinComponents[name]);
  53423. });
  53424. });
  53425. }
  53426. // Gather component data from mappings.
  53427. for (i = 0; i < this.attributes.length; i++) {
  53428. attr = this.attributes[i];
  53429. mapping = this.mappings[attr.name];
  53430. if (mapping) {
  53431. path = utils.entity.getComponentPropertyPath(mapping);
  53432. if (path.constructor === Array) {
  53433. data[path[0]] = data[path[0]] || {};
  53434. data[path[0]][path[1]] = attr.value.trim();
  53435. } else {
  53436. data[path] = attr.value.trim();
  53437. }
  53438. continue;
  53439. }
  53440. }
  53441. return data;
  53442. /**
  53443. * For the base to be extensible, both objects must be pure JavaScript objects.
  53444. * The function assumes that base is undefined, or null or a pure object.
  53445. */
  53446. function extend (base, extension) {
  53447. if (isUndefined(base)) {
  53448. return copy(extension);
  53449. }
  53450. if (isUndefined(extension)) {
  53451. return copy(base);
  53452. }
  53453. if (isPureObject(base) && isPureObject(extension)) {
  53454. return utils.extendDeep(base, extension);
  53455. }
  53456. return copy(extension);
  53457. }
  53458. function isUndefined (value) {
  53459. return typeof value === 'undefined';
  53460. }
  53461. function copy (value) {
  53462. if (isPureObject(value)) {
  53463. return utils.extendDeep({}, value);
  53464. }
  53465. return value;
  53466. }
  53467. function isPureObject (value) {
  53468. return value !== null && value.constructor === Object;
  53469. }
  53470. }
  53471. },
  53472. /**
  53473. * Sync to attribute to component property whenever mapped attribute changes.
  53474. * If attribute is mapped to a component property, set the component property using
  53475. * the attribute value.
  53476. */
  53477. attributeChangedCallback: {
  53478. value: function (attr, oldVal, value) {
  53479. var componentName = this.mappings[attr];
  53480. if (attr in this.deprecatedMappings) {
  53481. console.warn(this.deprecatedMappings[attr]);
  53482. }
  53483. if (!attr || !componentName) { return; }
  53484. // Set value.
  53485. setComponentProperty(this, componentName, value);
  53486. }
  53487. }
  53488. })
  53489. });
  53490. // Store.
  53491. primitives[name] = primitive;
  53492. return primitive;
  53493. };
  53494. /**
  53495. * Add component mappings using schema.
  53496. */
  53497. function addComponentMapping (componentName, mappings) {
  53498. var schema = components[componentName].schema;
  53499. Object.keys(schema).map(function (prop) {
  53500. // Hyphenate where there is camelCase.
  53501. var attrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  53502. // If there is a mapping collision, prefix with component name and hyphen.
  53503. if (mappings[attrName] !== undefined) { attrName = componentName + '-' + prop; }
  53504. mappings[attrName] = componentName + '.' + prop;
  53505. });
  53506. }
  53507. /**
  53508. * Helper to define a primitive, building mappings using a component schema.
  53509. */
  53510. function definePrimitive (tagName, defaultComponents, mappings) {
  53511. // If no initial mappings provided, start from empty map.
  53512. mappings = mappings || {};
  53513. // From the default components, add mapping automagically.
  53514. Object.keys(defaultComponents).map(function buildMappings (componentName) {
  53515. addComponentMapping(componentName, mappings);
  53516. });
  53517. // Register the primitive.
  53518. module.exports.registerPrimitive(tagName, utils.extendDeep({}, null, {
  53519. defaultComponents: defaultComponents,
  53520. mappings: mappings
  53521. }));
  53522. }
  53523. module.exports.definePrimitive = definePrimitive;
  53524. },{"../../core/a-entity":101,"../../core/a-register-element":104,"../../core/component":105,"../../utils/":178}],122:[function(_dereq_,module,exports){
  53525. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53526. registerPrimitive('a-camera', {
  53527. defaultComponents: {
  53528. 'camera': {},
  53529. 'look-controls': {},
  53530. 'wasd-controls': {},
  53531. 'position': {x: 0, y: 1.6, z: 0}
  53532. },
  53533. mappings: {
  53534. active: 'camera.active',
  53535. far: 'camera.far',
  53536. fov: 'camera.fov',
  53537. 'look-controls-enabled': 'look-controls.enabled',
  53538. near: 'camera.near',
  53539. 'pointer-lock-enabled': 'look-controls.pointerLockEnabled',
  53540. 'wasd-controls-enabled': 'wasd-controls.enabled',
  53541. 'reverse-mouse-drag': 'look-controls.reverseMouseDrag',
  53542. zoom: 'camera.zoom'
  53543. }
  53544. });
  53545. },{"../primitives":121}],123:[function(_dereq_,module,exports){
  53546. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53547. registerPrimitive('a-collada-model', {
  53548. mappings: {
  53549. src: 'collada-model'
  53550. }
  53551. });
  53552. },{"../primitives":121}],124:[function(_dereq_,module,exports){
  53553. var getMeshMixin = _dereq_('../getMeshMixin');
  53554. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53555. var utils = _dereq_('../../../utils/');
  53556. registerPrimitive('a-cursor', utils.extendDeep({}, getMeshMixin(), {
  53557. defaultComponents: {
  53558. cursor: {},
  53559. geometry: {
  53560. primitive: 'ring',
  53561. radiusOuter: 0.016,
  53562. radiusInner: 0.01,
  53563. segmentsTheta: 32
  53564. },
  53565. material: {
  53566. color: '#000',
  53567. shader: 'flat',
  53568. opacity: 0.8
  53569. },
  53570. position: {
  53571. x: 0,
  53572. y: 0,
  53573. z: -1
  53574. }
  53575. },
  53576. mappings: {
  53577. far: 'raycaster.far',
  53578. fuse: 'cursor.fuse',
  53579. 'fuse-timeout': 'cursor.fuseTimeout',
  53580. interval: 'raycaster.interval',
  53581. objects: 'raycaster.objects'
  53582. }
  53583. }));
  53584. },{"../../../utils/":178,"../getMeshMixin":119,"../primitives":121}],125:[function(_dereq_,module,exports){
  53585. var getMeshMixin = _dereq_('../getMeshMixin');
  53586. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53587. var utils = _dereq_('../../../utils/');
  53588. registerPrimitive('a-curvedimage', utils.extendDeep({}, getMeshMixin(), {
  53589. defaultComponents: {
  53590. geometry: {
  53591. height: 1,
  53592. primitive: 'cylinder',
  53593. radius: 2,
  53594. segmentsRadial: 48,
  53595. thetaLength: 270,
  53596. openEnded: true,
  53597. thetaStart: 0
  53598. },
  53599. material: {
  53600. color: '#FFF',
  53601. shader: 'flat',
  53602. side: 'double',
  53603. transparent: true,
  53604. repeat: '-1 1'
  53605. }
  53606. },
  53607. mappings: {
  53608. height: 'geometry.height',
  53609. 'open-ended': 'geometry.openEnded',
  53610. radius: 'geometry.radius',
  53611. segments: 'geometry.segmentsRadial',
  53612. start: 'geometry.thetaStart',
  53613. 'theta-length': 'geometry.thetaLength',
  53614. 'theta-start': 'geometry.thetaStart',
  53615. 'width': 'geometry.thetaLength'
  53616. }
  53617. }));
  53618. },{"../../../utils/":178,"../getMeshMixin":119,"../primitives":121}],126:[function(_dereq_,module,exports){
  53619. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53620. registerPrimitive('a-gltf-model', {
  53621. mappings: {
  53622. src: 'gltf-model'
  53623. }
  53624. });
  53625. },{"../primitives":121}],127:[function(_dereq_,module,exports){
  53626. var getMeshMixin = _dereq_('../getMeshMixin');
  53627. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53628. var utils = _dereq_('../../../utils/');
  53629. registerPrimitive('a-image', utils.extendDeep({}, getMeshMixin(), {
  53630. defaultComponents: {
  53631. geometry: {
  53632. primitive: 'plane'
  53633. },
  53634. material: {
  53635. color: '#FFF',
  53636. shader: 'flat',
  53637. side: 'double',
  53638. transparent: true
  53639. }
  53640. },
  53641. mappings: {
  53642. height: 'geometry.height',
  53643. width: 'geometry.width'
  53644. }
  53645. }));
  53646. },{"../../../utils/":178,"../getMeshMixin":119,"../primitives":121}],128:[function(_dereq_,module,exports){
  53647. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53648. registerPrimitive('a-light', {
  53649. defaultComponents: {
  53650. light: {}
  53651. },
  53652. mappings: {
  53653. angle: 'light.angle',
  53654. color: 'light.color',
  53655. 'ground-color': 'light.groundColor',
  53656. decay: 'light.decay',
  53657. distance: 'light.distance',
  53658. intensity: 'light.intensity',
  53659. penumbra: 'light.penumbra',
  53660. type: 'light.type',
  53661. target: 'light.target'
  53662. }
  53663. });
  53664. },{"../primitives":121}],129:[function(_dereq_,module,exports){
  53665. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53666. registerPrimitive('a-link', {
  53667. defaultComponents: {
  53668. link: {
  53669. visualAspectEnabled: true
  53670. }
  53671. },
  53672. mappings: {
  53673. href: 'link.href',
  53674. image: 'link.image',
  53675. title: 'link.title'
  53676. }
  53677. });
  53678. },{"../primitives":121}],130:[function(_dereq_,module,exports){
  53679. var meshMixin = _dereq_('../getMeshMixin')();
  53680. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53681. var utils = _dereq_('../../../utils/');
  53682. registerPrimitive('a-obj-model', utils.extendDeep({}, meshMixin, {
  53683. defaultComponents: {
  53684. 'obj-model': {}
  53685. },
  53686. mappings: {
  53687. src: 'obj-model.obj',
  53688. mtl: 'obj-model.mtl'
  53689. }
  53690. }));
  53691. },{"../../../utils/":178,"../getMeshMixin":119,"../primitives":121}],131:[function(_dereq_,module,exports){
  53692. var getMeshMixin = _dereq_('../getMeshMixin');
  53693. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53694. var utils = _dereq_('../../../utils/');
  53695. var meshPrimitives = _dereq_('./meshPrimitives');
  53696. registerPrimitive('a-sky', utils.extendDeep({}, getMeshMixin(), {
  53697. defaultComponents: {
  53698. geometry: {
  53699. primitive: 'sphere',
  53700. radius: 5000,
  53701. segmentsWidth: 64,
  53702. segmentsHeight: 32
  53703. },
  53704. material: {
  53705. color: '#FFF',
  53706. side: 'back',
  53707. shader: 'flat',
  53708. npot: true
  53709. },
  53710. scale: '-1 1 1'
  53711. },
  53712. mappings: utils.extendDeep({}, meshPrimitives['a-sphere'].prototype.mappings)
  53713. }));
  53714. },{"../../../utils/":178,"../getMeshMixin":119,"../primitives":121,"./meshPrimitives":136}],132:[function(_dereq_,module,exports){
  53715. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53716. registerPrimitive('a-sound', {
  53717. defaultComponents: {
  53718. sound: {}
  53719. },
  53720. mappings: {
  53721. src: 'sound.src',
  53722. on: 'sound.on',
  53723. autoplay: 'sound.autoplay',
  53724. loop: 'sound.loop',
  53725. volume: 'sound.volume'
  53726. }
  53727. });
  53728. },{"../primitives":121}],133:[function(_dereq_,module,exports){
  53729. // <a-text> using `definePrimitive` helper.
  53730. var definePrimitive = _dereq_('../primitives').definePrimitive;
  53731. definePrimitive('a-text', {text: {anchor: 'align', width: 5}});
  53732. },{"../primitives":121}],134:[function(_dereq_,module,exports){
  53733. var getMeshMixin = _dereq_('../getMeshMixin');
  53734. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53735. var utils = _dereq_('../../../utils/');
  53736. registerPrimitive('a-video', utils.extendDeep({}, getMeshMixin(), {
  53737. defaultComponents: {
  53738. geometry: {
  53739. primitive: 'plane'
  53740. },
  53741. material: {
  53742. color: '#FFF',
  53743. shader: 'flat',
  53744. side: 'double',
  53745. transparent: true
  53746. }
  53747. },
  53748. mappings: {
  53749. height: 'geometry.height',
  53750. width: 'geometry.width'
  53751. }
  53752. }));
  53753. },{"../../../utils/":178,"../getMeshMixin":119,"../primitives":121}],135:[function(_dereq_,module,exports){
  53754. var getMeshMixin = _dereq_('../getMeshMixin');
  53755. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53756. var utils = _dereq_('../../../utils/');
  53757. registerPrimitive('a-videosphere', utils.extendDeep({}, getMeshMixin(), {
  53758. defaultComponents: {
  53759. geometry: {
  53760. primitive: 'sphere',
  53761. radius: 5000,
  53762. segmentsWidth: 64,
  53763. segmentsHeight: 32
  53764. },
  53765. material: {
  53766. color: '#FFF',
  53767. shader: 'flat',
  53768. side: 'back',
  53769. npot: true
  53770. },
  53771. scale: '-1 1 1'
  53772. },
  53773. mappings: {
  53774. radius: 'geometry.radius',
  53775. 'segments-height': 'geometry.segmentsHeight',
  53776. 'segments-width': 'geometry.segmentsWidth'
  53777. }
  53778. }));
  53779. },{"../../../utils/":178,"../getMeshMixin":119,"../primitives":121}],136:[function(_dereq_,module,exports){
  53780. /**
  53781. * Automated mesh primitive registration.
  53782. */
  53783. var getMeshMixin = _dereq_('../getMeshMixin');
  53784. var geometries = _dereq_('../../../core/geometry').geometries;
  53785. var geometryNames = _dereq_('../../../core/geometry').geometryNames;
  53786. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53787. var utils = _dereq_('../../../utils/');
  53788. // For testing.
  53789. var meshPrimitives = module.exports = {};
  53790. // Generate primitive for each geometry type.
  53791. geometryNames.forEach(function registerMeshPrimitive (geometryName) {
  53792. var geometry = geometries[geometryName];
  53793. var geometryHyphened = unCamelCase(geometryName);
  53794. // Generate mappings.
  53795. var mappings = {};
  53796. Object.keys(geometry.schema).forEach(function createMapping (property) {
  53797. mappings[unCamelCase(property)] = 'geometry.' + property;
  53798. });
  53799. // Register.
  53800. var tagName = 'a-' + geometryHyphened;
  53801. var primitive = registerPrimitive(tagName, utils.extendDeep({}, getMeshMixin(), {
  53802. defaultComponents: {geometry: {primitive: geometryName}},
  53803. mappings: mappings
  53804. }));
  53805. meshPrimitives[tagName] = primitive;
  53806. });
  53807. /**
  53808. * camelCase to hyphened-string.
  53809. */
  53810. function unCamelCase (str) {
  53811. return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  53812. }
  53813. },{"../../../core/geometry":106,"../../../utils/":178,"../getMeshMixin":119,"../primitives":121}],137:[function(_dereq_,module,exports){
  53814. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53815. var THREE = _dereq_('../lib/three');
  53816. registerGeometry('box', {
  53817. schema: {
  53818. depth: {default: 1, min: 0},
  53819. height: {default: 1, min: 0},
  53820. width: {default: 1, min: 0},
  53821. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  53822. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'},
  53823. segmentsDepth: {default: 1, min: 1, max: 20, type: 'int'}
  53824. },
  53825. init: function (data) {
  53826. this.geometry = new THREE.BoxGeometry(
  53827. data.width, data.height, data.depth,
  53828. data.segmentsWidth, data.segmentsHeight, data.segmentsDepth);
  53829. }
  53830. });
  53831. },{"../core/geometry":106,"../lib/three":154}],138:[function(_dereq_,module,exports){
  53832. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53833. var THREE = _dereq_('../lib/three');
  53834. var degToRad = THREE.Math.degToRad;
  53835. registerGeometry('circle', {
  53836. schema: {
  53837. radius: {default: 1, min: 0},
  53838. segments: {default: 32, min: 3, type: 'int'},
  53839. thetaLength: {default: 360, min: 0},
  53840. thetaStart: {default: 0}
  53841. },
  53842. init: function (data) {
  53843. this.geometry = new THREE.CircleGeometry(
  53844. data.radius, data.segments, degToRad(data.thetaStart), degToRad(data.thetaLength));
  53845. }
  53846. });
  53847. },{"../core/geometry":106,"../lib/three":154}],139:[function(_dereq_,module,exports){
  53848. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53849. var THREE = _dereq_('../lib/three');
  53850. var degToRad = THREE.Math.degToRad;
  53851. registerGeometry('cone', {
  53852. schema: {
  53853. height: {default: 1, min: 0},
  53854. openEnded: {default: false},
  53855. radiusBottom: {default: 1, min: 0},
  53856. radiusTop: {default: 0.01, min: 0},
  53857. segmentsHeight: {default: 18, min: 1, type: 'int'},
  53858. segmentsRadial: {default: 36, min: 3, type: 'int'},
  53859. thetaLength: {default: 360, min: 0},
  53860. thetaStart: {default: 0}
  53861. },
  53862. init: function (data) {
  53863. this.geometry = new THREE.CylinderGeometry(
  53864. data.radiusTop, data.radiusBottom, data.height, data.segmentsRadial,
  53865. data.segmentsHeight, data.openEnded, degToRad(data.thetaStart),
  53866. degToRad(data.thetaLength));
  53867. }
  53868. });
  53869. },{"../core/geometry":106,"../lib/three":154}],140:[function(_dereq_,module,exports){
  53870. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53871. var THREE = _dereq_('../lib/three');
  53872. var degToRad = THREE.Math.degToRad;
  53873. registerGeometry('cylinder', {
  53874. schema: {
  53875. height: {default: 1, min: 0},
  53876. openEnded: {default: false},
  53877. radius: {default: 1, min: 0},
  53878. segmentsHeight: {default: 18, min: 1, type: 'int'},
  53879. segmentsRadial: {default: 36, min: 3, type: 'int'},
  53880. thetaLength: {default: 360, min: 0},
  53881. thetaStart: {default: 0}
  53882. },
  53883. init: function (data) {
  53884. this.geometry = new THREE.CylinderGeometry(
  53885. data.radius, data.radius, data.height, data.segmentsRadial, data.segmentsHeight,
  53886. data.openEnded, degToRad(data.thetaStart), degToRad(data.thetaLength));
  53887. }
  53888. });
  53889. },{"../core/geometry":106,"../lib/three":154}],141:[function(_dereq_,module,exports){
  53890. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53891. var THREE = _dereq_('../lib/three');
  53892. registerGeometry('dodecahedron', {
  53893. schema: {
  53894. detail: {default: 0, min: 0, max: 5, type: 'int'},
  53895. radius: {default: 1, min: 0}
  53896. },
  53897. init: function (data) {
  53898. this.geometry = new THREE.DodecahedronGeometry(data.radius, data.detail);
  53899. }
  53900. });
  53901. },{"../core/geometry":106,"../lib/three":154}],142:[function(_dereq_,module,exports){
  53902. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53903. var THREE = _dereq_('../lib/three');
  53904. registerGeometry('icosahedron', {
  53905. schema: {
  53906. detail: {default: 0, min: 0, max: 5, type: 'int'},
  53907. radius: {default: 1, min: 0}
  53908. },
  53909. init: function (data) {
  53910. this.geometry = new THREE.IcosahedronGeometry(data.radius, data.detail);
  53911. }
  53912. });
  53913. },{"../core/geometry":106,"../lib/three":154}],143:[function(_dereq_,module,exports){
  53914. _dereq_('./box.js');
  53915. _dereq_('./circle.js');
  53916. _dereq_('./cone.js');
  53917. _dereq_('./cylinder.js');
  53918. _dereq_('./dodecahedron.js');
  53919. _dereq_('./icosahedron.js');
  53920. _dereq_('./octahedron.js');
  53921. _dereq_('./plane.js');
  53922. _dereq_('./ring.js');
  53923. _dereq_('./sphere.js');
  53924. _dereq_('./tetrahedron.js');
  53925. _dereq_('./torus.js');
  53926. _dereq_('./torusKnot.js');
  53927. _dereq_('./triangle.js');
  53928. },{"./box.js":137,"./circle.js":138,"./cone.js":139,"./cylinder.js":140,"./dodecahedron.js":141,"./icosahedron.js":142,"./octahedron.js":144,"./plane.js":145,"./ring.js":146,"./sphere.js":147,"./tetrahedron.js":148,"./torus.js":149,"./torusKnot.js":150,"./triangle.js":151}],144:[function(_dereq_,module,exports){
  53929. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53930. var THREE = _dereq_('../lib/three');
  53931. registerGeometry('octahedron', {
  53932. schema: {
  53933. detail: {default: 0, min: 0, max: 5, type: 'int'},
  53934. radius: {default: 1, min: 0}
  53935. },
  53936. init: function (data) {
  53937. this.geometry = new THREE.OctahedronGeometry(data.radius, data.detail);
  53938. }
  53939. });
  53940. },{"../core/geometry":106,"../lib/three":154}],145:[function(_dereq_,module,exports){
  53941. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53942. var THREE = _dereq_('../lib/three');
  53943. registerGeometry('plane', {
  53944. schema: {
  53945. height: {default: 1, min: 0},
  53946. width: {default: 1, min: 0},
  53947. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  53948. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'}
  53949. },
  53950. init: function (data) {
  53951. this.geometry = new THREE.PlaneGeometry(data.width, data.height, data.segmentsWidth, data.segmentsHeight);
  53952. }
  53953. });
  53954. },{"../core/geometry":106,"../lib/three":154}],146:[function(_dereq_,module,exports){
  53955. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53956. var THREE = _dereq_('../lib/three');
  53957. var degToRad = THREE.Math.degToRad;
  53958. registerGeometry('ring', {
  53959. schema: {
  53960. radiusInner: {default: 0.8, min: 0},
  53961. radiusOuter: {default: 1.2, min: 0},
  53962. segmentsPhi: {default: 10, min: 1, type: 'int'},
  53963. segmentsTheta: {default: 32, min: 3, type: 'int'},
  53964. thetaLength: {default: 360, min: 0},
  53965. thetaStart: {default: 0}
  53966. },
  53967. init: function (data) {
  53968. this.geometry = new THREE.RingGeometry(
  53969. data.radiusInner, data.radiusOuter, data.segmentsTheta, data.segmentsPhi,
  53970. degToRad(data.thetaStart), degToRad(data.thetaLength));
  53971. }
  53972. });
  53973. },{"../core/geometry":106,"../lib/three":154}],147:[function(_dereq_,module,exports){
  53974. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53975. var THREE = _dereq_('../lib/three');
  53976. var degToRad = THREE.Math.degToRad;
  53977. registerGeometry('sphere', {
  53978. schema: {
  53979. radius: {default: 1, min: 0},
  53980. phiLength: {default: 360},
  53981. phiStart: {default: 0, min: 0},
  53982. thetaLength: {default: 180, min: 0},
  53983. thetaStart: {default: 0},
  53984. segmentsHeight: {default: 18, min: 2, type: 'int'},
  53985. segmentsWidth: {default: 36, min: 3, type: 'int'}
  53986. },
  53987. init: function (data) {
  53988. this.geometry = new THREE.SphereGeometry(
  53989. data.radius, data.segmentsWidth, data.segmentsHeight, degToRad(data.phiStart),
  53990. degToRad(data.phiLength), degToRad(data.thetaStart), degToRad(data.thetaLength));
  53991. }
  53992. });
  53993. },{"../core/geometry":106,"../lib/three":154}],148:[function(_dereq_,module,exports){
  53994. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53995. var THREE = _dereq_('../lib/three');
  53996. registerGeometry('tetrahedron', {
  53997. schema: {
  53998. detail: {default: 0, min: 0, max: 5, type: 'int'},
  53999. radius: {default: 1, min: 0}
  54000. },
  54001. init: function (data) {
  54002. this.geometry = new THREE.TetrahedronGeometry(data.radius, data.detail);
  54003. }
  54004. });
  54005. },{"../core/geometry":106,"../lib/three":154}],149:[function(_dereq_,module,exports){
  54006. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  54007. var THREE = _dereq_('../lib/three');
  54008. var degToRad = THREE.Math.degToRad;
  54009. registerGeometry('torus', {
  54010. schema: {
  54011. arc: {default: 360},
  54012. radius: {default: 1, min: 0},
  54013. radiusTubular: {default: 0.2, min: 0},
  54014. segmentsRadial: {default: 36, min: 2, type: 'int'},
  54015. segmentsTubular: {default: 32, min: 3, type: 'int'}
  54016. },
  54017. init: function (data) {
  54018. this.geometry = new THREE.TorusGeometry(
  54019. data.radius, data.radiusTubular * 2, data.segmentsRadial, data.segmentsTubular,
  54020. degToRad(data.arc));
  54021. }
  54022. });
  54023. },{"../core/geometry":106,"../lib/three":154}],150:[function(_dereq_,module,exports){
  54024. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  54025. var THREE = _dereq_('../lib/three');
  54026. registerGeometry('torusKnot', {
  54027. schema: {
  54028. p: {default: 2, min: 1},
  54029. q: {default: 3, min: 1},
  54030. radius: {default: 1, min: 0},
  54031. radiusTubular: {default: 0.2, min: 0},
  54032. segmentsRadial: {default: 8, min: 3, type: 'int'},
  54033. segmentsTubular: {default: 100, min: 3, type: 'int'}
  54034. },
  54035. init: function (data) {
  54036. this.geometry = new THREE.TorusKnotGeometry(
  54037. data.radius, data.radiusTubular * 2, data.segmentsTubular, data.segmentsRadial,
  54038. data.p, data.q);
  54039. }
  54040. });
  54041. },{"../core/geometry":106,"../lib/three":154}],151:[function(_dereq_,module,exports){
  54042. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  54043. var THREE = _dereq_('../lib/three');
  54044. var quaternion = new THREE.Quaternion();
  54045. var rotateVector = new THREE.Vector3(0, 0, 1);
  54046. var uvMinVector = new THREE.Vector2();
  54047. var uvMaxVector = new THREE.Vector2();
  54048. var uvScaleVector = new THREE.Vector2();
  54049. registerGeometry('triangle', {
  54050. schema: {
  54051. vertexA: {type: 'vec3', default: {x: 0, y: 0.5, z: 0}},
  54052. vertexB: {type: 'vec3', default: {x: -0.5, y: -0.5, z: 0}},
  54053. vertexC: {type: 'vec3', default: {x: 0.5, y: -0.5, z: 0}}
  54054. },
  54055. init: function (data) {
  54056. var geometry;
  54057. var normal;
  54058. var triangle;
  54059. var uvA;
  54060. var uvB;
  54061. var uvC;
  54062. triangle = new THREE.Triangle();
  54063. triangle.a.set(data.vertexA.x, data.vertexA.y, data.vertexA.z);
  54064. triangle.b.set(data.vertexB.x, data.vertexB.y, data.vertexB.z);
  54065. triangle.c.set(data.vertexC.x, data.vertexC.y, data.vertexC.z);
  54066. normal = triangle.getNormal(new THREE.Vector3());
  54067. // Rotate the 3D triangle to be parallel to XY plane.
  54068. quaternion.setFromUnitVectors(normal, rotateVector);
  54069. uvA = triangle.a.clone().applyQuaternion(quaternion);
  54070. uvB = triangle.b.clone().applyQuaternion(quaternion);
  54071. uvC = triangle.c.clone().applyQuaternion(quaternion);
  54072. // Compute UVs.
  54073. // Normalize x/y values of UV so they are within 0 to 1.
  54074. uvMinVector.set(Math.min(uvA.x, uvB.x, uvC.x), Math.min(uvA.y, uvB.y, uvC.y));
  54075. uvMaxVector.set(Math.max(uvA.x, uvB.x, uvC.x), Math.max(uvA.y, uvB.y, uvC.y));
  54076. uvScaleVector.set(0, 0).subVectors(uvMaxVector, uvMinVector);
  54077. uvA = new THREE.Vector2().subVectors(uvA, uvMinVector).divide(uvScaleVector);
  54078. uvB = new THREE.Vector2().subVectors(uvB, uvMinVector).divide(uvScaleVector);
  54079. uvC = new THREE.Vector2().subVectors(uvC, uvMinVector).divide(uvScaleVector);
  54080. geometry = this.geometry = new THREE.Geometry();
  54081. geometry.vertices.push(triangle.a);
  54082. geometry.vertices.push(triangle.b);
  54083. geometry.vertices.push(triangle.c);
  54084. geometry.faces.push(new THREE.Face3(0, 1, 2, normal));
  54085. geometry.faceVertexUvs[0] = [[uvA, uvB, uvC]];
  54086. }
  54087. });
  54088. },{"../core/geometry":106,"../lib/three":154}],152:[function(_dereq_,module,exports){
  54089. // Polyfill `Promise`.
  54090. window.Promise = window.Promise || _dereq_('promise-polyfill');
  54091. // WebVR polyfill
  54092. // Check before the polyfill runs.
  54093. window.hasNativeWebVRImplementation = !!window.navigator.getVRDisplays ||
  54094. !!window.navigator.getVRDevices;
  54095. window.hasNativeWebXRImplementation = navigator.xr !== undefined;
  54096. // If WebXR is defined WebVRPolyfill does not initialize.
  54097. if (!window.hasNativeWebXRImplementation) {
  54098. var isIOSOlderThan10 = _dereq_('./utils/isIOSOlderThan10');
  54099. // Workaround for iOS Safari canvas sizing issues in stereo (webvr-polyfill/issues/102).
  54100. // Only for iOS on versions older than 10.
  54101. var bufferScale = isIOSOlderThan10(window.navigator.userAgent) ? 1 / window.devicePixelRatio : 1;
  54102. var WebVRPolyfill = _dereq_('webvr-polyfill');
  54103. var polyfillConfig = {
  54104. BUFFER_SCALE: bufferScale,
  54105. CARDBOARD_UI_DISABLED: true,
  54106. ROTATE_INSTRUCTIONS_DISABLED: true
  54107. };
  54108. window.webvrpolyfill = new WebVRPolyfill(polyfillConfig);
  54109. }
  54110. var utils = _dereq_('./utils/');
  54111. var debug = utils.debug;
  54112. var error = debug('A-Frame:error');
  54113. var warn = debug('A-Frame:warn');
  54114. if (window.document.currentScript && window.document.currentScript.parentNode !==
  54115. window.document.head && !window.debug) {
  54116. warn('Put the A-Frame <script> tag in the <head> of the HTML *before* the scene to ' +
  54117. 'ensure everything for A-Frame is properly registered before they are used from ' +
  54118. 'HTML.');
  54119. }
  54120. // Error if not using a server.
  54121. if (window.location.protocol === 'file:') {
  54122. error(
  54123. 'This HTML file is currently being served via the file:// protocol. ' +
  54124. 'Assets, textures, and models WILL NOT WORK due to cross-origin policy! ' +
  54125. 'Please use a local or hosted server: ' +
  54126. 'https://aframe.io/docs/0.5.0/introduction/getting-started.html#using-a-local-server.');
  54127. }
  54128. _dereq_('present'); // Polyfill `performance.now()`.
  54129. // CSS.
  54130. if (utils.device.isBrowserEnvironment) {
  54131. _dereq_('./style/aframe.css');
  54132. _dereq_('./style/rStats.css');
  54133. }
  54134. // Required before `AEntity` so that all components are registered.
  54135. var AScene = _dereq_('./core/scene/a-scene').AScene;
  54136. var components = _dereq_('./core/component').components;
  54137. var registerComponent = _dereq_('./core/component').registerComponent;
  54138. var registerGeometry = _dereq_('./core/geometry').registerGeometry;
  54139. var registerPrimitive = _dereq_('./extras/primitives/primitives').registerPrimitive;
  54140. var registerShader = _dereq_('./core/shader').registerShader;
  54141. var registerSystem = _dereq_('./core/system').registerSystem;
  54142. var shaders = _dereq_('./core/shader').shaders;
  54143. var systems = _dereq_('./core/system').systems;
  54144. // Exports THREE to window so three.js can be used without alteration.
  54145. var THREE = window.THREE = _dereq_('./lib/three');
  54146. var pkg = _dereq_('../package');
  54147. _dereq_('./components/index'); // Register standard components.
  54148. _dereq_('./geometries/index'); // Register standard geometries.
  54149. _dereq_('./shaders/index'); // Register standard shaders.
  54150. _dereq_('./systems/index'); // Register standard systems.
  54151. var ANode = _dereq_('./core/a-node');
  54152. var AEntity = _dereq_('./core/a-entity'); // Depends on ANode and core components.
  54153. _dereq_('./core/a-assets');
  54154. _dereq_('./core/a-cubemap');
  54155. _dereq_('./core/a-mixin');
  54156. // Extras.
  54157. _dereq_('./extras/components/');
  54158. _dereq_('./extras/primitives/');
  54159. console.log('A-Frame Version: 0.8.2 (Date 2018-12-23, Commit #d399a0d)');
  54160. console.log('three Version:', pkg.dependencies['three']);
  54161. console.log('WebVR Polyfill Version:', pkg.dependencies['webvr-polyfill']);
  54162. module.exports = window.AFRAME = {
  54163. AComponent: _dereq_('./core/component').Component,
  54164. AEntity: AEntity,
  54165. ANode: ANode,
  54166. ANIME: _dereq_('animejs'),
  54167. AScene: AScene,
  54168. components: components,
  54169. geometries: _dereq_('./core/geometry').geometries,
  54170. registerComponent: registerComponent,
  54171. registerElement: _dereq_('./core/a-register-element').registerElement,
  54172. registerGeometry: registerGeometry,
  54173. registerPrimitive: registerPrimitive,
  54174. registerShader: registerShader,
  54175. registerSystem: registerSystem,
  54176. primitives: {
  54177. getMeshMixin: _dereq_('./extras/primitives/getMeshMixin'),
  54178. primitives: _dereq_('./extras/primitives/primitives').primitives
  54179. },
  54180. scenes: _dereq_('./core/scene/scenes'),
  54181. schema: _dereq_('./core/schema'),
  54182. shaders: shaders,
  54183. systems: systems,
  54184. THREE: THREE,
  54185. utils: utils,
  54186. version: pkg.version
  54187. };
  54188. },{"../package":51,"./components/index":61,"./core/a-assets":99,"./core/a-cubemap":100,"./core/a-entity":101,"./core/a-mixin":102,"./core/a-node":103,"./core/a-register-element":104,"./core/component":105,"./core/geometry":106,"./core/scene/a-scene":108,"./core/scene/scenes":112,"./core/schema":114,"./core/shader":115,"./core/system":116,"./extras/components/":117,"./extras/primitives/":120,"./extras/primitives/getMeshMixin":119,"./extras/primitives/primitives":121,"./geometries/index":143,"./lib/three":154,"./shaders/index":156,"./style/aframe.css":161,"./style/rStats.css":162,"./systems/index":166,"./utils/":178,"./utils/isIOSOlderThan10":179,"animejs":2,"present":31,"promise-polyfill":33,"webvr-polyfill":46}],153:[function(_dereq_,module,exports){
  54189. window.aframeStats = function (scene) {
  54190. var _rS = null;
  54191. var _scene = scene;
  54192. var _values = {
  54193. te: {
  54194. caption: 'Entities'
  54195. },
  54196. lt: {
  54197. caption: 'Load Time'
  54198. }
  54199. };
  54200. var _groups = [ {
  54201. caption: 'A-Frame',
  54202. values: [ 'te', 'lt' ]
  54203. } ];
  54204. function _update () {
  54205. _rS('te').set(getEntityCount());
  54206. if (window.performance.getEntriesByName) {
  54207. _rS('lt').set(window.performance.getEntriesByName('render-started')[0].startTime.toFixed(0));
  54208. }
  54209. }
  54210. function getEntityCount () {
  54211. var elements = _scene.querySelectorAll('*');
  54212. Array.prototype.slice.call(elements).filter(function (el) {
  54213. return el.isEntity;
  54214. });
  54215. return elements.length;
  54216. }
  54217. function _start () {}
  54218. function _end () {}
  54219. function _attach (r) {
  54220. _rS = r;
  54221. }
  54222. return {
  54223. update: _update,
  54224. start: _start,
  54225. end: _end,
  54226. attach: _attach,
  54227. values: _values,
  54228. groups: _groups,
  54229. fractions: []
  54230. };
  54231. };
  54232. if (typeof module === 'object') {
  54233. module.exports = {
  54234. aframeStats: window.aframeStats
  54235. };
  54236. }
  54237. },{}],154:[function(_dereq_,module,exports){
  54238. (function (global){
  54239. var THREE = global.THREE = _dereq_('three');
  54240. // Allow cross-origin images to be loaded.
  54241. // This should not be on `THREE.Loader` nor `THREE.ImageUtils`.
  54242. // Must be on `THREE.TextureLoader`.
  54243. if (THREE.TextureLoader) {
  54244. THREE.TextureLoader.prototype.crossOrigin = 'anonymous';
  54245. }
  54246. // This is for images loaded from the model loaders.
  54247. if (THREE.ImageLoader) {
  54248. THREE.ImageLoader.prototype.crossOrigin = 'anonymous';
  54249. }
  54250. // In-memory caching for XHRs (for images, audio files, textures, etc.).
  54251. if (THREE.Cache) {
  54252. THREE.Cache.enabled = true;
  54253. }
  54254. // TODO: Eventually include these only if they are needed by a component.
  54255. _dereq_('three/examples/js/loaders/DRACOLoader'); // THREE.DRACOLoader
  54256. _dereq_('three/examples/js/loaders/GLTFLoader'); // THREE.GLTFLoader
  54257. _dereq_('three/examples/js/loaders/OBJLoader'); // THREE.OBJLoader
  54258. _dereq_('three/examples/js/loaders/MTLLoader'); // THREE.MTLLoader
  54259. _dereq_('three/examples/js/loaders/ColladaLoader'); // THREE.ColladaLoader
  54260. THREE.ColladaLoader.prototype.crossOrigin = 'anonymous';
  54261. THREE.GLTFLoader.prototype.crossOrigin = 'anonymous';
  54262. THREE.MTLLoader.prototype.crossOrigin = 'anonymous';
  54263. THREE.OBJLoader.prototype.crossOrigin = 'anonymous';
  54264. module.exports = THREE;
  54265. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  54266. },{"three":39,"three/examples/js/loaders/ColladaLoader":40,"three/examples/js/loaders/DRACOLoader":41,"three/examples/js/loaders/GLTFLoader":42,"three/examples/js/loaders/MTLLoader":43,"three/examples/js/loaders/OBJLoader":44}],155:[function(_dereq_,module,exports){
  54267. var registerShader = _dereq_('../core/shader').registerShader;
  54268. var THREE = _dereq_('../lib/three');
  54269. var utils = _dereq_('../utils/');
  54270. /**
  54271. * Flat shader using THREE.MeshBasicMaterial.
  54272. */
  54273. module.exports.Shader = registerShader('flat', {
  54274. schema: {
  54275. color: {type: 'color'},
  54276. fog: {default: true},
  54277. height: {default: 256},
  54278. offset: {type: 'vec2', default: {x: 0, y: 0}},
  54279. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  54280. src: {type: 'map'},
  54281. width: {default: 512},
  54282. wireframe: {default: false},
  54283. wireframeLinewidth: {default: 2}
  54284. },
  54285. /**
  54286. * Initializes the shader.
  54287. * Adds a reference from the scene to this entity as the camera.
  54288. */
  54289. init: function (data) {
  54290. this.materialData = {color: new THREE.Color()};
  54291. this.textureSrc = null;
  54292. getMaterialData(data, this.materialData);
  54293. this.material = new THREE.MeshBasicMaterial(this.materialData);
  54294. utils.material.updateMap(this, data);
  54295. },
  54296. update: function (data) {
  54297. this.updateMaterial(data);
  54298. utils.material.updateMap(this, data);
  54299. },
  54300. /**
  54301. * Updating existing material.
  54302. *
  54303. * @param {object} data - Material component data.
  54304. */
  54305. updateMaterial: function (data) {
  54306. var key;
  54307. getMaterialData(data, this.materialData);
  54308. for (key in this.materialData) {
  54309. this.material[key] = this.materialData[key];
  54310. }
  54311. }
  54312. });
  54313. /**
  54314. * Builds and normalize material data, normalizing stuff along the way.
  54315. *
  54316. * @param {object} data - Material data.
  54317. * @param {object} materialData - Object to reuse.
  54318. * @returns {object} Updated material data.
  54319. */
  54320. function getMaterialData (data, materialData) {
  54321. materialData.color.set(data.color);
  54322. materialData.fog = data.fog;
  54323. materialData.wireframe = data.wireframe;
  54324. materialData.wireframeLinewidth = data.wireframeLinewidth;
  54325. return materialData;
  54326. }
  54327. },{"../core/shader":115,"../lib/three":154,"../utils/":178}],156:[function(_dereq_,module,exports){
  54328. _dereq_('./flat');
  54329. _dereq_('./standard');
  54330. _dereq_('./sdf');
  54331. _dereq_('./msdf');
  54332. _dereq_('./ios10hls');
  54333. },{"./flat":155,"./ios10hls":157,"./msdf":158,"./sdf":159,"./standard":160}],157:[function(_dereq_,module,exports){
  54334. var registerShader = _dereq_('../core/shader').registerShader;
  54335. /**
  54336. * Custom shader for iOS 10 HTTP Live Streaming (HLS).
  54337. * For more information on HLS, see https://datatracker.ietf.org/doc/draft-pantos-http-live-streaming/
  54338. */
  54339. module.exports.Shader = registerShader('ios10hls', {
  54340. schema: {
  54341. src: {type: 'map', is: 'uniform'},
  54342. opacity: {type: 'number', is: 'uniform', default: 1}
  54343. },
  54344. vertexShader: [
  54345. 'varying vec2 vUV;',
  54346. 'void main(void) {',
  54347. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  54348. ' vUV = uv;',
  54349. '}'
  54350. ].join('\n'),
  54351. fragmentShader: [
  54352. 'uniform sampler2D src;',
  54353. 'uniform float opacity;',
  54354. 'varying vec2 vUV;',
  54355. 'void main() {',
  54356. ' vec2 offset = vec2(0, 0);',
  54357. ' vec2 repeat = vec2(1, 1);',
  54358. ' vec4 color = texture2D(src, vec2(vUV.x / repeat.x + offset.x, (1.0 - vUV.y) / repeat.y + offset.y)).bgra;',
  54359. ' gl_FragColor = vec4(color.rgb, opacity);',
  54360. '}'
  54361. ].join('\n')
  54362. });
  54363. },{"../core/shader":115}],158:[function(_dereq_,module,exports){
  54364. var registerShader = _dereq_('../core/shader').registerShader;
  54365. /**
  54366. * Multi-channel signed distance field.
  54367. * Used by text component.
  54368. */
  54369. module.exports.Shader = registerShader('msdf', {
  54370. schema: {
  54371. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  54372. color: {type: 'color', is: 'uniform', default: 'white'},
  54373. map: {type: 'map', is: 'uniform'},
  54374. negate: {type: 'boolean', is: 'uniform', default: true},
  54375. opacity: {type: 'number', is: 'uniform', default: 1.0}
  54376. },
  54377. raw: true,
  54378. vertexShader: [
  54379. 'attribute vec2 uv;',
  54380. 'attribute vec3 position;',
  54381. 'uniform mat4 projectionMatrix;',
  54382. 'uniform mat4 modelViewMatrix;',
  54383. 'varying vec2 vUV;',
  54384. 'void main(void) {',
  54385. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  54386. ' vUV = uv;',
  54387. '}'
  54388. ].join('\n'),
  54389. fragmentShader: [
  54390. '#ifdef GL_OES_standard_derivatives',
  54391. '#extension GL_OES_standard_derivatives: enable',
  54392. '#endif',
  54393. 'precision highp float;',
  54394. 'uniform bool negate;',
  54395. 'uniform float alphaTest;',
  54396. 'uniform float opacity;',
  54397. 'uniform sampler2D map;',
  54398. 'uniform vec3 color;',
  54399. 'varying vec2 vUV;',
  54400. 'float median(float r, float g, float b) {',
  54401. ' return max(min(r, g), min(max(r, g), b));',
  54402. '}',
  54403. // FIXME: Experimentally determined constants.
  54404. '#define BIG_ENOUGH 0.001',
  54405. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  54406. 'void main() {',
  54407. ' vec3 sample = texture2D(map, vUV).rgb;',
  54408. ' if (negate) { sample = 1.0 - sample; }',
  54409. ' float sigDist = median(sample.r, sample.g, sample.b) - 0.5;',
  54410. ' float alpha = clamp(sigDist / fwidth(sigDist) + 0.5, 0.0, 1.0);',
  54411. ' float dscale = 0.353505;',
  54412. ' vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
  54413. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  54414. ' // Do modified alpha test.',
  54415. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  54416. ' gl_FragColor = vec4(color.xyz, alpha * opacity);',
  54417. '}'
  54418. ].join('\n')
  54419. });
  54420. },{"../core/shader":115}],159:[function(_dereq_,module,exports){
  54421. var registerShader = _dereq_('../core/shader').registerShader;
  54422. /**
  54423. * Signed distance field.
  54424. * Used by text component.
  54425. */
  54426. module.exports.Shader = registerShader('sdf', {
  54427. schema: {
  54428. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  54429. color: {type: 'color', is: 'uniform', default: 'white'},
  54430. map: {type: 'map', is: 'uniform'},
  54431. opacity: {type: 'number', is: 'uniform', default: 1.0}
  54432. },
  54433. raw: true,
  54434. vertexShader: [
  54435. 'attribute vec2 uv;',
  54436. 'attribute vec3 position;',
  54437. 'uniform mat4 projectionMatrix;',
  54438. 'uniform mat4 modelViewMatrix;',
  54439. 'varying vec2 vUV;',
  54440. 'void main(void) {',
  54441. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  54442. ' vUV = uv;',
  54443. '}'
  54444. ].join('\n'),
  54445. fragmentShader: [
  54446. '#ifdef GL_OES_standard_derivatives',
  54447. '#extension GL_OES_standard_derivatives: enable',
  54448. '#endif',
  54449. 'precision highp float;',
  54450. 'uniform float alphaTest;',
  54451. 'uniform float opacity;',
  54452. 'uniform sampler2D map;',
  54453. 'uniform vec3 color;',
  54454. 'varying vec2 vUV;',
  54455. '#ifdef GL_OES_standard_derivatives',
  54456. ' float contour(float width, float value) {',
  54457. ' return smoothstep(0.5 - value, 0.5 + value, width);',
  54458. ' }',
  54459. '#else',
  54460. ' float aastep(float value, float afwidth) {',
  54461. ' return smoothstep(0.5 - afwidth, 0.5 + afwidth, value);',
  54462. ' }',
  54463. '#endif',
  54464. // FIXME: Experimentally determined constants.
  54465. '#define BIG_ENOUGH 0.001',
  54466. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  54467. '#define ALL_SMOOTH 0.4',
  54468. '#define ALL_ROUGH 0.02',
  54469. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  54470. 'void main() {',
  54471. // When we have derivatives and can get texel size for supersampling.
  54472. ' #ifdef GL_OES_standard_derivatives',
  54473. ' vec2 uv = vUV;',
  54474. ' vec4 texColor = texture2D(map, uv);',
  54475. ' float dist = texColor.a;',
  54476. ' float width = fwidth(dist);',
  54477. ' float alpha = contour(dist, width);',
  54478. ' float dscale = 0.353505;',
  54479. ' vec2 duv = dscale * (dFdx(uv) + dFdy(uv));',
  54480. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  54481. // Otherwise do weighted supersampling.
  54482. // FIXME: why this weighting?
  54483. ' if (isBigEnough <= BIG_ENOUGH) {',
  54484. ' vec4 box = vec4 (uv - duv, uv + duv);',
  54485. ' alpha = (alpha + 0.5 * (',
  54486. ' contour(texture2D(map, box.xy).a, width)',
  54487. ' + contour(texture2D(map, box.zw).a, width)',
  54488. ' + contour(texture2D(map, box.xw).a, width)',
  54489. ' + contour(texture2D(map, box.zy).a, width)',
  54490. ' )) / 3.0;',
  54491. ' }',
  54492. // Do modified alpha test.
  54493. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  54494. ' #else',
  54495. // When we don't have derivatives, use approximations.
  54496. ' vec4 texColor = texture2D(map, vUV);',
  54497. ' float value = texColor.a;',
  54498. // FIXME: if we understood font pixel dimensions, this could probably be improved
  54499. ' float afwidth = (1.0 / 32.0) * (1.4142135623730951 / (2.0 * gl_FragCoord.w));',
  54500. ' float alpha = aastep(value, afwidth);',
  54501. // Use gl_FragCoord.w to guess when we should blend.
  54502. // FIXME: If we understood font pixel dimensions, this could probably be improved.
  54503. ' 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);',
  54504. ' if (alpha < alphaTest) { if (ratio >= 1.0) { discard; return; } alpha = 0.0; }',
  54505. ' alpha = alpha * ratio + (1.0 - ratio) * value;',
  54506. ' if (ratio < 1.0 && alpha <= DISCARD_ALPHA) { discard; return; }',
  54507. ' #endif',
  54508. ' gl_FragColor = vec4(color, opacity * alpha);',
  54509. '}'
  54510. ].join('\n')
  54511. });
  54512. },{"../core/shader":115}],160:[function(_dereq_,module,exports){
  54513. var registerShader = _dereq_('../core/shader').registerShader;
  54514. var THREE = _dereq_('../lib/three');
  54515. var utils = _dereq_('../utils/');
  54516. var CubeLoader = new THREE.CubeTextureLoader();
  54517. var texturePromises = {};
  54518. /**
  54519. * Standard (physically-based) shader using THREE.MeshStandardMaterial.
  54520. */
  54521. module.exports.Shader = registerShader('standard', {
  54522. schema: {
  54523. ambientOcclusionMap: {type: 'map'},
  54524. ambientOcclusionMapIntensity: {default: 1},
  54525. ambientOcclusionTextureOffset: {type: 'vec2'},
  54526. ambientOcclusionTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  54527. color: {type: 'color'},
  54528. displacementMap: {type: 'map'},
  54529. displacementScale: {default: 1},
  54530. displacementBias: {default: 0.5},
  54531. displacementTextureOffset: {type: 'vec2'},
  54532. displacementTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  54533. emissive: {type: 'color', default: '#000'},
  54534. emissiveIntensity: {default: 1},
  54535. envMap: {default: ''},
  54536. fog: {default: true},
  54537. height: {default: 256},
  54538. metalness: {default: 0.0, min: 0.0, max: 1.0},
  54539. metalnessMap: {type: 'map'},
  54540. metalnessTextureOffset: {type: 'vec2'},
  54541. metalnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  54542. normalMap: {type: 'map'},
  54543. normalScale: {type: 'vec2', default: {x: 1, y: 1}},
  54544. normalTextureOffset: {type: 'vec2'},
  54545. normalTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  54546. offset: {type: 'vec2', default: {x: 0, y: 0}},
  54547. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  54548. roughness: {default: 0.5, min: 0.0, max: 1.0},
  54549. roughnessMap: {type: 'map'},
  54550. roughnessTextureOffset: {type: 'vec2'},
  54551. roughnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  54552. sphericalEnvMap: {type: 'map'},
  54553. src: {type: 'map'},
  54554. width: {default: 512},
  54555. wireframe: {default: false},
  54556. wireframeLinewidth: {default: 2}
  54557. },
  54558. /**
  54559. * Initializes the shader.
  54560. * Adds a reference from the scene to this entity as the camera.
  54561. */
  54562. init: function (data) {
  54563. this.materialData = {color: new THREE.Color(), emissive: new THREE.Color()};
  54564. getMaterialData(data, this.materialData);
  54565. this.material = new THREE.MeshStandardMaterial(this.materialData);
  54566. utils.material.updateMap(this, data);
  54567. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  54568. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  54569. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  54570. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  54571. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  54572. this.updateEnvMap(data);
  54573. },
  54574. update: function (data) {
  54575. this.updateMaterial(data);
  54576. utils.material.updateMap(this, data);
  54577. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  54578. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  54579. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  54580. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  54581. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  54582. this.updateEnvMap(data);
  54583. },
  54584. /**
  54585. * Updating existing material.
  54586. *
  54587. * @param {object} data - Material component data.
  54588. * @returns {object} Material.
  54589. */
  54590. updateMaterial: function (data) {
  54591. var key;
  54592. var material = this.material;
  54593. getMaterialData(data, this.materialData);
  54594. for (key in this.materialData) {
  54595. material[key] = this.materialData[key];
  54596. }
  54597. },
  54598. /**
  54599. * Handle environment cubemap. Textures are cached in texturePromises.
  54600. */
  54601. updateEnvMap: function (data) {
  54602. var self = this;
  54603. var material = this.material;
  54604. var envMap = data.envMap;
  54605. var sphericalEnvMap = data.sphericalEnvMap;
  54606. // No envMap defined or already loading.
  54607. if ((!envMap && !sphericalEnvMap) || this.isLoadingEnvMap) {
  54608. material.envMap = null;
  54609. material.needsUpdate = true;
  54610. return;
  54611. }
  54612. this.isLoadingEnvMap = true;
  54613. // if a spherical env map is defined then use it.
  54614. if (sphericalEnvMap) {
  54615. this.el.sceneEl.systems.material.loadTexture(sphericalEnvMap, {src: sphericalEnvMap}, function textureLoaded (texture) {
  54616. self.isLoadingEnvMap = false;
  54617. texture.mapping = THREE.SphericalReflectionMapping;
  54618. material.envMap = texture;
  54619. utils.material.handleTextureEvents(self.el, texture);
  54620. material.needsUpdate = true;
  54621. });
  54622. return;
  54623. }
  54624. // Another material is already loading this texture. Wait on promise.
  54625. if (texturePromises[envMap]) {
  54626. texturePromises[envMap].then(function (cube) {
  54627. self.isLoadingEnvMap = false;
  54628. material.envMap = cube;
  54629. utils.material.handleTextureEvents(self.el, cube);
  54630. material.needsUpdate = true;
  54631. });
  54632. return;
  54633. }
  54634. // Material is first to load this texture. Load and resolve texture.
  54635. texturePromises[envMap] = new Promise(function (resolve) {
  54636. utils.srcLoader.validateCubemapSrc(envMap, function loadEnvMap (urls) {
  54637. CubeLoader.load(urls, function (cube) {
  54638. // Texture loaded.
  54639. self.isLoadingEnvMap = false;
  54640. material.envMap = cube;
  54641. utils.material.handleTextureEvents(self.el, cube);
  54642. resolve(cube);
  54643. });
  54644. });
  54645. });
  54646. }
  54647. });
  54648. /**
  54649. * Builds and normalize material data, normalizing stuff along the way.
  54650. *
  54651. * @param {object} data - Material data.
  54652. * @param {object} materialData - Object to use.
  54653. * @returns {object} Updated materialData.
  54654. */
  54655. function getMaterialData (data, materialData) {
  54656. materialData.color.set(data.color);
  54657. materialData.emissive.set(data.emissive);
  54658. materialData.emissiveIntensity = data.emissiveIntensity;
  54659. materialData.fog = data.fog;
  54660. materialData.metalness = data.metalness;
  54661. materialData.roughness = data.roughness;
  54662. materialData.wireframe = data.wireframe;
  54663. materialData.wireframeLinewidth = data.wireframeLinewidth;
  54664. if (data.normalMap) { materialData.normalScale = data.normalScale; }
  54665. if (data.ambientOcclusionMap) {
  54666. materialData.aoMapIntensity = data.ambientOcclusionMapIntensity;
  54667. }
  54668. if (data.displacementMap) {
  54669. materialData.displacementScale = data.displacementScale;
  54670. materialData.displacementBias = data.displacementBias;
  54671. }
  54672. return materialData;
  54673. }
  54674. },{"../core/shader":115,"../lib/three":154,"../utils/":178}],161:[function(_dereq_,module,exports){
  54675. var css = "html.a-fullscreen{bottom:0;left:0;position:fixed;right:0;top:0}html.a-fullscreen body{height:100%;margin:0;overflow:hidden;padding:0;width:100%}html.a-fullscreen .a-canvas{width:100%!important;height:100%!important;top:0!important;left:0!important;right:0!important;bottom:0!important;position:fixed!important}html:not(.a-fullscreen) .a-enter-vr{right:5px;bottom:5px}:-webkit-full-screen{background-color:transparent}.a-hidden{display:none!important}.a-canvas{height:100%;left:0;position:absolute;top:0;width:100%}.a-canvas.a-grab-cursor:hover{cursor:grab;cursor:-moz-grab;cursor:-webkit-grab}.a-inspector-loader{background-color:#ed3160;position:fixed;left:3px;top:3px;padding:6px 10px;color:#fff;text-decoration:none;font-size:12px;font-family:Roboto,sans-serif;text-align:center;z-index:99999;width:204px}@keyframes dots-1{from{opacity:0}25%{opacity:1}}@keyframes dots-2{from{opacity:0}50%{opacity:1}}@keyframes dots-3{from{opacity:0}75%{opacity:1}}@-webkit-keyframes dots-1{from{opacity:0}25%{opacity:1}}@-webkit-keyframes dots-2{from{opacity:0}50%{opacity:1}}@-webkit-keyframes dots-3{from{opacity:0}75%{opacity:1}}.a-inspector-loader .dots span{animation:dots-1 2s infinite steps(1);-webkit-animation:dots-1 2s infinite steps(1)}.a-inspector-loader .dots span:first-child+span{animation-name:dots-2;-webkit-animation-name:dots-2}.a-inspector-loader .dots span:first-child+span+span{animation-name:dots-3;-webkit-animation-name:dots-3}a-scene{display:block;position:relative;height:100%;width:100%}a-assets,a-scene audio,a-scene img,a-scene video{display:none}.a-enter-vr-modal,.a-orientation-modal{font-family:Consolas,Andale Mono,Courier New,monospace}.a-enter-vr-modal a{border-bottom:1px solid #fff;padding:2px 0;text-decoration:none;transition:.1s color ease-in}.a-enter-vr-modal a:hover{background-color:#fff;color:#111;padding:2px 4px;position:relative;left:-4px}.a-enter-vr{font-family:sans-serif,monospace;font-size:13px;width:100%;font-weight:200;line-height:16px;position:absolute;right:20px;bottom:20px}.a-enter-vr-button,.a-enter-vr-modal,.a-enter-vr-modal a{color:#fff}.a-enter-vr-button{background:url(data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20245.82%20141.73%22%3E%3Cdefs%3E%3Cstyle%3E.a%7Bfill%3A%23fff%3Bfill-rule%3Aevenodd%3B%7D%3C%2Fstyle%3E%3C%2Fdefs%3E%3Ctitle%3Emask%3C%2Ftitle%3E%3Cpath%20class%3D%22a%22%20d%3D%22M175.56%2C111.37c-22.52%2C0-40.77-18.84-40.77-42.07S153%2C27.24%2C175.56%2C27.24s40.77%2C18.84%2C40.77%2C42.07S198.08%2C111.37%2C175.56%2C111.37ZM26.84%2C69.31c0-23.23%2C18.25-42.07%2C40.77-42.07s40.77%2C18.84%2C40.77%2C42.07-18.26%2C42.07-40.77%2C42.07S26.84%2C92.54%2C26.84%2C69.31ZM27.27%2C0C11.54%2C0%2C0%2C12.34%2C0%2C28.58V110.9c0%2C16.24%2C11.54%2C30.83%2C27.27%2C30.83H99.57c2.17%2C0%2C4.19-1.83%2C5.4-3.7L116.47%2C118a8%2C8%2C0%2C0%2C1%2C12.52-.18l11.51%2C20.34c1.2%2C1.86%2C3.22%2C3.61%2C5.39%2C3.61h72.29c15.74%2C0%2C27.63-14.6%2C27.63-30.83V28.58C245.82%2C12.34%2C233.93%2C0%2C218.19%2C0H27.27Z%22%2F%3E%3C%2Fsvg%3E) 50% 50%/70% 70% no-repeat rgba(0,0,0,.35);border:0;bottom:0;cursor:pointer;min-width:50px;min-height:30px;padding-right:5%;padding-top:4%;position:absolute;right:0;transition:background-color .05s ease;-webkit-transition:background-color .05s ease;z-index:9999}.a-enter-vr-button:active,.a-enter-vr-button:hover{background-color:#666}[data-a-enter-vr-no-webvr] .a-enter-vr-button{border-color:#666;opacity:.65}[data-a-enter-vr-no-webvr] .a-enter-vr-button:active,[data-a-enter-vr-no-webvr] .a-enter-vr-button:hover{background-color:rgba(0,0,0,.35);cursor:not-allowed}.a-enter-vr-modal{background-color:#666;border-radius:0;display:none;min-height:32px;margin-right:70px;padding:9px;width:280px;right:2%;position:absolute}.a-enter-vr-modal:after{border-bottom:10px solid transparent;border-left:10px solid #666;border-top:10px solid transparent;display:inline-block;content:'';position:absolute;right:-5px;top:5px;width:0;height:0}.a-enter-vr-modal a,.a-enter-vr-modal p{display:inline}.a-enter-vr-modal p{margin:0}.a-enter-vr-modal p:after{content:' '}[data-a-enter-vr-no-headset].a-enter-vr:hover .a-enter-vr-modal,[data-a-enter-vr-no-webvr].a-enter-vr:hover .a-enter-vr-modal{display:block}.a-orientation-modal{background:url(data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20xmlns%3Axlink%3D%22http%3A//www.w3.org/1999/xlink%22%20version%3D%221.1%22%20x%3D%220px%22%20y%3D%220px%22%20viewBox%3D%220%200%2090%2090%22%20enable-background%3D%22new%200%200%2090%2090%22%20xml%3Aspace%3D%22preserve%22%3E%3Cpolygon%20points%3D%220%2C0%200%2C0%200%2C0%20%22%3E%3C/polygon%3E%3Cg%3E%3Cpath%20d%3D%22M71.545%2C48.145h-31.98V20.743c0-2.627-2.138-4.765-4.765-4.765H18.456c-2.628%2C0-4.767%2C2.138-4.767%2C4.765v42.789%20%20%20c0%2C2.628%2C2.138%2C4.766%2C4.767%2C4.766h5.535v0.959c0%2C2.628%2C2.138%2C4.765%2C4.766%2C4.765h42.788c2.628%2C0%2C4.766-2.137%2C4.766-4.765V52.914%20%20%20C76.311%2C50.284%2C74.173%2C48.145%2C71.545%2C48.145z%20M18.455%2C16.935h16.344c2.1%2C0%2C3.808%2C1.708%2C3.808%2C3.808v27.401H37.25V22.636%20%20%20c0-0.264-0.215-0.478-0.479-0.478H16.482c-0.264%2C0-0.479%2C0.214-0.479%2C0.478v36.585c0%2C0.264%2C0.215%2C0.478%2C0.479%2C0.478h7.507v7.644%20%20%20h-5.534c-2.101%2C0-3.81-1.709-3.81-3.81V20.743C14.645%2C18.643%2C16.354%2C16.935%2C18.455%2C16.935z%20M16.96%2C23.116h19.331v25.031h-7.535%20%20%20c-2.628%2C0-4.766%2C2.139-4.766%2C4.768v5.828h-7.03V23.116z%20M71.545%2C73.064H28.757c-2.101%2C0-3.81-1.708-3.81-3.808V52.914%20%20%20c0-2.102%2C1.709-3.812%2C3.81-3.812h42.788c2.1%2C0%2C3.809%2C1.71%2C3.809%2C3.812v16.343C75.354%2C71.356%2C73.645%2C73.064%2C71.545%2C73.064z%22%3E%3C/path%3E%3Cpath%20d%3D%22M28.919%2C58.424c-1.466%2C0-2.659%2C1.193-2.659%2C2.66c0%2C1.466%2C1.193%2C2.658%2C2.659%2C2.658c1.468%2C0%2C2.662-1.192%2C2.662-2.658%20%20%20C31.581%2C59.617%2C30.387%2C58.424%2C28.919%2C58.424z%20M28.919%2C62.786c-0.939%2C0-1.703-0.764-1.703-1.702c0-0.939%2C0.764-1.704%2C1.703-1.704%20%20%20c0.94%2C0%2C1.705%2C0.765%2C1.705%2C1.704C30.623%2C62.022%2C29.858%2C62.786%2C28.919%2C62.786z%22%3E%3C/path%3E%3Cpath%20d%3D%22M69.654%2C50.461H33.069c-0.264%2C0-0.479%2C0.215-0.479%2C0.479v20.288c0%2C0.264%2C0.215%2C0.478%2C0.479%2C0.478h36.585%20%20%20c0.263%2C0%2C0.477-0.214%2C0.477-0.478V50.939C70.131%2C50.676%2C69.917%2C50.461%2C69.654%2C50.461z%20M69.174%2C51.417V70.75H33.548V51.417H69.174z%22%3E%3C/path%3E%3Cpath%20d%3D%22M45.201%2C30.296c6.651%2C0%2C12.233%2C5.351%2C12.551%2C11.977l-3.033-2.638c-0.193-0.165-0.507-0.142-0.675%2C0.048%20%20%20c-0.174%2C0.198-0.153%2C0.501%2C0.045%2C0.676l3.883%2C3.375c0.09%2C0.075%2C0.198%2C0.115%2C0.312%2C0.115c0.141%2C0%2C0.273-0.061%2C0.362-0.166%20%20%20l3.371-3.877c0.173-0.2%2C0.151-0.502-0.047-0.675c-0.194-0.166-0.508-0.144-0.676%2C0.048l-2.592%2C2.979%20%20%20c-0.18-3.417-1.629-6.605-4.099-9.001c-2.538-2.461-5.877-3.817-9.404-3.817c-0.264%2C0-0.479%2C0.215-0.479%2C0.479%20%20%20C44.72%2C30.083%2C44.936%2C30.296%2C45.201%2C30.296z%22%3E%3C/path%3E%3C/g%3E%3C/svg%3E) center/50% 50% no-repeat rgba(244,244,244,1);bottom:0;font-size:14px;font-weight:600;left:0;line-height:20px;right:0;position:fixed;top:0;z-index:9999999}.a-orientation-modal:after{color:#666;content:\"Insert phone into Cardboard holder.\";display:block;position:absolute;text-align:center;top:70%;transform:translateY(-70%);width:100%}.a-orientation-modal button{background:url(data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20xmlns%3Axlink%3D%22http%3A//www.w3.org/1999/xlink%22%20version%3D%221.1%22%20x%3D%220px%22%20y%3D%220px%22%20viewBox%3D%220%200%20100%20100%22%20enable-background%3D%22new%200%200%20100%20100%22%20xml%3Aspace%3D%22preserve%22%3E%3Cpath%20fill%3D%22%23000000%22%20d%3D%22M55.209%2C50l17.803-17.803c1.416-1.416%2C1.416-3.713%2C0-5.129c-1.416-1.417-3.713-1.417-5.129%2C0L50.08%2C44.872%20%20L32.278%2C27.069c-1.416-1.417-3.714-1.417-5.129%2C0c-1.417%2C1.416-1.417%2C3.713%2C0%2C5.129L44.951%2C50L27.149%2C67.803%20%20c-1.417%2C1.416-1.417%2C3.713%2C0%2C5.129c0.708%2C0.708%2C1.636%2C1.062%2C2.564%2C1.062c0.928%2C0%2C1.856-0.354%2C2.564-1.062L50.08%2C55.13l17.803%2C17.802%20%20c0.708%2C0.708%2C1.637%2C1.062%2C2.564%2C1.062s1.856-0.354%2C2.564-1.062c1.416-1.416%2C1.416-3.713%2C0-5.129L55.209%2C50z%22%3E%3C/path%3E%3C/svg%3E) no-repeat;border:none;height:50px;text-indent:-9999px;width:50px}.a-loader-title{background-color:rgba(0,0,0,.6);font-family:sans-serif,monospace;text-align:center;font-size:20px;height:50px;font-weight:300;line-height:50px;position:absolute;right:0;left:0;top:0;color:#fff}"; (_dereq_("browserify-css").createStyle(css, { "href": "src/style/aframe.css"})); module.exports = css;
  54676. },{"browserify-css":5}],162:[function(_dereq_,module,exports){
  54677. 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;
  54678. },{"browserify-css":5}],163:[function(_dereq_,module,exports){
  54679. var constants = _dereq_('../constants/');
  54680. var registerSystem = _dereq_('../core/system').registerSystem;
  54681. var DEFAULT_CAMERA_ATTR = 'data-aframe-default-camera';
  54682. /**
  54683. * Camera system. Manages which camera is active among multiple cameras in scene.
  54684. *
  54685. * @member {object} activeCameraEl - Active camera entity.
  54686. */
  54687. module.exports.System = registerSystem('camera', {
  54688. init: function () {
  54689. this.activeCameraEl = null;
  54690. this.render = this.render.bind(this);
  54691. this.unwrapRender = this.unwrapRender.bind(this);
  54692. this.wrapRender = this.wrapRender.bind(this);
  54693. this.initialCameraFound = false;
  54694. this.numUserCameras = 0;
  54695. this.numUserCamerasChecked = 0;
  54696. this.setupInitialCamera();
  54697. },
  54698. /**
  54699. * Setup initial camera, either searching for camera or
  54700. * creating a default camera if user has not added one during the initial scene traversal.
  54701. * We want sceneEl.camera to be ready, set, and initialized before the rest of the scene
  54702. * loads.
  54703. *
  54704. * Default camera offset height is at average eye level (~1.6m).
  54705. */
  54706. setupInitialCamera: function () {
  54707. var cameraEls;
  54708. var i;
  54709. var sceneEl = this.sceneEl;
  54710. var self = this;
  54711. // Camera already defined or the one defined it is an spectator one.
  54712. if (sceneEl.camera && !sceneEl.camera.el.getAttribute('camera').spectator) {
  54713. sceneEl.emit('cameraready', {cameraEl: sceneEl.camera.el});
  54714. return;
  54715. }
  54716. // Search for initial user-defined camera.
  54717. cameraEls = sceneEl.querySelectorAll('a-camera, [camera]');
  54718. // No user cameras, create default one.
  54719. if (!cameraEls.length) {
  54720. this.createDefaultCamera();
  54721. return;
  54722. }
  54723. this.numUserCameras = cameraEls.length;
  54724. for (i = 0; i < cameraEls.length; i++) {
  54725. cameraEls[i].addEventListener('object3dset', function (evt) {
  54726. if (evt.detail.type !== 'camera') { return; }
  54727. self.checkUserCamera(this);
  54728. });
  54729. // Load camera and wait for camera to initialize.
  54730. if (cameraEls[i].isNode) {
  54731. cameraEls[i].load();
  54732. } else {
  54733. cameraEls[i].addEventListener('nodeready', function () {
  54734. this.load();
  54735. });
  54736. }
  54737. }
  54738. },
  54739. /**
  54740. * Check if a user-defined camera entity is appropriate to be initial camera.
  54741. * (active + non-spectator).
  54742. *
  54743. * Keep track of the number of cameras we checked and whether we found one.
  54744. */
  54745. checkUserCamera: function (cameraEl) {
  54746. var cameraData;
  54747. var sceneEl = this.el.sceneEl;
  54748. this.numUserCamerasChecked++;
  54749. // Already found one.
  54750. if (this.initialCameraFound) { return; }
  54751. // Check if camera is appropriate for being the initial camera.
  54752. cameraData = cameraEl.getAttribute('camera');
  54753. if (!cameraData.active || cameraData.spectator) {
  54754. // No user cameras eligible, create default camera.
  54755. if (this.numUserCamerasChecked === this.numUserCameras) {
  54756. this.createDefaultCamera();
  54757. }
  54758. return;
  54759. }
  54760. this.initialCameraFound = true;
  54761. sceneEl.camera = cameraEl.getObject3D('camera');
  54762. sceneEl.emit('cameraready', {cameraEl: cameraEl});
  54763. },
  54764. createDefaultCamera: function () {
  54765. var defaultCameraEl;
  54766. var sceneEl = this.sceneEl;
  54767. // Set up default camera.
  54768. defaultCameraEl = document.createElement('a-entity');
  54769. defaultCameraEl.setAttribute('camera', {active: true});
  54770. defaultCameraEl.setAttribute('position', {
  54771. x: 0,
  54772. y: constants.DEFAULT_CAMERA_HEIGHT,
  54773. z: 0
  54774. });
  54775. defaultCameraEl.setAttribute('wasd-controls', '');
  54776. defaultCameraEl.setAttribute('look-controls', '');
  54777. defaultCameraEl.setAttribute(constants.AFRAME_INJECTED, '');
  54778. defaultCameraEl.addEventListener('object3dset', function (evt) {
  54779. if (evt.detail.type !== 'camera') { return; }
  54780. sceneEl.camera = evt.detail.object;
  54781. sceneEl.emit('cameraready', {cameraEl: defaultCameraEl});
  54782. });
  54783. sceneEl.appendChild(defaultCameraEl);
  54784. defaultCameraEl.load();
  54785. },
  54786. /**
  54787. * Set a different active camera.
  54788. * When we choose a (sort of) random scene camera as the replacement, set its `active` to
  54789. * true. The camera component will call `setActiveCamera` and handle passing the torch to
  54790. * the new camera.
  54791. */
  54792. disableActiveCamera: function () {
  54793. var cameraEls;
  54794. var newActiveCameraEl;
  54795. cameraEls = this.sceneEl.querySelectorAll('[camera]');
  54796. newActiveCameraEl = cameraEls[cameraEls.length - 1];
  54797. newActiveCameraEl.setAttribute('camera', 'active', true);
  54798. },
  54799. /**
  54800. * Set active camera to be used by renderer.
  54801. * Removes the default camera (if present).
  54802. * Disables all other cameras in the scene.
  54803. *
  54804. * @param {Element} newCameraEl - Entity with camera component.
  54805. */
  54806. setActiveCamera: function (newCameraEl) {
  54807. var cameraEl;
  54808. var cameraEls;
  54809. var i;
  54810. var newCamera;
  54811. var previousCamera = this.activeCameraEl;
  54812. var sceneEl = this.sceneEl;
  54813. // Same camera.
  54814. newCamera = newCameraEl.getObject3D('camera');
  54815. if (!newCamera || newCameraEl === this.activeCameraEl) { return; }
  54816. // Grab the default camera.
  54817. var defaultCameraWrapper = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  54818. var defaultCameraEl = defaultCameraWrapper &&
  54819. defaultCameraWrapper.querySelector('[camera]');
  54820. // Remove default camera if new camera is not the default camera.
  54821. if (newCameraEl !== defaultCameraEl) { removeDefaultCamera(sceneEl); }
  54822. // Make new camera active.
  54823. this.activeCameraEl = newCameraEl;
  54824. this.activeCameraEl.play();
  54825. sceneEl.camera = newCamera;
  54826. // Disable current camera
  54827. if (previousCamera) {
  54828. previousCamera.setAttribute('camera', 'active', false);
  54829. }
  54830. // Disable other cameras in the scene
  54831. cameraEls = sceneEl.querySelectorAll('[camera]');
  54832. for (i = 0; i < cameraEls.length; i++) {
  54833. cameraEl = cameraEls[i];
  54834. if (!cameraEl.isEntity || newCameraEl === cameraEl) { continue; }
  54835. cameraEl.setAttribute('camera', 'active', false);
  54836. cameraEl.pause();
  54837. }
  54838. sceneEl.emit('camera-set-active', {cameraEl: newCameraEl});
  54839. },
  54840. /**
  54841. * Set spectator camera to render the scene on a 2D display.
  54842. *
  54843. * @param {Element} newCameraEl - Entity with camera component.
  54844. */
  54845. setSpectatorCamera: function (newCameraEl) {
  54846. var newCamera;
  54847. var previousCamera = this.spectatorCameraEl;
  54848. var sceneEl = this.sceneEl;
  54849. var spectatorCameraEl;
  54850. // Same camera.
  54851. newCamera = newCameraEl.getObject3D('camera');
  54852. if (!newCamera || newCameraEl === this.spectatorCameraEl) { return; }
  54853. // Disable current camera
  54854. if (previousCamera) {
  54855. previousCamera.setAttribute('camera', 'spectator', false);
  54856. }
  54857. spectatorCameraEl = this.spectatorCameraEl = newCameraEl;
  54858. sceneEl.addEventListener('enter-vr', this.wrapRender);
  54859. sceneEl.addEventListener('exit-vr', this.unwrapRender);
  54860. spectatorCameraEl.setAttribute('camera', 'active', false);
  54861. spectatorCameraEl.play();
  54862. sceneEl.emit('camera-set-spectator', {cameraEl: newCameraEl});
  54863. },
  54864. /**
  54865. * Disables current spectator camera.
  54866. */
  54867. disableSpectatorCamera: function () {
  54868. this.spectatorCameraEl = undefined;
  54869. },
  54870. /**
  54871. * Wrap the render method of the renderer to render
  54872. * the spectator camera after vrDisplay.submitFrame.
  54873. */
  54874. wrapRender: function () {
  54875. if (!this.spectatorCameraEl) { return; }
  54876. this.originalRender = this.sceneEl.renderer.render;
  54877. this.sceneEl.renderer.render = this.render;
  54878. },
  54879. unwrapRender: function () {
  54880. if (!this.originalRender) { return; }
  54881. this.sceneEl.renderer.render = this.originalRender;
  54882. this.originalRender = undefined;
  54883. },
  54884. render: function (scene, camera, renderTarget) {
  54885. var isVREnabled;
  54886. var sceneEl = this.sceneEl;
  54887. var spectatorCamera;
  54888. isVREnabled = sceneEl.renderer.vr.enabled;
  54889. this.originalRender.call(sceneEl.renderer, scene, camera, renderTarget);
  54890. if (!this.spectatorCameraEl || sceneEl.isMobile || !isVREnabled) { return; }
  54891. spectatorCamera = this.spectatorCameraEl.components.camera.camera;
  54892. sceneEl.renderer.vr.enabled = false;
  54893. this.originalRender.call(sceneEl.renderer, scene, spectatorCamera);
  54894. sceneEl.renderer.vr.enabled = isVREnabled;
  54895. }
  54896. });
  54897. /**
  54898. * Remove injected default camera from scene, if present.
  54899. *
  54900. * @param {Element} sceneEl
  54901. */
  54902. function removeDefaultCamera (sceneEl) {
  54903. var defaultCamera;
  54904. var camera = sceneEl.camera;
  54905. if (!camera) { return; }
  54906. // Remove default camera if present.
  54907. defaultCamera = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  54908. if (!defaultCamera) { return; }
  54909. sceneEl.removeChild(defaultCamera);
  54910. }
  54911. },{"../constants/":97,"../core/system":116}],164:[function(_dereq_,module,exports){
  54912. var geometries = _dereq_('../core/geometry').geometries;
  54913. var registerSystem = _dereq_('../core/system').registerSystem;
  54914. var THREE = _dereq_('../lib/three');
  54915. /**
  54916. * System for geometry component.
  54917. * Handle geometry caching.
  54918. *
  54919. * @member {object} cache - Mapping of stringified component data to THREE.Geometry objects.
  54920. * @member {object} cacheCount - Keep track of number of entities using a geometry to
  54921. * know whether to dispose on removal.
  54922. */
  54923. module.exports.System = registerSystem('geometry', {
  54924. init: function () {
  54925. this.cache = {};
  54926. this.cacheCount = {};
  54927. },
  54928. /**
  54929. * Reset cache. Mainly for testing.
  54930. */
  54931. clearCache: function () {
  54932. this.cache = {};
  54933. this.cacheCount = {};
  54934. },
  54935. /**
  54936. * Attempt to retrieve from cache.
  54937. *
  54938. * @returns {Object|null} A geometry if it exists, else null.
  54939. */
  54940. getOrCreateGeometry: function (data) {
  54941. var cache = this.cache;
  54942. var cachedGeometry;
  54943. var hash;
  54944. // Skip all caching logic.
  54945. if (data.skipCache) { return createGeometry(data); }
  54946. // Try to retrieve from cache first.
  54947. hash = this.hash(data);
  54948. cachedGeometry = cache[hash];
  54949. incrementCacheCount(this.cacheCount, hash);
  54950. if (cachedGeometry) { return cachedGeometry; }
  54951. // Create geometry.
  54952. cachedGeometry = createGeometry(data);
  54953. // Cache and return geometry.
  54954. cache[hash] = cachedGeometry;
  54955. return cachedGeometry;
  54956. },
  54957. /**
  54958. * Let system know that an entity is no longer using a geometry.
  54959. */
  54960. unuseGeometry: function (data) {
  54961. var cache = this.cache;
  54962. var cacheCount = this.cacheCount;
  54963. var geometry;
  54964. var hash;
  54965. if (data.skipCache) { return; }
  54966. hash = this.hash(data);
  54967. if (!cache[hash]) { return; }
  54968. decrementCacheCount(cacheCount, hash);
  54969. // Another entity is still using this geometry. No need to do anything.
  54970. if (cacheCount[hash] > 0) { return; }
  54971. // No more entities are using this geometry. Dispose.
  54972. geometry = cache[hash];
  54973. geometry.dispose();
  54974. delete cache[hash];
  54975. delete cacheCount[hash];
  54976. },
  54977. /**
  54978. * Use JSON.stringify to turn component data into hash.
  54979. * Should be deterministic within a single browser engine.
  54980. * If not, then look into json-stable-stringify.
  54981. */
  54982. hash: function (data) {
  54983. return JSON.stringify(data);
  54984. }
  54985. });
  54986. /**
  54987. * Create geometry using component data.
  54988. *
  54989. * @param {object} data - Component data.
  54990. * @returns {object} Geometry.
  54991. */
  54992. function createGeometry (data) {
  54993. var geometryType = data.primitive;
  54994. var GeometryClass = geometries[geometryType] && geometries[geometryType].Geometry;
  54995. var geometryInstance = new GeometryClass();
  54996. if (!GeometryClass) { throw new Error('Unknown geometry `' + geometryType + '`'); }
  54997. geometryInstance.init(data);
  54998. return toBufferGeometry(geometryInstance.geometry, data.buffer);
  54999. }
  55000. /**
  55001. * Decreate count of entity using a geometry.
  55002. */
  55003. function decrementCacheCount (cacheCount, hash) {
  55004. cacheCount[hash]--;
  55005. }
  55006. /**
  55007. * Increase count of entity using a geometry.
  55008. */
  55009. function incrementCacheCount (cacheCount, hash) {
  55010. cacheCount[hash] = cacheCount[hash] === undefined ? 1 : cacheCount[hash] + 1;
  55011. }
  55012. /**
  55013. * Transform geometry to BufferGeometry if `doBuffer`.
  55014. *
  55015. * @param {object} geometry
  55016. * @param {boolean} doBuffer
  55017. * @returns {object} Geometry.
  55018. */
  55019. function toBufferGeometry (geometry, doBuffer) {
  55020. var bufferGeometry;
  55021. if (!doBuffer) { return geometry; }
  55022. bufferGeometry = new THREE.BufferGeometry().fromGeometry(geometry);
  55023. bufferGeometry.metadata = {type: geometry.type, parameters: geometry.parameters || {}};
  55024. geometry.dispose(); // Dispose no longer needed non-buffer geometry.
  55025. return bufferGeometry;
  55026. }
  55027. },{"../core/geometry":106,"../core/system":116,"../lib/three":154}],165:[function(_dereq_,module,exports){
  55028. var registerSystem = _dereq_('../core/system').registerSystem;
  55029. var THREE = _dereq_('../lib/three');
  55030. /**
  55031. * glTF model system.
  55032. *
  55033. * Configures glTF loading options. Models using glTF compression require that a Draco decoder be
  55034. * provided externally.
  55035. *
  55036. * @param {string} dracoDecoderPath - Base path from which to load Draco decoder library.
  55037. */
  55038. module.exports.System = registerSystem('gltf-model', {
  55039. schema: {
  55040. dracoDecoderPath: {default: ''}
  55041. },
  55042. init: function () {
  55043. var path = this.data.dracoDecoderPath;
  55044. THREE.DRACOLoader.setDecoderPath(path);
  55045. this.dracoLoader = path ? new THREE.DRACOLoader() : null;
  55046. },
  55047. getDRACOLoader: function () {
  55048. return this.dracoLoader;
  55049. }
  55050. });
  55051. },{"../core/system":116,"../lib/three":154}],166:[function(_dereq_,module,exports){
  55052. _dereq_('./camera');
  55053. _dereq_('./geometry');
  55054. _dereq_('./gltf-model');
  55055. _dereq_('./light');
  55056. _dereq_('./material');
  55057. _dereq_('./shadow');
  55058. _dereq_('./tracked-controls-webvr');
  55059. _dereq_('./tracked-controls-webxr');
  55060. },{"./camera":163,"./geometry":164,"./gltf-model":165,"./light":167,"./material":168,"./shadow":169,"./tracked-controls-webvr":170,"./tracked-controls-webxr":171}],167:[function(_dereq_,module,exports){
  55061. var registerSystem = _dereq_('../core/system').registerSystem;
  55062. var bind = _dereq_('../utils/bind');
  55063. var constants = _dereq_('../constants/');
  55064. var DEFAULT_LIGHT_ATTR = 'data-aframe-default-light';
  55065. /**
  55066. * Light system.
  55067. *
  55068. * Prescribes default lighting if not specified (one ambient, one directional).
  55069. * Removes default lighting from the scene when a new light is added.
  55070. *
  55071. * @param {bool} defaultLights - Whether default lighting are defined.
  55072. * @param {bool} userDefinedLights - Whether user lighting is defined.
  55073. */
  55074. module.exports.System = registerSystem('light', {
  55075. schema: {
  55076. defaultLightsEnabled: {default: true}
  55077. },
  55078. init: function () {
  55079. this.defaultLights = false;
  55080. this.userDefinedLights = false;
  55081. // Wait for all entities to fully load before checking for existence of lights.
  55082. // Since entities wait for <a-assets> to load, any lights attaching to the scene
  55083. // will do so asynchronously.
  55084. this.sceneEl.addEventListener('loaded', bind(this.setupDefaultLights, this));
  55085. },
  55086. /**
  55087. * Notify scene that light has been added and to remove the default.
  55088. *
  55089. * @param {object} el - element holding the light component.
  55090. */
  55091. registerLight: function (el) {
  55092. if (!el.hasAttribute(DEFAULT_LIGHT_ATTR)) {
  55093. // User added a light, remove default lights through DOM.
  55094. this.removeDefaultLights();
  55095. this.userDefinedLights = true;
  55096. }
  55097. },
  55098. removeDefaultLights: function () {
  55099. var defaultLights;
  55100. var sceneEl = this.sceneEl;
  55101. if (!this.defaultLights) { return; }
  55102. defaultLights = document.querySelectorAll('[' + DEFAULT_LIGHT_ATTR + ']');
  55103. for (var i = 0; i < defaultLights.length; i++) {
  55104. sceneEl.removeChild(defaultLights[i]);
  55105. }
  55106. this.defaultLights = false;
  55107. },
  55108. /**
  55109. * Prescibe default lights to the scene.
  55110. * Does so by injecting markup such that this state is not invisible.
  55111. * These lights are removed if the user adds any lights.
  55112. */
  55113. setupDefaultLights: function () {
  55114. var sceneEl = this.sceneEl;
  55115. var ambientLight;
  55116. var directionalLight;
  55117. if (this.userDefinedLights || this.defaultLights || !this.data.defaultLightsEnabled) {
  55118. return;
  55119. }
  55120. ambientLight = document.createElement('a-entity');
  55121. ambientLight.setAttribute('light', {color: '#BBB', type: 'ambient'});
  55122. ambientLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  55123. ambientLight.setAttribute(constants.AFRAME_INJECTED, '');
  55124. sceneEl.appendChild(ambientLight);
  55125. directionalLight = document.createElement('a-entity');
  55126. directionalLight.setAttribute('light', {color: '#FFF', intensity: 0.6, castShadow: true});
  55127. directionalLight.setAttribute('position', {x: -0.5, y: 1, z: 1});
  55128. directionalLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  55129. directionalLight.setAttribute(constants.AFRAME_INJECTED, '');
  55130. sceneEl.appendChild(directionalLight);
  55131. this.defaultLights = true;
  55132. }
  55133. });
  55134. },{"../constants/":97,"../core/system":116,"../utils/bind":172}],168:[function(_dereq_,module,exports){
  55135. var registerSystem = _dereq_('../core/system').registerSystem;
  55136. var THREE = _dereq_('../lib/three');
  55137. var utils = _dereq_('../utils/');
  55138. var isHLS = _dereq_('../utils/material').isHLS;
  55139. var bind = utils.bind;
  55140. var debug = utils.debug;
  55141. var error = debug('components:texture:error');
  55142. var TextureLoader = new THREE.TextureLoader();
  55143. var warn = debug('components:texture:warn');
  55144. TextureLoader.setCrossOrigin('anonymous');
  55145. /**
  55146. * System for material component.
  55147. * Handle material registration, updates (for fog), and texture caching.
  55148. *
  55149. * @member {object} materials - Registered materials.
  55150. * @member {object} textureCounts - Number of times each texture is used. Tracked
  55151. * separately from textureCache, because the cache (1) is populated in
  55152. * multiple places, and (2) may be cleared at any time.
  55153. * @member {object} textureCache - Texture cache for:
  55154. * - Images: textureCache has mapping of src -> repeat -> cached three.js texture.
  55155. * - Videos: textureCache has mapping of videoElement -> cached three.js texture.
  55156. */
  55157. module.exports.System = registerSystem('material', {
  55158. init: function () {
  55159. this.materials = {};
  55160. this.textureCounts = {};
  55161. this.textureCache = {};
  55162. this.sceneEl.addEventListener(
  55163. 'materialtextureloaded',
  55164. bind(this.onMaterialTextureLoaded, this)
  55165. );
  55166. },
  55167. clearTextureCache: function () {
  55168. this.textureCache = {};
  55169. },
  55170. /**
  55171. * Determine whether `src` is a image or video. Then try to load the asset, then call back.
  55172. *
  55173. * @param {string, or element} src - Texture URL or element.
  55174. * @param {string} data - Relevant texture data used for caching.
  55175. * @param {function} cb - Callback to pass texture to.
  55176. */
  55177. loadTexture: function (src, data, cb) {
  55178. var self = this;
  55179. // Canvas.
  55180. if (src.tagName === 'CANVAS') {
  55181. this.loadCanvas(src, data, cb);
  55182. return;
  55183. }
  55184. // Video element.
  55185. if (src.tagName === 'VIDEO') {
  55186. if (!src.src && !src.srcObject && !src.childElementCount) {
  55187. warn('Video element was defined with neither `source` elements nor `src` / `srcObject` attributes.');
  55188. }
  55189. this.loadVideo(src, data, cb);
  55190. return;
  55191. }
  55192. utils.srcLoader.validateSrc(src, loadImageCb, loadVideoCb);
  55193. function loadImageCb (src) { self.loadImage(src, data, cb); }
  55194. function loadVideoCb (src) { self.loadVideo(src, data, cb); }
  55195. },
  55196. /**
  55197. * High-level function for loading image textures (THREE.Texture).
  55198. *
  55199. * @param {Element|string} src - Texture source.
  55200. * @param {object} data - Texture data.
  55201. * @param {function} cb - Callback to pass texture to.
  55202. */
  55203. loadImage: function (src, data, handleImageTextureLoaded) {
  55204. var hash = this.hash(data);
  55205. var textureCache = this.textureCache;
  55206. // Texture already being loaded or already loaded. Wait on promise.
  55207. if (textureCache[hash]) {
  55208. textureCache[hash].then(handleImageTextureLoaded);
  55209. return;
  55210. }
  55211. // Texture not yet being loaded. Start loading it.
  55212. textureCache[hash] = loadImageTexture(src, data);
  55213. textureCache[hash].then(handleImageTextureLoaded);
  55214. },
  55215. /**
  55216. * High-level function for loading canvas textures (THREE.Texture).
  55217. *
  55218. * @param {Element|string} src - Texture source.
  55219. * @param {object} data - Texture data.
  55220. * @param {function} cb - Callback to pass texture to.
  55221. */
  55222. loadCanvas: function (src, data, cb) {
  55223. var texture;
  55224. texture = new THREE.CanvasTexture(src);
  55225. setTextureProperties(texture, data);
  55226. cb(texture);
  55227. },
  55228. /**
  55229. * Load video texture (THREE.VideoTexture).
  55230. * Which is just an image texture that RAFs + needsUpdate.
  55231. * Note that creating a video texture is synchronous unlike loading an image texture.
  55232. * Made asynchronous to be consistent with image textures.
  55233. *
  55234. * @param {Element|string} src - Texture source.
  55235. * @param {object} data - Texture data.
  55236. * @param {function} cb - Callback to pass texture to.
  55237. */
  55238. loadVideo: function (src, data, cb) {
  55239. var hash;
  55240. var texture;
  55241. var textureCache = this.textureCache;
  55242. var videoEl;
  55243. var videoTextureResult;
  55244. function handleVideoTextureLoaded (result) {
  55245. result.texture.needsUpdate = true;
  55246. cb(result.texture, result.videoEl);
  55247. }
  55248. // Video element provided.
  55249. if (typeof src !== 'string') {
  55250. // Check cache before creating texture.
  55251. videoEl = src;
  55252. hash = this.hashVideo(data, videoEl);
  55253. if (textureCache[hash]) {
  55254. textureCache[hash].then(handleVideoTextureLoaded);
  55255. return;
  55256. }
  55257. // If not in cache, fix up the attributes then start to create the texture.
  55258. fixVideoAttributes(videoEl);
  55259. }
  55260. // Only URL provided. Use video element to create texture.
  55261. videoEl = videoEl || createVideoEl(src, data.width, data.height);
  55262. // Generated video element already cached. Use that.
  55263. hash = this.hashVideo(data, videoEl);
  55264. if (textureCache[hash]) {
  55265. textureCache[hash].then(handleVideoTextureLoaded);
  55266. return;
  55267. }
  55268. // Create new video texture.
  55269. texture = new THREE.VideoTexture(videoEl);
  55270. texture.minFilter = THREE.LinearFilter;
  55271. setTextureProperties(texture, data);
  55272. // If iOS and video is HLS, do some hacks.
  55273. if (this.sceneEl.isIOS &&
  55274. isHLS(videoEl.src || videoEl.getAttribute('src'),
  55275. videoEl.type || videoEl.getAttribute('type'))) {
  55276. // Actually BGRA. Tell shader to correct later.
  55277. texture.format = THREE.RGBAFormat;
  55278. texture.needsCorrectionBGRA = true;
  55279. // Apparently needed for HLS. Tell shader to correct later.
  55280. texture.flipY = false;
  55281. texture.needsCorrectionFlipY = true;
  55282. }
  55283. // Cache as promise to be consistent with image texture caching.
  55284. videoTextureResult = {texture: texture, videoEl: videoEl};
  55285. textureCache[hash] = Promise.resolve(videoTextureResult);
  55286. handleVideoTextureLoaded(videoTextureResult);
  55287. },
  55288. /**
  55289. * Create a hash of the material properties for texture cache key.
  55290. */
  55291. hash: function (data) {
  55292. if (data.src.tagName) {
  55293. // Since `data.src` can be an element, parse out the string if necessary for the hash.
  55294. data = utils.extendDeep({}, data);
  55295. data.src = data.src.src;
  55296. }
  55297. return JSON.stringify(data);
  55298. },
  55299. hashVideo: function (data, videoEl) {
  55300. return calculateVideoCacheHash(data, videoEl);
  55301. },
  55302. /**
  55303. * Keep track of material in case an update trigger is needed (e.g., fog).
  55304. *
  55305. * @param {object} material
  55306. */
  55307. registerMaterial: function (material) {
  55308. this.materials[material.uuid] = material;
  55309. },
  55310. /**
  55311. * Stop tracking material, and dispose of any textures not being used by
  55312. * another material component.
  55313. *
  55314. * @param {object} material
  55315. */
  55316. unregisterMaterial: function (material) {
  55317. delete this.materials[material.uuid];
  55318. // If any textures on this material are no longer in use, dispose of them.
  55319. var textureCounts = this.textureCounts;
  55320. Object.keys(material)
  55321. .filter(function (propName) {
  55322. return material[propName] && material[propName].isTexture;
  55323. })
  55324. .forEach(function (mapName) {
  55325. textureCounts[material[mapName].uuid]--;
  55326. if (textureCounts[material[mapName].uuid] <= 0) {
  55327. material[mapName].dispose();
  55328. }
  55329. });
  55330. },
  55331. /**
  55332. * Trigger update to all registered materials.
  55333. */
  55334. updateMaterials: function (material) {
  55335. var materials = this.materials;
  55336. Object.keys(materials).forEach(function (uuid) {
  55337. materials[uuid].needsUpdate = true;
  55338. });
  55339. },
  55340. /**
  55341. * Track textures used by material components, so that they can be safely
  55342. * disposed when no longer in use. Textures must be registered here, and not
  55343. * through registerMaterial(), because textures may not be attached at the
  55344. * time the material is registered.
  55345. *
  55346. * @param {Event} e
  55347. */
  55348. onMaterialTextureLoaded: function (e) {
  55349. if (!this.textureCounts[e.detail.texture.uuid]) {
  55350. this.textureCounts[e.detail.texture.uuid] = 0;
  55351. }
  55352. this.textureCounts[e.detail.texture.uuid]++;
  55353. }
  55354. });
  55355. /**
  55356. * Calculates consistent hash from a video element using its attributes.
  55357. * If the video element has an ID, use that.
  55358. * Else build a hash that looks like `src:myvideo.mp4;height:200;width:400;`.
  55359. *
  55360. * @param data {object} - Texture data such as repeat.
  55361. * @param videoEl {Element} - Video element.
  55362. * @returns {string}
  55363. */
  55364. function calculateVideoCacheHash (data, videoEl) {
  55365. var i;
  55366. var id = videoEl.getAttribute('id');
  55367. var hash;
  55368. var videoAttributes;
  55369. if (id) { return id; }
  55370. // Calculate hash using sorted video attributes.
  55371. hash = '';
  55372. videoAttributes = data || {};
  55373. for (i = 0; i < videoEl.attributes.length; i++) {
  55374. videoAttributes[videoEl.attributes[i].name] = videoEl.attributes[i].value;
  55375. }
  55376. Object.keys(videoAttributes).sort().forEach(function (name) {
  55377. hash += name + ':' + videoAttributes[name] + ';';
  55378. });
  55379. return hash;
  55380. }
  55381. /**
  55382. * Load image texture.
  55383. *
  55384. * @private
  55385. * @param {string|object} src - An <img> element or url to an image file.
  55386. * @param {object} data - Data to set texture properties like `repeat`.
  55387. * @returns {Promise} Resolves once texture is loaded.
  55388. */
  55389. function loadImageTexture (src, data) {
  55390. return new Promise(doLoadImageTexture);
  55391. function doLoadImageTexture (resolve, reject) {
  55392. var isEl = typeof src !== 'string';
  55393. function resolveTexture (texture) {
  55394. setTextureProperties(texture, data);
  55395. texture.needsUpdate = true;
  55396. resolve(texture);
  55397. }
  55398. // Create texture from an element.
  55399. if (isEl) {
  55400. resolveTexture(new THREE.Texture(src));
  55401. return;
  55402. }
  55403. // Request and load texture from src string. THREE will create underlying element.
  55404. // Use THREE.TextureLoader (src, onLoad, onProgress, onError) to load texture.
  55405. TextureLoader.load(
  55406. src,
  55407. resolveTexture,
  55408. function () { /* no-op */ },
  55409. function (xhr) {
  55410. error('`$s` could not be fetched (Error code: %s; Response: %s)', xhr.status,
  55411. xhr.statusText);
  55412. }
  55413. );
  55414. }
  55415. }
  55416. /**
  55417. * Set texture properties such as repeat and offset.
  55418. *
  55419. * @param {object} data - With keys like `repeat`.
  55420. */
  55421. function setTextureProperties (texture, data) {
  55422. var offset = data.offset || {x: 0, y: 0};
  55423. var repeat = data.repeat || {x: 1, y: 1};
  55424. var npot = data.npot || false;
  55425. // To support NPOT textures, wrap must be ClampToEdge (not Repeat),
  55426. // and filters must not use mipmaps (i.e. Nearest or Linear).
  55427. if (npot) {
  55428. texture.wrapS = THREE.ClampToEdgeWrapping;
  55429. texture.wrapT = THREE.ClampToEdgeWrapping;
  55430. texture.magFilter = THREE.LinearFilter;
  55431. texture.minFilter = THREE.LinearFilter;
  55432. }
  55433. // Don't bother setting repeat if it is 1/1. Power-of-two is required to repeat.
  55434. if (repeat.x !== 1 || repeat.y !== 1) {
  55435. texture.wrapS = THREE.RepeatWrapping;
  55436. texture.wrapT = THREE.RepeatWrapping;
  55437. texture.repeat.set(repeat.x, repeat.y);
  55438. }
  55439. // Don't bother setting offset if it is 0/0.
  55440. if (offset.x !== 0 || offset.y !== 0) {
  55441. texture.offset.set(offset.x, offset.y);
  55442. }
  55443. }
  55444. /**
  55445. * Create video element to be used as a texture.
  55446. *
  55447. * @param {string} src - Url to a video file.
  55448. * @param {number} width - Width of the video.
  55449. * @param {number} height - Height of the video.
  55450. * @returns {Element} Video element.
  55451. */
  55452. function createVideoEl (src, width, height) {
  55453. var videoEl = document.createElement('video');
  55454. videoEl.width = width;
  55455. videoEl.height = height;
  55456. // Support inline videos for iOS webviews.
  55457. videoEl.setAttribute('playsinline', '');
  55458. videoEl.setAttribute('webkit-playsinline', '');
  55459. videoEl.autoplay = true;
  55460. videoEl.loop = true;
  55461. videoEl.crossOrigin = 'anonymous';
  55462. videoEl.addEventListener('error', function () {
  55463. warn('`$s` is not a valid video', src);
  55464. }, true);
  55465. videoEl.src = src;
  55466. return videoEl;
  55467. }
  55468. /**
  55469. * Fixes a video element's attributes to prevent developers from accidentally passing the
  55470. * wrong attribute values to commonly misused video attributes.
  55471. *
  55472. * <video> does not treat `autoplay`, `controls`, `crossorigin`, `loop`, and `preload` as
  55473. * as booleans. Existence of those attributes will mean truthy.
  55474. *
  55475. * For example, translates <video loop="false"> to <video>.
  55476. *
  55477. * @see https://developer.mozilla.org/docs/Web/HTML/Element/video#Attributes
  55478. * @param {Element} videoEl - Video element.
  55479. * @returns {Element} Video element with the correct properties updated.
  55480. */
  55481. function fixVideoAttributes (videoEl) {
  55482. videoEl.autoplay = videoEl.hasAttribute('autoplay') && videoEl.getAttribute('autoplay') !== 'false';
  55483. videoEl.controls = videoEl.hasAttribute('controls') && videoEl.getAttribute('controls') !== 'false';
  55484. if (videoEl.getAttribute('loop') === 'false') {
  55485. videoEl.removeAttribute('loop');
  55486. }
  55487. if (videoEl.getAttribute('preload') === 'false') {
  55488. videoEl.preload = 'none';
  55489. }
  55490. videoEl.crossOrigin = videoEl.crossOrigin || 'anonymous';
  55491. // To support inline videos in iOS webviews.
  55492. videoEl.setAttribute('playsinline', '');
  55493. videoEl.setAttribute('webkit-playsinline', '');
  55494. return videoEl;
  55495. }
  55496. },{"../core/system":116,"../lib/three":154,"../utils/":178,"../utils/material":180}],169:[function(_dereq_,module,exports){
  55497. var registerSystem = _dereq_('../core/system').registerSystem;
  55498. var THREE = _dereq_('../lib/three');
  55499. var SHADOW_MAP_TYPE_MAP = {
  55500. basic: THREE.BasicShadowMap,
  55501. pcf: THREE.PCFShadowMap,
  55502. pcfsoft: THREE.PCFSoftShadowMap
  55503. };
  55504. /**
  55505. * Shadow system.
  55506. *
  55507. * Enabled automatically when one or more shadow components are added to the scene, the system sets
  55508. * options on the WebGLRenderer for configuring shadow appearance.
  55509. */
  55510. module.exports.System = registerSystem('shadow', {
  55511. schema: {
  55512. autoUpdate: {default: true},
  55513. type: {default: 'pcf', oneOf: ['basic', 'pcf', 'pcfsoft']}
  55514. },
  55515. init: function () {
  55516. var sceneEl = this.sceneEl;
  55517. var data = this.data;
  55518. this.shadowMapEnabled = false;
  55519. if (!sceneEl.renderer) { return; } // For tests.
  55520. sceneEl.renderer.shadowMap.type = SHADOW_MAP_TYPE_MAP[data.type];
  55521. sceneEl.renderer.shadowMap.autoUpdate = data.autoUpdate;
  55522. this.setShadowMapEnabled(this.shadowMapEnabled);
  55523. },
  55524. /**
  55525. * Enables/disables the renderer shadow map.
  55526. * @param {boolean} enabled
  55527. */
  55528. setShadowMapEnabled: function (enabled) {
  55529. var renderer = this.sceneEl.renderer;
  55530. this.shadowMapEnabled = enabled;
  55531. if (renderer) {
  55532. renderer.shadowMap.enabled = enabled;
  55533. }
  55534. }
  55535. });
  55536. },{"../core/system":116,"../lib/three":154}],170:[function(_dereq_,module,exports){
  55537. var registerSystem = _dereq_('../core/system').registerSystem;
  55538. var utils = _dereq_('../utils');
  55539. /**
  55540. * Tracked controls system.
  55541. * Maintain list with available tracked controllers.
  55542. */
  55543. module.exports.System = registerSystem('tracked-controls-webvr', {
  55544. init: function () {
  55545. var self = this;
  55546. this.controllers = [];
  55547. this.updateControllerList();
  55548. this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
  55549. if (!navigator.getVRDisplays) { return; }
  55550. this.sceneEl.addEventListener('enter-vr', function () {
  55551. navigator.getVRDisplays().then(function (displays) {
  55552. if (displays.length) { self.vrDisplay = displays[0]; }
  55553. });
  55554. });
  55555. },
  55556. tick: function () {
  55557. if (navigator.userAgent.indexOf('Chrome') !== -1) {
  55558. // Call getGamepads for Chrome for it to update. Not sure if needed in future.
  55559. navigator.getGamepads && navigator.getGamepads();
  55560. }
  55561. this.throttledUpdateControllerList();
  55562. },
  55563. /**
  55564. * Update controller list.
  55565. */
  55566. updateControllerList: function () {
  55567. var controllers = this.controllers;
  55568. var gamepad;
  55569. var gamepads;
  55570. var i;
  55571. var prevCount;
  55572. gamepads = navigator.getGamepads && navigator.getGamepads();
  55573. if (!gamepads) { return; }
  55574. prevCount = controllers.length;
  55575. controllers.length = 0;
  55576. for (i = 0; i < gamepads.length; ++i) {
  55577. gamepad = gamepads[i];
  55578. if (gamepad && gamepad.pose) {
  55579. controllers.push(gamepad);
  55580. }
  55581. }
  55582. if (controllers.length !== prevCount) {
  55583. this.el.emit('controllersupdated', undefined, false);
  55584. }
  55585. }
  55586. });
  55587. },{"../core/system":116,"../utils":178}],171:[function(_dereq_,module,exports){
  55588. var registerSystem = _dereq_('../core/system').registerSystem;
  55589. /**
  55590. * Tracked controls system.
  55591. * Maintain list with available tracked controllers.
  55592. */
  55593. module.exports.System = registerSystem('tracked-controls-webxr', {
  55594. init: function () {
  55595. this.controllers = [];
  55596. this.addSessionEventListeners = this.addSessionEventListeners.bind(this);
  55597. this.onInputSourcesChange = this.onInputSourcesChange.bind(this);
  55598. this.addSessionEventListeners();
  55599. this.el.sceneEl.addEventListener('enter-vr', this.addSessionEventListeners);
  55600. },
  55601. addSessionEventListeners: function () {
  55602. var sceneEl = this.el;
  55603. if (!sceneEl.xrSession) { return; }
  55604. this.onInputSourcesChange();
  55605. sceneEl.xrSession.addEventListener('inputsourceschange', this.onInputSourcesChange);
  55606. },
  55607. onInputSourcesChange: function () {
  55608. this.controllers = this.el.xrSession.getInputSources();
  55609. this.el.emit('controllersupdated', undefined, false);
  55610. }
  55611. });
  55612. },{"../core/system":116}],172:[function(_dereq_,module,exports){
  55613. /**
  55614. * Faster version of Function.prototype.bind
  55615. * @param {Function} fn - Function to wrap.
  55616. * @param {Object} ctx - What to bind as context.
  55617. * @param {...*} arguments - Arguments to pass through.
  55618. */
  55619. module.exports = function bind (fn, ctx/* , arg1, arg2 */) {
  55620. return (function (prependedArgs) {
  55621. return function bound () {
  55622. // Concat the bound function arguments with those passed to original bind
  55623. var args = prependedArgs.concat(Array.prototype.slice.call(arguments, 0));
  55624. return fn.apply(ctx, args);
  55625. };
  55626. })(Array.prototype.slice.call(arguments, 2));
  55627. };
  55628. },{}],173:[function(_dereq_,module,exports){
  55629. /* global THREE */
  55630. var debug = _dereq_('./debug');
  55631. var extend = _dereq_('object-assign');
  55632. var warn = debug('utils:coordinates:warn');
  55633. // Order of coordinates parsed by coordinates.parse.
  55634. var COORDINATE_KEYS = ['x', 'y', 'z', 'w'];
  55635. // Coordinate string regex. Handles negative, positive, and decimals.
  55636. var regex = /^\s*((-?\d*\.{0,1}\d+(e-?\d+)?)\s+){2,3}(-?\d*\.{0,1}\d+(e-?\d+)?)\s*$/;
  55637. module.exports.regex = regex;
  55638. var OBJECT = 'object';
  55639. var whitespaceRegex = /\s+/g;
  55640. /**
  55641. * Parses coordinates from an "x y z" string.
  55642. * Example: "3 10 -5" to {x: 3, y: 10, z: -5}.
  55643. *
  55644. * @param {string} val - An "x y z" string.
  55645. * @param {string} defaults - fallback value.
  55646. * @returns {object} An object with keys [x, y, z].
  55647. */
  55648. function parse (value, defaultVec) {
  55649. var coordinate;
  55650. var defaultVal;
  55651. var key;
  55652. var i;
  55653. var vec;
  55654. var x;
  55655. var y;
  55656. var z;
  55657. var w;
  55658. if (value && value instanceof Object) {
  55659. x = value.x === undefined ? defaultVec && defaultVec.x : value.x;
  55660. y = value.y === undefined ? defaultVec && defaultVec.y : value.y;
  55661. z = value.z === undefined ? defaultVec && defaultVec.z : value.z;
  55662. w = value.w === undefined ? defaultVec && defaultVec.w : value.w;
  55663. if (x !== undefined) { value.x = parseIfString(x); }
  55664. if (y !== undefined) { value.y = parseIfString(y); }
  55665. if (z !== undefined) { value.z = parseIfString(z); }
  55666. if (w !== undefined) { value.w = parseIfString(w); }
  55667. return value;
  55668. }
  55669. if (value === null || value === undefined) {
  55670. return typeof defaultVec === OBJECT ? extend({}, defaultVec) : defaultVec;
  55671. }
  55672. coordinate = value.trim().split(whitespaceRegex);
  55673. vec = {};
  55674. for (i = 0; i < COORDINATE_KEYS.length; i++) {
  55675. key = COORDINATE_KEYS[i];
  55676. if (coordinate[i]) {
  55677. vec[key] = parseFloat(coordinate[i], 10);
  55678. } else {
  55679. defaultVal = defaultVec && defaultVec[key];
  55680. if (defaultVal === undefined) { continue; }
  55681. vec[key] = parseIfString(defaultVal);
  55682. }
  55683. }
  55684. return vec;
  55685. }
  55686. module.exports.parse = parse;
  55687. /**
  55688. * Stringify coordinates from an object with keys [x y z].
  55689. * Example: {x: 3, y: 10, z: -5} to "3 10 -5".
  55690. *
  55691. * @param {object|string} data - An object with keys [x y z].
  55692. * @returns {string} An "x y z" string.
  55693. */
  55694. function stringify (data) {
  55695. var str;
  55696. if (typeof data !== OBJECT) { return data; }
  55697. str = data.x + ' ' + data.y;
  55698. if (data.z) { str += ' ' + data.z; }
  55699. if (data.w) { str += ' ' + data.w; }
  55700. return str;
  55701. }
  55702. module.exports.stringify = stringify;
  55703. /**
  55704. * @returns {bool}
  55705. */
  55706. function isCoordinates (value) {
  55707. return regex.test(value);
  55708. }
  55709. module.exports.isCoordinates = isCoordinates;
  55710. module.exports.isCoordinate = function (value) {
  55711. warn('`AFRAME.utils.isCoordinate` has been renamed to `AFRAME.utils.isCoordinates`');
  55712. return isCoordinates(value);
  55713. };
  55714. function parseIfString (val) {
  55715. if (val.constructor === String) {
  55716. return parseFloat(val, 10);
  55717. }
  55718. return val;
  55719. }
  55720. /**
  55721. * Convert {x, y, z} object to three.js Vector3.
  55722. */
  55723. module.exports.toVector3 = function (vec3) {
  55724. return new THREE.Vector3(vec3.x, vec3.y, vec3.z);
  55725. };
  55726. },{"./debug":174,"object-assign":25}],174:[function(_dereq_,module,exports){
  55727. (function (process){
  55728. var debugLib = _dereq_('debug');
  55729. var extend = _dereq_('object-assign');
  55730. var settings = {
  55731. colors: {
  55732. debug: 'gray',
  55733. error: 'red',
  55734. info: 'gray',
  55735. warn: 'orange'
  55736. }
  55737. };
  55738. /**
  55739. * Monkeypatches `debug` so we can colorize error/warning messages.
  55740. *
  55741. * (See issue: https://github.com/visionmedia/debug/issues/137)
  55742. */
  55743. var debug = function (namespace) {
  55744. var d = debugLib(namespace);
  55745. d.color = getDebugNamespaceColor(namespace);
  55746. return d;
  55747. };
  55748. extend(debug, debugLib);
  55749. /**
  55750. * Returns the type of the namespace (e.g., `error`, `warn`).
  55751. *
  55752. * @param {String} namespace
  55753. * The debug logger's namespace (e.g., `components:geometry:warn`).
  55754. * @returns {String} The type of the namespace (e.g., `warn`).
  55755. * @api private
  55756. */
  55757. function getDebugNamespaceType (namespace) {
  55758. var chunks = namespace.split(':');
  55759. return chunks[chunks.length - 1]; // Return the last one
  55760. }
  55761. /**
  55762. * Returns the color of the namespace (e.g., `orange`).
  55763. *
  55764. * @param {String} namespace
  55765. * The debug logger's namespace (e.g., `components:geometry:warn`).
  55766. * @returns {String} The color of the namespace (e.g., `orange`).
  55767. * @api private
  55768. */
  55769. function getDebugNamespaceColor (namespace) {
  55770. var type = getDebugNamespaceType(namespace);
  55771. var color = settings.colors && settings.colors[type];
  55772. return color || null;
  55773. }
  55774. /**
  55775. * Returns `localStorage` if possible.
  55776. *
  55777. * This is necessary because Safari throws when a user disables
  55778. * cookies or `localStorage` and you attempt to access it.
  55779. *
  55780. * @returns {localStorage}
  55781. * @api private
  55782. */
  55783. function storage () {
  55784. try {
  55785. return window.localStorage;
  55786. } catch (e) {
  55787. }
  55788. }
  55789. /**
  55790. * To enable console logging, type this in the Console of your Dev Tools:
  55791. *
  55792. * localStorage.logs = 1
  55793. *
  55794. * To disable console logging:
  55795. *
  55796. * localStorage.logs = 0
  55797. *
  55798. */
  55799. var ls = storage();
  55800. if (ls && (parseInt(ls.logs, 10) || ls.logs === 'true')) {
  55801. debug.enable('*');
  55802. } else {
  55803. debug.enable('*:error,*:info,*:warn');
  55804. }
  55805. if (process.browser) { window.logs = debug; }
  55806. module.exports = debug;
  55807. }).call(this,_dereq_('_process'))
  55808. },{"_process":32,"debug":8,"object-assign":25}],175:[function(_dereq_,module,exports){
  55809. (function (process){
  55810. var vrDisplay;
  55811. // Support both WebVR and WebXR APIs.
  55812. if (navigator.xr) {
  55813. navigator.xr.requestDevice().then(function (device) {
  55814. device.supportsSession({immersive: true, exclusive: true}).then(function () {
  55815. var sceneEl = document.querySelector('a-scene');
  55816. vrDisplay = device;
  55817. if (sceneEl) { sceneEl.emit('displayconnected', {vrDisplay: vrDisplay}); }
  55818. });
  55819. });
  55820. } else {
  55821. if (navigator.getVRDisplays) {
  55822. navigator.getVRDisplays().then(function (displays) {
  55823. var sceneEl = document.querySelector('a-scene');
  55824. vrDisplay = displays.length && displays[0];
  55825. if (sceneEl) { sceneEl.emit('displayconnected', {vrDisplay: vrDisplay}); }
  55826. });
  55827. }
  55828. }
  55829. module.exports.isWebXRAvailable = navigator.xr !== undefined;
  55830. function getVRDisplay () { return vrDisplay; }
  55831. module.exports.getVRDisplay = getVRDisplay;
  55832. /**
  55833. * Determine if a headset is connected by checking if a vrDisplay is available.
  55834. */
  55835. function checkHeadsetConnected () { return !!getVRDisplay(); }
  55836. module.exports.checkHeadsetConnected = checkHeadsetConnected;
  55837. /**
  55838. * Check for positional tracking.
  55839. */
  55840. function checkHasPositionalTracking () {
  55841. var vrDisplay = getVRDisplay();
  55842. if (isMobile() || isGearVR()) { return false; }
  55843. return vrDisplay && vrDisplay.capabilities.hasPosition;
  55844. }
  55845. module.exports.checkHasPositionalTracking = checkHasPositionalTracking;
  55846. /**
  55847. * Checks if browser is mobile.
  55848. * @return {Boolean} True if mobile browser detected.
  55849. */
  55850. var isMobile = (function () {
  55851. var _isMobile = false;
  55852. (function (a) {
  55853. // eslint-disable-next-line no-useless-escape
  55854. 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))) {
  55855. _isMobile = true;
  55856. }
  55857. if (isIOS() || isTablet() || isR7()) {
  55858. _isMobile = true;
  55859. }
  55860. })(window.navigator.userAgent || window.navigator.vendor || window.opera);
  55861. return function () { return _isMobile; };
  55862. })();
  55863. module.exports.isMobile = isMobile;
  55864. /**
  55865. * Detect tablet devices.
  55866. * @param {string} mockUserAgent - Allow passing a mock user agent for testing.
  55867. */
  55868. function isTablet (mockUserAgent) {
  55869. var userAgent = mockUserAgent || window.navigator.userAgent;
  55870. return /ipad|Nexus (7|9)|xoom|sch-i800|playbook|tablet|kindle/i.test(userAgent);
  55871. }
  55872. module.exports.isTablet = isTablet;
  55873. function isIOS () {
  55874. return /iPad|iPhone|iPod/.test(window.navigator.platform);
  55875. }
  55876. module.exports.isIOS = isIOS;
  55877. function isGearVR () {
  55878. return /SamsungBrowser.+Mobile VR/i.test(window.navigator.userAgent);
  55879. }
  55880. module.exports.isGearVR = isGearVR;
  55881. /**
  55882. * Detect Oculus Go device
  55883. */
  55884. function isOculusGo () {
  55885. return /Pacific Build.+OculusBrowser.+SamsungBrowser.+Mobile VR/i.test(window.navigator.userAgent);
  55886. }
  55887. module.exports.isOculusGo = isOculusGo;
  55888. function isR7 () {
  55889. return /R7 Build/.test(window.navigator.userAgent);
  55890. }
  55891. module.exports.isR7 = isR7;
  55892. /**
  55893. * Checks mobile device orientation.
  55894. * @return {Boolean} True if landscape orientation.
  55895. */
  55896. module.exports.isLandscape = function () {
  55897. var orientation = window.orientation;
  55898. if (isR7()) { orientation += 90; }
  55899. return orientation === 90 || orientation === -90;
  55900. };
  55901. /**
  55902. * Check if running in a browser or spoofed browser (bundler).
  55903. * We need to check a node api that isn't mocked on either side.
  55904. * `require` and `module.exports` are mocked in browser by bundlers.
  55905. * `window` is mocked in node.
  55906. * `process` is also mocked by browserify, but has custom properties.
  55907. */
  55908. module.exports.isBrowserEnvironment = !!(!process || process.browser);
  55909. /**
  55910. * Check if running in node on the server.
  55911. */
  55912. module.exports.isNodeEnvironment = !module.exports.isBrowserEnvironment;
  55913. /**
  55914. * Update an Object3D pose if a polyfilled vrDisplay is present.
  55915. */
  55916. module.exports.PolyfillControls = function PolyfillControls (object) {
  55917. var frameData;
  55918. var vrDisplay = window.webvrpolyfill && window.webvrpolyfill.getPolyfillDisplays()[0];
  55919. if (window.VRFrameData) { frameData = new window.VRFrameData(); }
  55920. this.update = function () {
  55921. var pose;
  55922. if (!vrDisplay) { return; }
  55923. vrDisplay.getFrameData(frameData);
  55924. pose = frameData.pose;
  55925. if (pose.orientation !== null) {
  55926. object.quaternion.fromArray(pose.orientation);
  55927. }
  55928. if (pose.position !== null) {
  55929. object.position.fromArray(pose.position);
  55930. } else {
  55931. object.position.set(0, 0, 0);
  55932. }
  55933. };
  55934. };
  55935. }).call(this,_dereq_('_process'))
  55936. },{"_process":32}],176:[function(_dereq_,module,exports){
  55937. /**
  55938. * Split a delimited component property string (e.g., `material.color`) to an object
  55939. * containing `component` name and `property` name. If there is no delimiter, just return the
  55940. * string back.
  55941. *
  55942. * Cache arrays from splitting strings via delimiter to save on memory.
  55943. *
  55944. * @param {string} str - e.g., `material.opacity`.
  55945. * @param {string} delimiter - e.g., `.`.
  55946. * @returns {array} e.g., `['material', 'opacity']`.
  55947. */
  55948. var propertyPathCache = {};
  55949. function getComponentPropertyPath (str, delimiter) {
  55950. delimiter = delimiter || '.';
  55951. if (!propertyPathCache[delimiter]) { propertyPathCache[delimiter] = {}; }
  55952. if (str.indexOf(delimiter) !== -1) {
  55953. propertyPathCache[delimiter][str] = str.split(delimiter);
  55954. } else {
  55955. propertyPathCache[delimiter][str] = str;
  55956. }
  55957. return propertyPathCache[delimiter][str];
  55958. }
  55959. module.exports.getComponentPropertyPath = getComponentPropertyPath;
  55960. module.exports.propertyPathCache = propertyPathCache;
  55961. /**
  55962. * Get component property using encoded component name + component property name with a
  55963. * delimiter.
  55964. */
  55965. module.exports.getComponentProperty = function (el, name, delimiter) {
  55966. var splitName;
  55967. delimiter = delimiter || '.';
  55968. if (name.indexOf(delimiter) !== -1) {
  55969. splitName = getComponentPropertyPath(name, delimiter);
  55970. if (splitName.constructor === String) {
  55971. return el.getAttribute(splitName);
  55972. }
  55973. return el.getAttribute(splitName[0])[splitName[1]];
  55974. }
  55975. return el.getAttribute(name);
  55976. };
  55977. /**
  55978. * Set component property using encoded component name + component property name with a
  55979. * delimiter.
  55980. */
  55981. module.exports.setComponentProperty = function (el, name, value, delimiter) {
  55982. var splitName;
  55983. delimiter = delimiter || '.';
  55984. if (name.indexOf(delimiter) !== -1) {
  55985. splitName = getComponentPropertyPath(name, delimiter);
  55986. if (splitName.constructor === String) {
  55987. el.setAttribute(splitName, value);
  55988. } else {
  55989. el.setAttribute(splitName[0], splitName[1], value);
  55990. }
  55991. return;
  55992. }
  55993. el.setAttribute(name, value);
  55994. };
  55995. },{}],177:[function(_dereq_,module,exports){
  55996. module.exports = function forceCanvasResizeSafariMobile (canvasEl) {
  55997. var width = canvasEl.style.width;
  55998. var height = canvasEl.style.height;
  55999. // Taken from webvr-polyfill (https://github.com/borismus/webvr-polyfill/blob/85f657cd502ec9417bf26b87c3cb2afa6a70e079/src/util.js#L200)
  56000. // iOS only workaround for https://bugs.webkit.org/show_bug.cgi?id=152556
  56001. // By changing the size 1 pixel and restoring the previous value
  56002. // we trigger a size recalculation cycle.
  56003. canvasEl.style.width = (parseInt(width, 10) + 1) + 'px';
  56004. canvasEl.style.height = (parseInt(height, 10) + 1) + 'px';
  56005. setTimeout(function () {
  56006. canvasEl.style.width = width;
  56007. canvasEl.style.height = height;
  56008. }, 200);
  56009. };
  56010. },{}],178:[function(_dereq_,module,exports){
  56011. /* global location */
  56012. /* Centralized place to reference utilities since utils is exposed to the user. */
  56013. var debug = _dereq_('./debug');
  56014. var deepAssign = _dereq_('deep-assign');
  56015. var device = _dereq_('./device');
  56016. var objectAssign = _dereq_('object-assign');
  56017. var objectPool = _dereq_('./object-pool');
  56018. var warn = debug('utils:warn');
  56019. module.exports.bind = _dereq_('./bind');
  56020. module.exports.coordinates = _dereq_('./coordinates');
  56021. module.exports.debug = debug;
  56022. module.exports.device = device;
  56023. module.exports.entity = _dereq_('./entity');
  56024. module.exports.forceCanvasResizeSafariMobile = _dereq_('./forceCanvasResizeSafariMobile');
  56025. module.exports.material = _dereq_('./material');
  56026. module.exports.objectPool = objectPool;
  56027. module.exports.split = _dereq_('./split').split;
  56028. module.exports.styleParser = _dereq_('./styleParser');
  56029. module.exports.trackedControls = _dereq_('./tracked-controls');
  56030. module.exports.checkHeadsetConnected = function () {
  56031. warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`');
  56032. return device.checkHeadsetConnected(arguments);
  56033. };
  56034. module.exports.isGearVR = function () {
  56035. warn('`utils.isGearVR` has moved to `utils.device.isGearVR`');
  56036. return device.isGearVR(arguments);
  56037. };
  56038. module.exports.isIOS = function () {
  56039. warn('`utils.isIOS` has moved to `utils.device.isIOS`');
  56040. return device.isIOS(arguments);
  56041. };
  56042. module.exports.isMobile = function () {
  56043. warn('`utils.isMobile has moved to `utils.device.isMobile`');
  56044. return device.isMobile(arguments);
  56045. };
  56046. /**
  56047. * Returns throttle function that gets called at most once every interval.
  56048. *
  56049. * @param {function} functionToThrottle
  56050. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  56051. * @param {object} optionalContext - If given, bind function to throttle to this context.
  56052. * @returns {function} Throttled function.
  56053. */
  56054. module.exports.throttle = function (functionToThrottle, minimumInterval, optionalContext) {
  56055. var lastTime;
  56056. if (optionalContext) {
  56057. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  56058. }
  56059. return function () {
  56060. var time = Date.now();
  56061. var sinceLastTime = typeof lastTime === 'undefined' ? minimumInterval : time - lastTime;
  56062. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  56063. lastTime = time;
  56064. functionToThrottle.apply(null, arguments);
  56065. }
  56066. };
  56067. };
  56068. /**
  56069. * Returns throttle function that gets called at most once every interval.
  56070. * Uses the time/timeDelta timestamps provided by the global render loop for better perf.
  56071. *
  56072. * @param {function} functionToThrottle
  56073. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  56074. * @param {object} optionalContext - If given, bind function to throttle to this context.
  56075. * @returns {function} Throttled function.
  56076. */
  56077. module.exports.throttleTick = function (functionToThrottle, minimumInterval, optionalContext) {
  56078. var lastTime;
  56079. if (optionalContext) {
  56080. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  56081. }
  56082. return function (time, delta) {
  56083. var sinceLastTime = typeof lastTime === 'undefined' ? delta : time - lastTime;
  56084. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  56085. lastTime = time;
  56086. functionToThrottle(time, sinceLastTime);
  56087. }
  56088. };
  56089. };
  56090. /**
  56091. * Returns debounce function that gets called only once after a set of repeated calls.
  56092. *
  56093. * @param {function} functionToDebounce
  56094. * @param {number} wait - Time to wait for repeated function calls (milliseconds).
  56095. * @param {boolean} immediate - Calls the function immediately regardless of if it should be waiting.
  56096. * @returns {function} Debounced function.
  56097. */
  56098. module.exports.debounce = function (func, wait, immediate) {
  56099. var timeout;
  56100. return function () {
  56101. var context = this;
  56102. var args = arguments;
  56103. var later = function () {
  56104. timeout = null;
  56105. if (!immediate) func.apply(context, args);
  56106. };
  56107. var callNow = immediate && !timeout;
  56108. clearTimeout(timeout);
  56109. timeout = setTimeout(later, wait);
  56110. if (callNow) func.apply(context, args);
  56111. };
  56112. };
  56113. /**
  56114. * Mix the properties of source object(s) into a destination object.
  56115. *
  56116. * @param {object} dest - The object to which properties will be copied.
  56117. * @param {...object} source - The object(s) from which properties will be copied.
  56118. */
  56119. module.exports.extend = objectAssign;
  56120. module.exports.extendDeep = deepAssign;
  56121. module.exports.clone = function (obj) {
  56122. return JSON.parse(JSON.stringify(obj));
  56123. };
  56124. /**
  56125. * Checks if two values are equal.
  56126. * Includes objects and arrays and nested objects and arrays.
  56127. * Try to keep this function performant as it will be called often to see if a component
  56128. * should be updated.
  56129. *
  56130. * @param {object} a - First object.
  56131. * @param {object} b - Second object.
  56132. * @returns {boolean} Whether two objects are deeply equal.
  56133. */
  56134. var deepEqual = (function () {
  56135. var arrayPool = objectPool.createPool(function () { return []; });
  56136. return function (a, b) {
  56137. var key;
  56138. var keysA;
  56139. var keysB;
  56140. var i;
  56141. var valA;
  56142. var valB;
  56143. // If not objects or arrays, compare as values.
  56144. if (a === undefined || b === undefined || a === null || b === null ||
  56145. !(a && b && (a.constructor === Object && b.constructor === Object) ||
  56146. (a.constructor === Array && b.constructor === Array))) {
  56147. return a === b;
  56148. }
  56149. // Different number of keys, not equal.
  56150. keysA = arrayPool.use();
  56151. keysB = arrayPool.use();
  56152. keysA.length = 0;
  56153. keysB.length = 0;
  56154. for (key in a) { keysA.push(key); }
  56155. for (key in b) { keysB.push(key); }
  56156. if (keysA.length !== keysB.length) {
  56157. arrayPool.recycle(keysA);
  56158. arrayPool.recycle(keysB);
  56159. return false;
  56160. }
  56161. // Return `false` at the first sign of inequality.
  56162. for (i = 0; i < keysA.length; ++i) {
  56163. valA = a[keysA[i]];
  56164. valB = b[keysA[i]];
  56165. // Check nested array and object.
  56166. if ((typeof valA === 'object' || typeof valB === 'object') ||
  56167. (Array.isArray(valA) && Array.isArray(valB))) {
  56168. if (valA === valB) { continue; }
  56169. if (!deepEqual(valA, valB)) {
  56170. arrayPool.recycle(keysA);
  56171. arrayPool.recycle(keysB);
  56172. return false;
  56173. }
  56174. } else if (valA !== valB) {
  56175. arrayPool.recycle(keysA);
  56176. arrayPool.recycle(keysB);
  56177. return false;
  56178. }
  56179. }
  56180. arrayPool.recycle(keysA);
  56181. arrayPool.recycle(keysB);
  56182. return true;
  56183. };
  56184. })();
  56185. module.exports.deepEqual = deepEqual;
  56186. /**
  56187. * Computes the difference between two objects.
  56188. *
  56189. * @param {object} a - First object to compare (e.g., oldData).
  56190. * @param {object} b - Second object to compare (e.g., newData).
  56191. * @returns {object}
  56192. * Difference object where set of keys note which values were not equal, and values are
  56193. * `b`'s values.
  56194. */
  56195. module.exports.diff = (function () {
  56196. var keys = [];
  56197. return function (a, b, targetObject) {
  56198. var aVal;
  56199. var bVal;
  56200. var bKey;
  56201. var diff;
  56202. var key;
  56203. var i;
  56204. var isComparingObjects;
  56205. diff = targetObject || {};
  56206. // Collect A keys.
  56207. keys.length = 0;
  56208. for (key in a) { keys.push(key); }
  56209. if (!b) { return diff; }
  56210. // Collect B keys.
  56211. for (bKey in b) {
  56212. if (keys.indexOf(bKey) === -1) {
  56213. keys.push(bKey);
  56214. }
  56215. }
  56216. for (i = 0; i < keys.length; i++) {
  56217. key = keys[i];
  56218. aVal = a[key];
  56219. bVal = b[key];
  56220. isComparingObjects = aVal && bVal &&
  56221. aVal.constructor === Object && bVal.constructor === Object;
  56222. if ((isComparingObjects && !deepEqual(aVal, bVal)) ||
  56223. (!isComparingObjects && aVal !== bVal)) {
  56224. diff[key] = bVal;
  56225. }
  56226. }
  56227. return diff;
  56228. };
  56229. })();
  56230. /**
  56231. * Returns whether we should capture this keyboard event for keyboard shortcuts.
  56232. * @param {Event} event Event object.
  56233. * @returns {Boolean} Whether the key event should be captured.
  56234. */
  56235. module.exports.shouldCaptureKeyEvent = function (event) {
  56236. if (event.metaKey) { return false; }
  56237. return document.activeElement === document.body;
  56238. };
  56239. /**
  56240. * Splits a string into an array based on a delimiter.
  56241. *
  56242. * @param {string=} [str=''] Source string
  56243. * @param {string=} [delimiter=' '] Delimiter to use
  56244. * @returns {array} Array of delimited strings
  56245. */
  56246. module.exports.splitString = function (str, delimiter) {
  56247. if (typeof delimiter === 'undefined') { delimiter = ' '; }
  56248. // First collapse the whitespace (or whatever the delimiter is).
  56249. var regex = new RegExp(delimiter, 'g');
  56250. str = (str || '').replace(regex, delimiter);
  56251. // Then split.
  56252. return str.split(delimiter);
  56253. };
  56254. /**
  56255. * Extracts data from the element given an object that contains expected keys.
  56256. *
  56257. * @param {Element} Source element.
  56258. * @param {Object} [defaults={}] Object of default key-value pairs.
  56259. * @returns {Object}
  56260. */
  56261. module.exports.getElData = function (el, defaults) {
  56262. defaults = defaults || {};
  56263. var data = {};
  56264. Object.keys(defaults).forEach(copyAttribute);
  56265. function copyAttribute (key) {
  56266. if (el.hasAttribute(key)) {
  56267. data[key] = el.getAttribute(key);
  56268. }
  56269. }
  56270. return data;
  56271. };
  56272. /**
  56273. * Retrieves querystring value.
  56274. * @param {String} name Name of querystring key.
  56275. * @return {String} Value
  56276. */
  56277. module.exports.getUrlParameter = function (name) {
  56278. // eslint-disable-next-line no-useless-escape
  56279. name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
  56280. var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  56281. var results = regex.exec(location.search);
  56282. return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
  56283. };
  56284. /**
  56285. * Detects whether context is within iframe.
  56286. */
  56287. module.exports.isIframed = function () {
  56288. return window.top !== window.self;
  56289. };
  56290. /**
  56291. * Finds all elements under the element that have the isScene
  56292. * property set to true
  56293. */
  56294. module.exports.findAllScenes = function (el) {
  56295. var matchingElements = [];
  56296. var allElements = el.getElementsByTagName('*');
  56297. for (var i = 0, n = allElements.length; i < n; i++) {
  56298. if (allElements[i].isScene) {
  56299. // Element exists with isScene set.
  56300. matchingElements.push(allElements[i]);
  56301. }
  56302. }
  56303. return matchingElements;
  56304. };
  56305. // Must be at bottom to avoid circular dependency.
  56306. module.exports.srcLoader = _dereq_('./src-loader');
  56307. },{"./bind":172,"./coordinates":173,"./debug":174,"./device":175,"./entity":176,"./forceCanvasResizeSafariMobile":177,"./material":180,"./object-pool":181,"./split":182,"./src-loader":183,"./styleParser":184,"./tracked-controls":185,"deep-assign":10,"object-assign":25}],179:[function(_dereq_,module,exports){
  56308. /**
  56309. * Check if device is iOS and older than version 10.
  56310. */
  56311. module.exports = function isIOSOlderThan10 (userAgent) {
  56312. return /(iphone|ipod|ipad).*os.(7_|8_|9_)/i.test(userAgent);
  56313. };
  56314. },{}],180:[function(_dereq_,module,exports){
  56315. var THREE = _dereq_('../lib/three');
  56316. var HLS_MIMETYPES = ['application/x-mpegurl', 'application/vnd.apple.mpegurl'];
  56317. /**
  56318. * Update `material` texture property (usually but not always `map`)
  56319. * from `data` property (usually but not always `src`)
  56320. *
  56321. * @param {object} shader - A-Frame shader instance.
  56322. * @param {object} data
  56323. */
  56324. module.exports.updateMapMaterialFromData = function (materialName, dataName, shader, data) {
  56325. var el = shader.el;
  56326. var material = shader.material;
  56327. var src = data[dataName];
  56328. // Because a single material / shader may have multiple textures,
  56329. // we need to remember the source value for this data property
  56330. // to avoid redundant operations which can be expensive otherwise
  56331. // (e.g. video texture loads).
  56332. if (!shader.materialSrcs) { shader.materialSrcs = {}; }
  56333. if (!src) {
  56334. // Forget the prior material src.
  56335. delete shader.materialSrcs[materialName];
  56336. // Remove the texture.
  56337. setMap(null);
  56338. return;
  56339. }
  56340. // Don't process if material src hasn't changed.
  56341. if (src === shader.materialSrcs[materialName]) { return; }
  56342. // Remember the new src for this texture (there may be multiple).
  56343. shader.materialSrcs[materialName] = src;
  56344. // If the new material src is already a texture, just use it.
  56345. if (src instanceof THREE.Texture) { setMap(src); } else {
  56346. // Load texture for the new material src.
  56347. // (And check if we should still use it once available in callback.)
  56348. el.sceneEl.systems.material.loadTexture(src,
  56349. {src: src, repeat: data.repeat, offset: data.offset, npot: data.npot},
  56350. checkSetMap);
  56351. }
  56352. function checkSetMap (texture) {
  56353. // If the source has been changed, don't use loaded texture.
  56354. if (shader.materialSrcs[materialName] !== src) { return; }
  56355. setMap(texture);
  56356. }
  56357. function setMap (texture) {
  56358. material[materialName] = texture;
  56359. material.needsUpdate = true;
  56360. handleTextureEvents(el, texture);
  56361. }
  56362. };
  56363. /**
  56364. * Update `material.map` given `data.src`. For standard and flat shaders.
  56365. *
  56366. * @param {object} shader - A-Frame shader instance.
  56367. * @param {object} data
  56368. */
  56369. module.exports.updateMap = function (shader, data) {
  56370. return module.exports.updateMapMaterialFromData('map', 'src', shader, data);
  56371. };
  56372. /**
  56373. * Updates the material's maps which give the illusion of extra geometry.
  56374. *
  56375. * @param {string} longType - The friendly name of the map from the component e.g. ambientOcclusionMap becomes aoMap in THREE.js
  56376. * @param {object} shader - A-Frame shader instance
  56377. * @param {object} data
  56378. */
  56379. module.exports.updateDistortionMap = function (longType, shader, data) {
  56380. var shortType = longType;
  56381. if (longType === 'ambientOcclusion') { shortType = 'ao'; }
  56382. var el = shader.el;
  56383. var material = shader.material;
  56384. var src = data[longType + 'Map'];
  56385. var info = {};
  56386. info.src = src;
  56387. // Pass through the repeat and offset to be handled by the material loader.
  56388. info.offset = data[longType + 'TextureOffset'];
  56389. info.repeat = data[longType + 'TextureRepeat'];
  56390. info.wrap = data[longType + 'TextureWrap'];
  56391. if (src) {
  56392. if (src === shader[longType + 'TextureSrc']) { return; }
  56393. // Texture added or changed.
  56394. shader[longType + 'TextureSrc'] = src;
  56395. el.sceneEl.systems.material.loadTexture(src, info, setMap);
  56396. return;
  56397. }
  56398. // Texture removed.
  56399. if (!material.map) { return; }
  56400. setMap(null);
  56401. function setMap (texture) {
  56402. material[shortType + 'Map'] = texture;
  56403. material.needsUpdate = true;
  56404. handleTextureEvents(el, texture);
  56405. }
  56406. };
  56407. /**
  56408. * Emit event on entities on texture-related events.
  56409. *
  56410. * @param {Element} el - Entity.
  56411. * @param {object} texture - three.js Texture.
  56412. */
  56413. function handleTextureEvents (el, texture) {
  56414. if (!texture) { return; }
  56415. el.emit('materialtextureloaded', {src: texture.image, texture: texture});
  56416. // Video events.
  56417. if (!texture.image || texture.image.tagName !== 'VIDEO') { return; }
  56418. texture.image.addEventListener('loadeddata', function emitVideoTextureLoadedDataAll () {
  56419. // Check to see if we need to use iOS 10 HLS shader.
  56420. // Only override the shader if it is stock shader that we know doesn't correct.
  56421. if (!el.components || !el.components.material) { return; }
  56422. if (texture.needsCorrectionBGRA && texture.needsCorrectionFlipY &&
  56423. ['standard', 'flat'].indexOf(el.components.material.data.shader) !== -1) {
  56424. el.setAttribute('material', 'shader', 'ios10hls');
  56425. }
  56426. el.emit('materialvideoloadeddata', {src: texture.image, texture: texture});
  56427. });
  56428. texture.image.addEventListener('ended', function emitVideoTextureEndedAll () {
  56429. // Works for non-looping videos only.
  56430. el.emit('materialvideoended', {src: texture.image, texture: texture});
  56431. });
  56432. }
  56433. module.exports.handleTextureEvents = handleTextureEvents;
  56434. /**
  56435. * Given video element src and type, guess whether stream is HLS.
  56436. *
  56437. * @param {string} src - src from video element (generally URL to content).
  56438. * @param {string} type - type from video element (generally MIME type if present).
  56439. */
  56440. module.exports.isHLS = function (src, type) {
  56441. if (type && HLS_MIMETYPES.includes(type.toLowerCase())) { return true; }
  56442. if (src && src.toLowerCase().indexOf('.m3u8') > 0) { return true; }
  56443. return false;
  56444. };
  56445. },{"../lib/three":154}],181:[function(_dereq_,module,exports){
  56446. /*
  56447. Adapted deePool by Kyle Simpson.
  56448. MIT License: http://getify.mit-license.org
  56449. */
  56450. var EMPTY_SLOT = Object.freeze(Object.create(null));
  56451. // Default object factory.
  56452. function defaultObjectFactory () { return {}; }
  56453. /**
  56454. * Create a new pool.
  56455. */
  56456. module.exports.createPool = function createPool (objectFactory) {
  56457. var objPool = [];
  56458. var nextFreeSlot = null; // Pool location to look for a free object to use.
  56459. objectFactory = objectFactory || defaultObjectFactory;
  56460. function use () {
  56461. var objToUse;
  56462. if (nextFreeSlot === null || nextFreeSlot === objPool.length) {
  56463. grow(objPool.length || 5);
  56464. }
  56465. objToUse = objPool[nextFreeSlot];
  56466. objPool[nextFreeSlot++] = EMPTY_SLOT;
  56467. clearObject(objToUse);
  56468. return objToUse;
  56469. }
  56470. function recycle (obj) {
  56471. if (!(obj instanceof Object)) { return; }
  56472. if (nextFreeSlot === null || nextFreeSlot === -1) {
  56473. objPool[objPool.length] = obj;
  56474. return;
  56475. }
  56476. objPool[--nextFreeSlot] = obj;
  56477. }
  56478. function grow (count) {
  56479. var currentLength;
  56480. var i;
  56481. count = count === undefined ? objPool.length : count;
  56482. if (count > 0 && nextFreeSlot == null) {
  56483. nextFreeSlot = 0;
  56484. }
  56485. if (count > 0) {
  56486. currentLength = objPool.length;
  56487. objPool.length += Number(count);
  56488. for (i = currentLength; i < objPool.length; i++) {
  56489. // Add new obj to pool.
  56490. objPool[i] = objectFactory();
  56491. }
  56492. }
  56493. return objPool.length;
  56494. }
  56495. function size () {
  56496. return objPool.length;
  56497. }
  56498. return {
  56499. grow: grow,
  56500. pool: objPool,
  56501. recycle: recycle,
  56502. size: size,
  56503. use: use
  56504. };
  56505. };
  56506. function clearObject (obj) {
  56507. var key;
  56508. if (!obj || obj.constructor !== Object) { return; }
  56509. for (key in obj) { obj[key] = undefined; }
  56510. }
  56511. module.exports.clearObject = clearObject;
  56512. },{}],182:[function(_dereq_,module,exports){
  56513. /**
  56514. * String split with cached result.
  56515. */
  56516. module.exports.split = (function () {
  56517. var splitCache = {};
  56518. return function (str, delimiter) {
  56519. if (!(delimiter in splitCache)) { splitCache[delimiter] = {}; }
  56520. if (str in splitCache[delimiter]) { return splitCache[delimiter][str]; }
  56521. splitCache[delimiter][str] = str.split(delimiter);
  56522. return splitCache[delimiter][str];
  56523. };
  56524. })();
  56525. },{}],183:[function(_dereq_,module,exports){
  56526. /* global Image, XMLHttpRequest */
  56527. var debug = _dereq_('./debug');
  56528. var warn = debug('utils:src-loader:warn');
  56529. /**
  56530. * Validate a texture, either as a selector or as a URL.
  56531. * Detects whether `src` is pointing to an image or video and invokes the appropriate
  56532. * callback.
  56533. *
  56534. * `src` will be passed into the callback
  56535. *
  56536. * @params {string|Element} src - URL or media element.
  56537. * @params {function} isImageCb - callback if texture is an image.
  56538. * @params {function} isVideoCb - callback if texture is a video.
  56539. */
  56540. function validateSrc (src, isImageCb, isVideoCb) {
  56541. checkIsImage(src, function isAnImageUrl (isImage) {
  56542. if (isImage) {
  56543. isImageCb(src);
  56544. return;
  56545. }
  56546. isVideoCb(src);
  56547. });
  56548. }
  56549. /**
  56550. * Validates six images as a cubemap, either as selector or comma-separated
  56551. * URLs.
  56552. *
  56553. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  56554. must be wrapped by `url()`.
  56555. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  56556. must be wrapped by `url()`.
  56557. */
  56558. function validateCubemapSrc (src, cb) {
  56559. var aCubemap;
  56560. var cubemapSrcRegex = '';
  56561. var i;
  56562. var urls;
  56563. var validatedUrls = [];
  56564. for (i = 0; i < 5; i++) {
  56565. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\),\\s*)';
  56566. }
  56567. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\)\\s*)';
  56568. urls = src.match(new RegExp(cubemapSrcRegex));
  56569. // `src` is a comma-separated list of URLs.
  56570. // In this case, re-use validateSrc for each side of the cube.
  56571. function isImageCb (url) {
  56572. validatedUrls.push(url);
  56573. if (validatedUrls.length === 6) {
  56574. cb(validatedUrls);
  56575. }
  56576. }
  56577. if (urls) {
  56578. for (i = 1; i < 7; i++) {
  56579. validateSrc(parseUrl(urls[i]), isImageCb);
  56580. }
  56581. return;
  56582. }
  56583. // `src` is a query selector to <a-cubemap> containing six $([src])s.
  56584. aCubemap = validateAndGetQuerySelector(src);
  56585. if (!aCubemap) { return; }
  56586. if (aCubemap.tagName === 'A-CUBEMAP' && aCubemap.srcs) {
  56587. return cb(aCubemap.srcs);
  56588. }
  56589. // Else if aCubeMap is not a <a-cubemap>.
  56590. warn('Selector "%s" does not point to <a-cubemap>', src);
  56591. }
  56592. /**
  56593. * Parses src from `url(src)`.
  56594. * @param {string} src - String to parse.
  56595. * @return {string} The parsed src, if parseable.
  56596. */
  56597. function parseUrl (src) {
  56598. var parsedSrc = src.match(/\url\((.+)\)/);
  56599. if (!parsedSrc) { return; }
  56600. return parsedSrc[1];
  56601. }
  56602. /**
  56603. * Call back whether `src` is an image.
  56604. *
  56605. * @param {string|Element} src - URL or element that will be tested.
  56606. * @param {function} onResult - Callback with whether `src` is an image.
  56607. */
  56608. function checkIsImage (src, onResult) {
  56609. var request;
  56610. if (src.tagName) {
  56611. onResult(src.tagName === 'IMG');
  56612. return;
  56613. }
  56614. request = new XMLHttpRequest();
  56615. // Try to send HEAD request to check if image first.
  56616. request.open('HEAD', src);
  56617. request.addEventListener('load', function (event) {
  56618. var contentType;
  56619. if (request.status >= 200 && request.status < 300) {
  56620. contentType = request.getResponseHeader('Content-Type');
  56621. if (contentType == null) {
  56622. checkIsImageFallback(src, onResult);
  56623. } else {
  56624. if (contentType.startsWith('image')) {
  56625. onResult(true);
  56626. } else {
  56627. onResult(false);
  56628. }
  56629. }
  56630. } else {
  56631. checkIsImageFallback(src, onResult);
  56632. }
  56633. request.abort();
  56634. });
  56635. request.send();
  56636. }
  56637. function checkIsImageFallback (src, onResult) {
  56638. var tester = new Image();
  56639. tester.addEventListener('load', onLoad);
  56640. function onLoad () { onResult(true); }
  56641. tester.addEventListener('error', onError);
  56642. function onError () { onResult(false); }
  56643. tester.src = src;
  56644. }
  56645. /**
  56646. * Query and validate a query selector,
  56647. *
  56648. * @param {string} selector - DOM selector.
  56649. * @return {object|null|undefined} Selected DOM element if exists.
  56650. null if query yields no results.
  56651. undefined if `selector` is not a valid selector.
  56652. */
  56653. function validateAndGetQuerySelector (selector) {
  56654. try {
  56655. var el = document.querySelector(selector);
  56656. if (!el) {
  56657. warn('No element was found matching the selector: "%s"', selector);
  56658. }
  56659. return el;
  56660. } catch (e) { // Capture exception if it's not a valid selector.
  56661. warn('"%s" is not a valid selector', selector);
  56662. return undefined;
  56663. }
  56664. }
  56665. module.exports = {
  56666. parseUrl: parseUrl,
  56667. validateSrc: validateSrc,
  56668. validateCubemapSrc: validateCubemapSrc
  56669. };
  56670. },{"./debug":174}],184:[function(_dereq_,module,exports){
  56671. /**
  56672. * Utils for parsing style-like strings (e.g., "primitive: box; width: 5; height: 4.5").
  56673. * Some code adapted from `style-attr` (https://github.com/joshwnj/style-attr)
  56674. * by Josh Johnston (MIT License).
  56675. */
  56676. var DASH_REGEX = /-([a-z])/g;
  56677. /**
  56678. * Deserialize style-like string into an object of properties.
  56679. *
  56680. * @param {string} value - HTML attribute value.
  56681. * @param {object} obj - Reused object for object pooling.
  56682. * @returns {object} Property data.
  56683. */
  56684. module.exports.parse = function (value, obj) {
  56685. var parsedData;
  56686. if (typeof value !== 'string') { return value; }
  56687. parsedData = styleParse(value, obj);
  56688. // The style parser returns an object { "" : "test"} when fed a string
  56689. if (parsedData['']) { return value; }
  56690. return transformKeysToCamelCase(parsedData);
  56691. };
  56692. /**
  56693. * Serialize an object of properties into a style-like string.
  56694. *
  56695. * @param {object} data - Property data.
  56696. * @returns {string}
  56697. */
  56698. module.exports.stringify = function (data) {
  56699. if (typeof data === 'string') { return data; }
  56700. return styleStringify(data);
  56701. };
  56702. /**
  56703. * Converts string from hyphen to camelCase.
  56704. *
  56705. * @param {string} str - String to camelCase.
  56706. * @return {string} CamelCased string.
  56707. */
  56708. function toCamelCase (str) {
  56709. return str.replace(DASH_REGEX, upperCase);
  56710. }
  56711. module.exports.toCamelCase = toCamelCase;
  56712. /**
  56713. * Converts object's keys from hyphens to camelCase (e.g., `max-value` to
  56714. * `maxValue`).
  56715. *
  56716. * @param {object} obj - The object to camelCase keys.
  56717. * @return {object} The object with keys camelCased.
  56718. */
  56719. function transformKeysToCamelCase (obj) {
  56720. var camelKey;
  56721. var key;
  56722. for (key in obj) {
  56723. camelKey = toCamelCase(key);
  56724. if (key === camelKey) { continue; }
  56725. obj[camelKey] = obj[key];
  56726. delete obj[key];
  56727. }
  56728. return obj;
  56729. }
  56730. module.exports.transformKeysToCamelCase = transformKeysToCamelCase;
  56731. /**
  56732. * Split a string into chunks matching `<key>: <value>`
  56733. */
  56734. var getKeyValueChunks = (function () {
  56735. var chunks = [];
  56736. var hasUnclosedUrl = /url\([^)]+$/;
  56737. return function getKeyValueChunks (raw) {
  56738. var chunk = '';
  56739. var nextSplit;
  56740. var offset = 0;
  56741. var sep = ';';
  56742. chunks.length = 0;
  56743. while (offset < raw.length) {
  56744. nextSplit = raw.indexOf(sep, offset);
  56745. if (nextSplit === -1) { nextSplit = raw.length; }
  56746. chunk += raw.substring(offset, nextSplit);
  56747. // data URIs can contain semicolons, so make sure we get the whole thing
  56748. if (hasUnclosedUrl.test(chunk)) {
  56749. chunk += ';';
  56750. offset = nextSplit + 1;
  56751. continue;
  56752. }
  56753. chunks.push(chunk.trim());
  56754. chunk = '';
  56755. offset = nextSplit + 1;
  56756. }
  56757. return chunks;
  56758. };
  56759. })();
  56760. /**
  56761. * Convert a style attribute string to an object.
  56762. *
  56763. * @param {object} str - Attribute string.
  56764. * @param {object} obj - Object to reuse as a base, else a new one will be allocated.
  56765. */
  56766. function styleParse (str, obj) {
  56767. var chunks;
  56768. var i;
  56769. var item;
  56770. var pos;
  56771. var key;
  56772. var val;
  56773. obj = obj || {};
  56774. chunks = getKeyValueChunks(str);
  56775. for (i = 0; i < chunks.length; i++) {
  56776. item = chunks[i];
  56777. if (!item) { continue; }
  56778. // Split with `.indexOf` rather than `.split` because the value may also contain colons.
  56779. pos = item.indexOf(':');
  56780. key = item.substr(0, pos).trim();
  56781. val = item.substr(pos + 1).trim();
  56782. obj[key] = val;
  56783. }
  56784. return obj;
  56785. }
  56786. /**
  56787. * Convert an object into an attribute string
  56788. **/
  56789. function styleStringify (obj) {
  56790. var key;
  56791. var keyCount = 0;
  56792. var i = 0;
  56793. var str = '';
  56794. for (key in obj) { keyCount++; }
  56795. for (key in obj) {
  56796. str += (key + ': ' + obj[key]);
  56797. if (i < keyCount - 1) { str += '; '; }
  56798. i++;
  56799. }
  56800. return str;
  56801. }
  56802. function upperCase (str) { return str[1].toUpperCase(); }
  56803. },{}],185:[function(_dereq_,module,exports){
  56804. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  56805. var AXIS_LABELS = ['x', 'y', 'z', 'w'];
  56806. var NUM_HANDS = 2; // Number of hands in a pair. Should always be 2.
  56807. /**
  56808. * Called on controller component `.play` handlers.
  56809. * Check if controller matches parameters and inject tracked-controls component.
  56810. * Handle event listeners.
  56811. * Generate controllerconnected or controllerdisconnected events.
  56812. *
  56813. * @param {object} component - Tracked controls component.
  56814. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  56815. * @param {object} queryObject - Map of values to match.
  56816. */
  56817. module.exports.checkControllerPresentAndSetup = function (component, idPrefix, queryObject) {
  56818. var el = component.el;
  56819. var controller;
  56820. var hasWebXR = el.sceneEl.hasWebXR;
  56821. var isControllerPresent = hasWebXR ? isControllerPresentWebXR : isControllerPresentWebVR;
  56822. var isPresent;
  56823. controller = isControllerPresent(component, idPrefix, queryObject);
  56824. isPresent = !!controller;
  56825. // If component was previously paused and now playing, re-add event listeners.
  56826. // Handle the event listeners here since this helper method is control of calling
  56827. // `.addEventListeners` and `.removeEventListeners`.
  56828. if (component.controllerPresent && !component.controllerEventsActive && !hasWebXR) {
  56829. component.addEventListeners();
  56830. }
  56831. // Nothing changed, no need to do anything.
  56832. if (isPresent === component.controllerPresent) { return isPresent; }
  56833. component.controllerPresent = isPresent;
  56834. // Update controller presence.
  56835. if (isPresent) {
  56836. component.injectTrackedControls();
  56837. if (!hasWebXR) { component.addEventListeners(); }
  56838. el.emit('controllerconnected', {name: component.name, component: component});
  56839. } else {
  56840. component.removeEventListeners();
  56841. el.emit('controllerdisconnected', {name: component.name, component: component});
  56842. }
  56843. };
  56844. /**
  56845. * Enumerate controller (that have pose) and check if they match parameters for WebVR
  56846. *
  56847. * @param {object} component - Tracked controls component.
  56848. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  56849. * @param {object} queryObject - Map of values to match.
  56850. */
  56851. function isControllerPresentWebVR (component, idPrefix, queryObject) {
  56852. var gamepads;
  56853. var sceneEl = component.el.sceneEl;
  56854. var trackedControlsSystem;
  56855. var filterControllerIndex = queryObject.index || 0;
  56856. if (!idPrefix) { return false; }
  56857. trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls-webvr'];
  56858. if (!trackedControlsSystem) { return false; }
  56859. gamepads = trackedControlsSystem.controllers;
  56860. if (!gamepads.length) { return false; }
  56861. return !!findMatchingControllerWebVR(gamepads, null, idPrefix, queryObject.hand,
  56862. filterControllerIndex);
  56863. }
  56864. /**
  56865. *
  56866. * @param {object} component - Tracked controls component.
  56867. */
  56868. function isControllerPresentWebXR (component, idPrefix, queryObject) {
  56869. var controllers;
  56870. var sceneEl = component.el.sceneEl;
  56871. var trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls-webxr'];
  56872. if (!trackedControlsSystem) { return false; }
  56873. controllers = trackedControlsSystem.controllers;
  56874. if (!controllers || !controllers.length) { return false; }
  56875. return findMatchingControllerWebXR(controllers, queryObject.hand);
  56876. }
  56877. module.exports.isControllerPresentWebVR = isControllerPresentWebVR;
  56878. module.exports.isControllerPresentWebXR = isControllerPresentWebXR;
  56879. /**
  56880. * Walk through the given controllers to find any where the device ID equals
  56881. * filterIdExact, or startsWith filterIdPrefix.
  56882. * A controller where this considered true is considered a 'match'.
  56883. *
  56884. * For each matching controller:
  56885. * If filterHand is set, and the controller:
  56886. * is handed, we further verify that controller.hand equals filterHand.
  56887. * is unhanded (controller.hand is ''), we skip until we have found a
  56888. * number of matching controllers that equals filterControllerIndex
  56889. * If filterHand is not set, we skip until we have found the nth matching
  56890. * controller, where n equals filterControllerIndex
  56891. *
  56892. * The method should be called with one of: [filterIdExact, filterIdPrefix] AND
  56893. * one or both of: [filterHand, filterControllerIndex]
  56894. *
  56895. * @param {object} controllers - Array of gamepads to search
  56896. * @param {string} filterIdExact - If set, used to find controllers with id === this value
  56897. * @param {string} filterIdPrefix - If set, used to find controllers with id startsWith this value
  56898. * @param {object} filterHand - If set, further filters controllers with matching 'hand' property
  56899. * @param {object} filterControllerIndex - Find the nth matching controller,
  56900. * where n equals filterControllerIndex. defaults to 0.
  56901. */
  56902. function findMatchingControllerWebVR (controllers, filterIdExact, filterIdPrefix, filterHand,
  56903. filterControllerIndex) {
  56904. var controller;
  56905. var i;
  56906. var matchingControllerOccurence = 0;
  56907. var targetControllerMatch = filterControllerIndex || 0;
  56908. for (i = 0; i < controllers.length; i++) {
  56909. controller = controllers[i];
  56910. // Determine if the controller ID matches our criteria.
  56911. if (filterIdPrefix && !controller.id.startsWith(filterIdPrefix)) {
  56912. continue;
  56913. }
  56914. if (!filterIdPrefix && controller.id !== filterIdExact) { continue; }
  56915. // If the hand filter and controller handedness are defined we compare them.
  56916. if (filterHand && controller.hand && filterHand !== controller.hand) { continue; }
  56917. // If we have detected an unhanded controller and the component was asking
  56918. // for a particular hand, we need to treat the controllers in the array as
  56919. // pairs of controllers. This effectively means that we need to skip
  56920. // NUM_HANDS matches for each controller number, instead of 1.
  56921. if (filterHand && !controller.hand) {
  56922. targetControllerMatch = NUM_HANDS * filterControllerIndex + ((filterHand === DEFAULT_HANDEDNESS) ? 0 : 1);
  56923. }
  56924. // We are looking for the nth occurence of a matching controller
  56925. // (n equals targetControllerMatch).
  56926. if (matchingControllerOccurence === targetControllerMatch) { return controller; }
  56927. ++matchingControllerOccurence;
  56928. }
  56929. return undefined;
  56930. }
  56931. function findMatchingControllerWebXR (controllers, handedness) {
  56932. var i;
  56933. for (i = 0; i < controllers.length; i++) {
  56934. if (controllers[i].handedness === handedness) {
  56935. return controllers[i];
  56936. }
  56937. }
  56938. return undefined;
  56939. }
  56940. module.exports.findMatchingControllerWebVR = findMatchingControllerWebVR;
  56941. module.exports.findMatchingControllerWebXR = findMatchingControllerWebXR;
  56942. /**
  56943. * Emit specific `moved` event(s) if axes changed based on original axismoved event.
  56944. *
  56945. * @param {object} component - Controller component in use.
  56946. * @param {array} axesMapping - For example `{thumbstick: [0, 1]}`.
  56947. * @param {object} evt - Event to process.
  56948. */
  56949. module.exports.emitIfAxesChanged = function (component, axesMapping, evt) {
  56950. var axes;
  56951. var buttonType;
  56952. var changed;
  56953. var detail;
  56954. var j;
  56955. for (buttonType in axesMapping) {
  56956. axes = axesMapping[buttonType];
  56957. changed = false;
  56958. for (j = 0; j < axes.length; j++) {
  56959. if (evt.detail.changed[axes[j]]) { changed = true; }
  56960. }
  56961. if (!changed) { continue; }
  56962. // Axis has changed. Emit the specific moved event with axis values in detail.
  56963. detail = {};
  56964. for (j = 0; j < axes.length; j++) {
  56965. detail[AXIS_LABELS[j]] = evt.detail.axis[axes[j]];
  56966. }
  56967. component.el.emit(buttonType + 'moved', detail);
  56968. }
  56969. };
  56970. /**
  56971. * Handle a button event and reemits the events.
  56972. *
  56973. * @param {string} id - id of the button.
  56974. * @param {string} evtName - name of the reemitted event
  56975. * @param {object} component - reference to the component
  56976. * @param {string} hand - handedness of the controller: left or right.
  56977. */
  56978. module.exports.onButtonEvent = function (id, evtName, component, hand) {
  56979. var mapping = hand ? component.mapping[hand] : component.mapping;
  56980. var buttonName = mapping.buttons[id];
  56981. component.el.emit(buttonName + evtName);
  56982. if (component.updateModel) {
  56983. component.updateModel(buttonName, evtName);
  56984. }
  56985. };
  56986. },{"../constants":97}],186:[function(_dereq_,module,exports){
  56987. window.glStats = function () {
  56988. var _rS = null;
  56989. var _totalDrawArraysCalls = 0,
  56990. _totalDrawElementsCalls = 0,
  56991. _totalUseProgramCalls = 0,
  56992. _totalFaces = 0,
  56993. _totalVertices = 0,
  56994. _totalPoints = 0,
  56995. _totalBindTexures = 0;
  56996. function _h ( f, c ) {
  56997. return function () {
  56998. c.apply( this, arguments );
  56999. f.apply( this, arguments );
  57000. };
  57001. }
  57002. WebGLRenderingContext.prototype.drawArrays = _h( WebGLRenderingContext.prototype.drawArrays, function () {
  57003. _totalDrawArraysCalls++;
  57004. if ( arguments[ 0 ] == this.POINTS ) _totalPoints += arguments[ 2 ];
  57005. else _totalVertices += arguments[ 2 ];
  57006. } );
  57007. WebGLRenderingContext.prototype.drawElements = _h( WebGLRenderingContext.prototype.drawElements, function () {
  57008. _totalDrawElementsCalls++;
  57009. _totalFaces += arguments[ 1 ] / 3;
  57010. _totalVertices += arguments[ 1 ];
  57011. } );
  57012. WebGLRenderingContext.prototype.useProgram = _h( WebGLRenderingContext.prototype.useProgram, function () {
  57013. _totalUseProgramCalls++;
  57014. } );
  57015. WebGLRenderingContext.prototype.bindTexture = _h( WebGLRenderingContext.prototype.bindTexture, function () {
  57016. _totalBindTexures++;
  57017. } );
  57018. var _values = {
  57019. allcalls: {
  57020. over: 3000,
  57021. caption: 'Calls (hook)'
  57022. },
  57023. drawelements: {
  57024. caption: 'drawElements (hook)'
  57025. },
  57026. drawarrays: {
  57027. caption: 'drawArrays (hook)'
  57028. }
  57029. };
  57030. var _groups = [ {
  57031. caption: 'WebGL',
  57032. values: [ 'allcalls', 'drawelements', 'drawarrays', 'useprogram', 'bindtexture', 'glfaces', 'glvertices', 'glpoints' ]
  57033. } ];
  57034. var _fractions = [ {
  57035. base: 'allcalls',
  57036. steps: [ 'drawelements', 'drawarrays' ]
  57037. } ];
  57038. function _update () {
  57039. _rS( 'allcalls' ).set( _totalDrawArraysCalls + _totalDrawElementsCalls );
  57040. _rS( 'drawElements' ).set( _totalDrawElementsCalls );
  57041. _rS( 'drawArrays' ).set( _totalDrawArraysCalls );
  57042. _rS( 'bindTexture' ).set( _totalBindTexures );
  57043. _rS( 'useProgram' ).set( _totalUseProgramCalls );
  57044. _rS( 'glfaces' ).set( _totalFaces );
  57045. _rS( 'glvertices' ).set( _totalVertices );
  57046. _rS( 'glpoints' ).set( _totalPoints );
  57047. }
  57048. function _start () {
  57049. _totalDrawArraysCalls = 0;
  57050. _totalDrawElementsCalls = 0;
  57051. _totalUseProgramCalls = 0;
  57052. _totalFaces = 0;
  57053. _totalVertices = 0;
  57054. _totalPoints = 0;
  57055. _totalBindTexures = 0;
  57056. }
  57057. function _end () {}
  57058. function _attach ( r ) {
  57059. _rS = r;
  57060. }
  57061. return {
  57062. update: _update,
  57063. start: _start,
  57064. end: _end,
  57065. attach: _attach,
  57066. values: _values,
  57067. groups: _groups,
  57068. fractions: _fractions
  57069. };
  57070. };
  57071. window.threeStats = function ( renderer ) {
  57072. var _rS = null;
  57073. var _values = {
  57074. 'renderer.info.memory.geometries': {
  57075. caption: 'Geometries'
  57076. },
  57077. 'renderer.info.memory.textures': {
  57078. caption: 'Textures'
  57079. },
  57080. 'renderer.info.programs': {
  57081. caption: 'Programs'
  57082. },
  57083. 'renderer.info.render.calls': {
  57084. caption: 'Calls'
  57085. },
  57086. 'renderer.info.render.triangles': {
  57087. caption: 'Triangles',
  57088. over: 1000
  57089. },
  57090. 'renderer.info.render.points': {
  57091. caption: 'Points'
  57092. }
  57093. };
  57094. var _groups = [ {
  57095. caption: 'Three.js - Memory',
  57096. values: [ 'renderer.info.memory.geometries', 'renderer.info.programs', 'renderer.info.memory.textures' ]
  57097. }, {
  57098. caption: 'Three.js - Render',
  57099. values: [ 'renderer.info.render.calls', 'renderer.info.render.triangles', 'renderer.info.render.points' ]
  57100. } ];
  57101. var _fractions = [];
  57102. function _update () {
  57103. _rS( 'renderer.info.memory.geometries' ).set( renderer.info.memory.geometries );
  57104. _rS( 'renderer.info.programs' ).set( renderer.info.programs.length );
  57105. _rS( 'renderer.info.memory.textures' ).set( renderer.info.memory.textures );
  57106. _rS( 'renderer.info.render.calls' ).set( renderer.info.render.calls );
  57107. _rS( 'renderer.info.render.triangles' ).set( renderer.info.render.triangles );
  57108. _rS( 'renderer.info.render.points' ).set( renderer.info.render.points );
  57109. }
  57110. function _start () {}
  57111. function _end () {}
  57112. function _attach ( r ) {
  57113. _rS = r;
  57114. }
  57115. return {
  57116. update: _update,
  57117. start: _start,
  57118. end: _end,
  57119. attach: _attach,
  57120. values: _values,
  57121. groups: _groups,
  57122. fractions: _fractions
  57123. };
  57124. };
  57125. /*
  57126. * From https://github.com/paulirish/memory-stats.js
  57127. */
  57128. window.BrowserStats = function () {
  57129. var _rS = null;
  57130. var _usedJSHeapSize = 0,
  57131. _totalJSHeapSize = 0;
  57132. if ( window.performance && !performance.memory ) {
  57133. performance.memory = {
  57134. usedJSHeapSize: 0,
  57135. totalJSHeapSize: 0
  57136. };
  57137. }
  57138. if ( performance.memory.totalJSHeapSize === 0 ) {
  57139. console.warn( 'totalJSHeapSize === 0... performance.memory is only available in Chrome .' );
  57140. }
  57141. var _values = {
  57142. memory: {
  57143. caption: 'Used Memory',
  57144. average: true,
  57145. avgMs: 1000,
  57146. over: 22
  57147. },
  57148. total: {
  57149. caption: 'Total Memory'
  57150. }
  57151. };
  57152. var _groups = [ {
  57153. caption: 'Browser',
  57154. values: [ 'memory', 'total' ]
  57155. } ];
  57156. var _fractions = [ {
  57157. base: 'total',
  57158. steps: [ 'memory' ]
  57159. } ];
  57160. var log1024 = Math.log( 1024 );
  57161. function _size ( v ) {
  57162. var precision = 100; //Math.pow(10, 2);
  57163. var i = Math.floor( Math.log( v ) / log1024 );
  57164. return Math.round( v * precision / Math.pow( 1024, i ) ) / precision; // + ' ' + sizes[i];
  57165. }
  57166. function _update () {
  57167. _usedJSHeapSize = _size( performance.memory.usedJSHeapSize );
  57168. _totalJSHeapSize = _size( performance.memory.totalJSHeapSize );
  57169. _rS( 'memory' ).set( _usedJSHeapSize );
  57170. _rS( 'total' ).set( _totalJSHeapSize );
  57171. }
  57172. function _start () {
  57173. _usedJSHeapSize = 0;
  57174. }
  57175. function _end () {}
  57176. function _attach ( r ) {
  57177. _rS = r;
  57178. }
  57179. return {
  57180. update: _update,
  57181. start: _start,
  57182. end: _end,
  57183. attach: _attach,
  57184. values: _values,
  57185. groups: _groups,
  57186. fractions: _fractions
  57187. };
  57188. };
  57189. if (typeof module === 'object') {
  57190. module.exports = {
  57191. glStats: window.glStats,
  57192. threeStats: window.threeStats,
  57193. BrowserStats: window.BrowserStats
  57194. };
  57195. }
  57196. },{}],187:[function(_dereq_,module,exports){
  57197. // performance.now() polyfill from https://gist.github.com/paulirish/5438650
  57198. 'use strict';
  57199. ( function () {
  57200. if ( 'performance' in window == false ) {
  57201. window.performance = {};
  57202. }
  57203. var performance = window.performance;
  57204. if ( 'now' in performance == false ) {
  57205. var nowOffset = Date.now();
  57206. if ( performance.timing && performance.timing.navigationStart ) {
  57207. nowOffset = performance.timing.navigationStart;
  57208. }
  57209. performance.now = function now () {
  57210. return Date.now() - nowOffset;
  57211. };
  57212. }
  57213. if( !performance.mark ) {
  57214. performance.mark = function(){}
  57215. }
  57216. if( !performance.measure ) {
  57217. performance.measure = function(){}
  57218. }
  57219. } )();
  57220. window.rStats = function rStats ( settings ) {
  57221. function iterateKeys ( array, callback ) {
  57222. var keys = Object.keys( array );
  57223. for ( var j = 0, l = keys.length; j < l; j++ ) {
  57224. callback( keys[ j ] );
  57225. }
  57226. }
  57227. function importCSS ( url ) {
  57228. var element = document.createElement( 'link' );
  57229. element.href = url;
  57230. element.rel = 'stylesheet';
  57231. element.type = 'text/css';
  57232. document.getElementsByTagName( 'head' )[ 0 ].appendChild( element );
  57233. }
  57234. var _settings = settings || {};
  57235. var _colours = _settings.colours || [ '#850700', '#c74900', '#fcb300', '#284280', '#4c7c0c' ];
  57236. var _cssFont = 'https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700,300';
  57237. var _cssRStats = ( _settings.CSSPath ? _settings.CSSPath : '' ) + 'rStats.css';
  57238. var _css = _settings.css || [ _cssFont, _cssRStats ];
  57239. _css.forEach(function (uri) {
  57240. importCSS( uri );
  57241. });
  57242. if ( !_settings.values ) _settings.values = {};
  57243. var _base, _div, _elHeight = 10, _elWidth = 200;
  57244. var _perfCounters = {};
  57245. function Graph ( _dom, _id, _defArg ) {
  57246. var _def = _defArg || {};
  57247. var _canvas = document.createElement( 'canvas' ),
  57248. _ctx = _canvas.getContext( '2d' ),
  57249. _max = 0,
  57250. _current = 0;
  57251. var c = _def.color ? _def.color : '#666666';
  57252. var _dotCanvas = document.createElement( 'canvas' ),
  57253. _dotCtx = _dotCanvas.getContext( '2d' );
  57254. _dotCanvas.width = 1;
  57255. _dotCanvas.height = 2 * _elHeight;
  57256. _dotCtx.fillStyle = '#444444';
  57257. _dotCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  57258. _dotCtx.fillStyle = c;
  57259. _dotCtx.fillRect( 0, _elHeight, 1, _elHeight );
  57260. _dotCtx.fillStyle = '#ffffff';
  57261. _dotCtx.globalAlpha = 0.5;
  57262. _dotCtx.fillRect( 0, _elHeight, 1, 1 );
  57263. _dotCtx.globalAlpha = 1;
  57264. var _alarmCanvas = document.createElement( 'canvas' ),
  57265. _alarmCtx = _alarmCanvas.getContext( '2d' );
  57266. _alarmCanvas.width = 1;
  57267. _alarmCanvas.height = 2 * _elHeight;
  57268. _alarmCtx.fillStyle = '#444444';
  57269. _alarmCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  57270. _alarmCtx.fillStyle = '#b70000';
  57271. _alarmCtx.fillRect( 0, _elHeight, 1, _elHeight );
  57272. _alarmCtx.globalAlpha = 0.5;
  57273. _alarmCtx.fillStyle = '#ffffff';
  57274. _alarmCtx.fillRect( 0, _elHeight, 1, 1 );
  57275. _alarmCtx.globalAlpha = 1;
  57276. function _init () {
  57277. _canvas.width = _elWidth;
  57278. _canvas.height = _elHeight;
  57279. _canvas.style.width = _canvas.width + 'px';
  57280. _canvas.style.height = _canvas.height + 'px';
  57281. _canvas.className = 'rs-canvas';
  57282. _dom.appendChild( _canvas );
  57283. _ctx.fillStyle = '#444444';
  57284. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  57285. }
  57286. function _draw ( v, alarm ) {
  57287. _current += ( v - _current ) * 0.1;
  57288. _max *= 0.99;
  57289. if ( _current > _max ) _max = _current;
  57290. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  57291. if ( alarm ) {
  57292. _ctx.drawImage( _alarmCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  57293. } else {
  57294. _ctx.drawImage( _dotCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  57295. }
  57296. }
  57297. _init();
  57298. return {
  57299. draw: _draw
  57300. };
  57301. }
  57302. function StackGraph ( _dom, _num ) {
  57303. var _canvas = document.createElement( 'canvas' ),
  57304. _ctx = _canvas.getContext( '2d' );
  57305. function _init () {
  57306. _canvas.width = _elWidth;
  57307. _canvas.height = _elHeight * _num;
  57308. _canvas.style.width = _canvas.width + 'px';
  57309. _canvas.style.height = _canvas.height + 'px';
  57310. _canvas.className = 'rs-canvas';
  57311. _dom.appendChild( _canvas );
  57312. _ctx.fillStyle = '#444444';
  57313. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  57314. }
  57315. function _draw ( v ) {
  57316. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  57317. var th = 0;
  57318. iterateKeys( v, function ( j ) {
  57319. var h = v[ j ] * _canvas.height;
  57320. _ctx.fillStyle = _colours[ j ];
  57321. _ctx.fillRect( _canvas.width - 1, th, 1, h );
  57322. th += h;
  57323. } );
  57324. }
  57325. _init();
  57326. return {
  57327. draw: _draw
  57328. };
  57329. }
  57330. function PerfCounter ( id, group ) {
  57331. var _id = id,
  57332. _time,
  57333. _value = 0,
  57334. _total = 0,
  57335. _averageValue = 0,
  57336. _accumValue = 0,
  57337. _accumStart = performance.now(),
  57338. _accumSamples = 0,
  57339. _dom = document.createElement( 'div' ),
  57340. _spanId = document.createElement( 'span' ),
  57341. _spanValue = document.createElement( 'div' ),
  57342. _spanValueText = document.createTextNode( '' ),
  57343. _def = _settings ? _settings.values[ _id.toLowerCase() ] : null,
  57344. _graph = new Graph( _dom, _id, _def ),
  57345. _started = false;
  57346. _spanId.className = 'rs-counter-id';
  57347. _spanId.textContent = ( _def && _def.caption ) ? _def.caption : _id;
  57348. _spanValue.className = 'rs-counter-value';
  57349. _spanValue.appendChild( _spanValueText );
  57350. _dom.appendChild( _spanId );
  57351. _dom.appendChild( _spanValue );
  57352. if ( group ) group.div.appendChild( _dom );
  57353. else _div.appendChild( _dom );
  57354. _time = performance.now();
  57355. function _average ( v ) {
  57356. if ( _def && _def.average ) {
  57357. _accumValue += v;
  57358. _accumSamples++;
  57359. var t = performance.now();
  57360. if ( t - _accumStart >= ( _def.avgMs || 1000 ) ) {
  57361. _averageValue = _accumValue / _accumSamples;
  57362. _accumValue = 0;
  57363. _accumStart = t;
  57364. _accumSamples = 0;
  57365. }
  57366. }
  57367. }
  57368. function _start () {
  57369. _time = performance.now();
  57370. if( _settings.userTimingAPI ) performance.mark( _id + '-start' );
  57371. _started = true;
  57372. }
  57373. function _end () {
  57374. _value = performance.now() - _time;
  57375. if( _settings.userTimingAPI ) {
  57376. performance.mark( _id + '-end' );
  57377. if( _started ) {
  57378. performance.measure( _id, _id + '-start', _id + '-end' );
  57379. }
  57380. }
  57381. _average( _value );
  57382. }
  57383. function _tick () {
  57384. _end();
  57385. _start();
  57386. }
  57387. function _draw () {
  57388. var v = ( _def && _def.average ) ? _averageValue : _value;
  57389. _spanValueText.nodeValue = Math.round( v * 100 ) / 100;
  57390. var a = ( _def && ( ( _def.below && _value < _def.below ) || ( _def.over && _value > _def.over ) ) );
  57391. _graph.draw( _value, a );
  57392. _dom.className = a ? 'rs-counter-base alarm' : 'rs-counter-base';
  57393. }
  57394. function _frame () {
  57395. var t = performance.now();
  57396. var e = t - _time;
  57397. _total++;
  57398. if ( e > 1000 ) {
  57399. if ( _def && _def.interpolate === false ) {
  57400. _value = _total;
  57401. } else {
  57402. _value = _total * 1000 / e;
  57403. }
  57404. _total = 0;
  57405. _time = t;
  57406. _average( _value );
  57407. }
  57408. }
  57409. function _set ( v ) {
  57410. _value = v;
  57411. _average( _value );
  57412. }
  57413. return {
  57414. set: _set,
  57415. start: _start,
  57416. tick: _tick,
  57417. end: _end,
  57418. frame: _frame,
  57419. value: function () {
  57420. return _value;
  57421. },
  57422. draw: _draw
  57423. };
  57424. }
  57425. function sample () {
  57426. var _value = 0;
  57427. function _set ( v ) {
  57428. _value = v;
  57429. }
  57430. return {
  57431. set: _set,
  57432. value: function () {
  57433. return _value;
  57434. }
  57435. };
  57436. }
  57437. function _perf ( idArg ) {
  57438. var id = idArg.toLowerCase();
  57439. if ( id === undefined ) id = 'default';
  57440. if ( _perfCounters[ id ] ) return _perfCounters[ id ];
  57441. var group = null;
  57442. if ( _settings && _settings.groups ) {
  57443. iterateKeys( _settings.groups, function ( j ) {
  57444. var g = _settings.groups[ parseInt( j, 10 ) ];
  57445. if ( !group && g.values.indexOf( id.toLowerCase() ) !== -1 ) {
  57446. group = g;
  57447. }
  57448. } );
  57449. }
  57450. var p = new PerfCounter( id, group );
  57451. _perfCounters[ id ] = p;
  57452. return p;
  57453. }
  57454. function _init () {
  57455. if ( _settings.plugins ) {
  57456. if ( !_settings.values ) _settings.values = {};
  57457. if ( !_settings.groups ) _settings.groups = [];
  57458. if ( !_settings.fractions ) _settings.fractions = [];
  57459. for ( var j = 0; j < _settings.plugins.length; j++ ) {
  57460. _settings.plugins[ j ].attach( _perf );
  57461. iterateKeys( _settings.plugins[ j ].values, function ( k ) {
  57462. _settings.values[ k ] = _settings.plugins[ j ].values[ k ];
  57463. } );
  57464. _settings.groups = _settings.groups.concat( _settings.plugins[ j ].groups );
  57465. _settings.fractions = _settings.fractions.concat( _settings.plugins[ j ].fractions );
  57466. }
  57467. } else {
  57468. _settings.plugins = {};
  57469. }
  57470. _base = document.createElement( 'div' );
  57471. _base.className = 'rs-base';
  57472. _div = document.createElement( 'div' );
  57473. _div.className = 'rs-container';
  57474. _div.style.height = 'auto';
  57475. _base.appendChild( _div );
  57476. document.body.appendChild( _base );
  57477. if ( !_settings ) return;
  57478. if ( _settings.groups ) {
  57479. iterateKeys( _settings.groups, function ( j ) {
  57480. var g = _settings.groups[ parseInt( j, 10 ) ];
  57481. var div = document.createElement( 'div' );
  57482. div.className = 'rs-group';
  57483. g.div = div;
  57484. var h1 = document.createElement( 'h1' );
  57485. h1.textContent = g.caption;
  57486. h1.addEventListener( 'click', function ( e ) {
  57487. this.classList.toggle( 'hidden' );
  57488. e.preventDefault();
  57489. }.bind( div ) );
  57490. _div.appendChild( h1 );
  57491. _div.appendChild( div );
  57492. } );
  57493. }
  57494. if ( _settings.fractions ) {
  57495. iterateKeys( _settings.fractions, function ( j ) {
  57496. var f = _settings.fractions[ parseInt( j, 10 ) ];
  57497. var div = document.createElement( 'div' );
  57498. div.className = 'rs-fraction';
  57499. var legend = document.createElement( 'div' );
  57500. legend.className = 'rs-legend';
  57501. var h = 0;
  57502. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  57503. var p = document.createElement( 'p' );
  57504. p.textContent = _settings.fractions[ j ].steps[ k ];
  57505. p.style.color = _colours[ h ];
  57506. legend.appendChild( p );
  57507. h++;
  57508. } );
  57509. div.appendChild( legend );
  57510. div.style.height = h * _elHeight + 'px';
  57511. f.div = div;
  57512. var graph = new StackGraph( div, h );
  57513. f.graph = graph;
  57514. _div.appendChild( div );
  57515. } );
  57516. }
  57517. }
  57518. function _update () {
  57519. iterateKeys( _settings.plugins, function ( j ) {
  57520. _settings.plugins[ j ].update();
  57521. } );
  57522. iterateKeys( _perfCounters, function ( j ) {
  57523. _perfCounters[ j ].draw();
  57524. } );
  57525. if ( _settings && _settings.fractions ) {
  57526. iterateKeys( _settings.fractions, function ( j ) {
  57527. var f = _settings.fractions[ parseInt( j, 10 ) ];
  57528. var v = [];
  57529. var base = _perfCounters[ f.base.toLowerCase() ];
  57530. if ( base ) {
  57531. base = base.value();
  57532. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  57533. var s = _settings.fractions[ j ].steps[ parseInt( k, 10 ) ].toLowerCase();
  57534. var val = _perfCounters[ s ];
  57535. if ( val ) {
  57536. v.push( val.value() / base );
  57537. }
  57538. } );
  57539. }
  57540. f.graph.draw( v );
  57541. } );
  57542. }
  57543. /*if( _height != _div.clientHeight ) {
  57544. _height = _div.clientHeight;
  57545. _base.style.height = _height + 2 * _elHeight + 'px';
  57546. console.log( _base.clientHeight );
  57547. }*/
  57548. }
  57549. _init();
  57550. return function ( id ) {
  57551. if ( id ) return _perf( id );
  57552. return {
  57553. element: _base,
  57554. update: _update
  57555. };
  57556. };
  57557. }
  57558. if (typeof module === 'object') {
  57559. module.exports = window.rStats;
  57560. }
  57561. },{}],188:[function(_dereq_,module,exports){
  57562. /*
  57563. * Copyright 2015 Google Inc. All Rights Reserved.
  57564. * Licensed under the Apache License, Version 2.0 (the "License");
  57565. * you may not use this file except in compliance with the License.
  57566. * You may obtain a copy of the License at
  57567. *
  57568. * http://www.apache.org/licenses/LICENSE-2.0
  57569. *
  57570. * Unless required by applicable law or agreed to in writing, software
  57571. * distributed under the License is distributed on an "AS IS" BASIS,
  57572. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  57573. * See the License for the specific language governing permissions and
  57574. * limitations under the License.
  57575. */
  57576. var Util = {};
  57577. Util.base64 = function(mimeType, base64) {
  57578. return 'data:' + mimeType + ';base64,' + base64;
  57579. };
  57580. Util.isMobile = function() {
  57581. var check = false;
  57582. (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);
  57583. return check;
  57584. };
  57585. Util.isIOS = function() {
  57586. return /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
  57587. };
  57588. Util.isIFrame = function() {
  57589. try {
  57590. return window.self !== window.top;
  57591. } catch (e) {
  57592. return true;
  57593. }
  57594. };
  57595. Util.appendQueryParameter = function(url, key, value) {
  57596. // Determine delimiter based on if the URL already GET parameters in it.
  57597. var delimiter = (url.indexOf('?') < 0 ? '?' : '&');
  57598. url += delimiter + key + '=' + value;
  57599. return url;
  57600. };
  57601. // From http://goo.gl/4WX3tg
  57602. Util.getQueryParameter = function(name) {
  57603. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  57604. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  57605. results = regex.exec(location.search);
  57606. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  57607. };
  57608. Util.isLandscapeMode = function() {
  57609. return (window.orientation == 90 || window.orientation == -90);
  57610. };
  57611. module.exports = Util;
  57612. },{}],189:[function(_dereq_,module,exports){
  57613. /*
  57614. * Copyright 2015 Google Inc. All Rights Reserved.
  57615. * Licensed under the Apache License, Version 2.0 (the "License");
  57616. * you may not use this file except in compliance with the License.
  57617. * You may obtain a copy of the License at
  57618. *
  57619. * http://www.apache.org/licenses/LICENSE-2.0
  57620. *
  57621. * Unless required by applicable law or agreed to in writing, software
  57622. * distributed under the License is distributed on an "AS IS" BASIS,
  57623. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  57624. * See the License for the specific language governing permissions and
  57625. * limitations under the License.
  57626. */
  57627. var Util = _dereq_('./util.js');
  57628. /**
  57629. * Android and iOS compatible wakelock implementation.
  57630. *
  57631. * Refactored thanks to dkovalev@.
  57632. */
  57633. function AndroidWakeLock() {
  57634. var video = document.createElement('video');
  57635. video.addEventListener('ended', function() {
  57636. video.play();
  57637. });
  57638. this.request = function() {
  57639. if (video.paused) {
  57640. // Base64 version of videos_src/no-sleep-60s.webm.
  57641. video.src = Util.base64('video/webm', 'GkXfowEAAAAAAAAfQoaBAUL3gQFC8oEEQvOBCEKChHdlYm1Ch4ECQoWBAhhTgGcBAAAAAAAH4xFNm3RALE27i1OrhBVJqWZTrIHfTbuMU6uEFlSua1OsggEwTbuMU6uEHFO7a1OsggfG7AEAAAAAAACkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmAQAAAAAAAEUq17GDD0JATYCNTGF2ZjU2LjQwLjEwMVdBjUxhdmY1Ni40MC4xMDFzpJAGSJTMbsLpDt/ySkipgX1fRImIQO1MAAAAAAAWVK5rAQAAAAAAADuuAQAAAAAAADLXgQFzxYEBnIEAIrWcg3VuZIaFVl9WUDmDgQEj44OEO5rKAOABAAAAAAAABrCBsLqBkB9DtnUBAAAAAAAAo+eBAKOmgQAAgKJJg0IAAV4BHsAHBIODCoAACmH2MAAAZxgz4dPSTFi5JACjloED6ACmAECSnABMQAADYAAAWi0quoCjloEH0ACmAECSnABNwAADYAAAWi0quoCjloELuACmAECSnABNgAADYAAAWi0quoCjloEPoACmAECSnABNYAADYAAAWi0quoCjloETiACmAECSnABNIAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTnghdwo5aBAAAApgBAkpwATOAAA2AAAFotKrqAo5aBA+gApgBAkpwATMAAA2AAAFotKrqAo5aBB9AApgBAkpwATIAAA2AAAFotKrqAo5aBC7gApgBAkpwATEAAA2AAAFotKrqAo5aBD6AApgDAkpwAQ2AAA2AAAFotKrqAo5aBE4gApgBAkpwATCAAA2AAAFotKrqAH0O2dQEAAAAAAACU54Iu4KOWgQAAAKYAQJKcAEvAAANgAABaLSq6gKOWgQPoAKYAQJKcAEtgAANgAABaLSq6gKOWgQfQAKYAQJKcAEsAAANgAABaLSq6gKOWgQu4AKYAQJKcAEqAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEogAANgAABaLSq6gKOWgROIAKYAQJKcAEnAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCRlCjloEAAACmAECSnABJgAADYAAAWi0quoCjloED6ACmAECSnABJIAADYAAAWi0quoCjloEH0ACmAMCSnABDYAADYAAAWi0quoCjloELuACmAECSnABI4AADYAAAWi0quoCjloEPoACmAECSnABIoAADYAAAWi0quoCjloETiACmAECSnABIYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngl3Ao5aBAAAApgBAkpwASCAAA2AAAFotKrqAo5aBA+gApgBAkpwASAAAA2AAAFotKrqAo5aBB9AApgBAkpwAR8AAA2AAAFotKrqAo5aBC7gApgBAkpwAR4AAA2AAAFotKrqAo5aBD6AApgBAkpwAR2AAA2AAAFotKrqAo5aBE4gApgBAkpwARyAAA2AAAFotKrqAH0O2dQEAAAAAAACU54J1MKOWgQAAAKYAwJKcAENgAANgAABaLSq6gKOWgQPoAKYAQJKcAEbgAANgAABaLSq6gKOWgQfQAKYAQJKcAEagAANgAABaLSq6gKOWgQu4AKYAQJKcAEaAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEZAAANgAABaLSq6gKOWgROIAKYAQJKcAEYAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCjKCjloEAAACmAECSnABF4AADYAAAWi0quoCjloED6ACmAECSnABFwAADYAAAWi0quoCjloEH0ACmAECSnABFoAADYAAAWi0quoCjloELuACmAECSnABFgAADYAAAWi0quoCjloEPoACmAMCSnABDYAADYAAAWi0quoCjloETiACmAECSnABFYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngqQQo5aBAAAApgBAkpwARUAAA2AAAFotKrqAo5aBA+gApgBAkpwARSAAA2AAAFotKrqAo5aBB9AApgBAkpwARQAAA2AAAFotKrqAo5aBC7gApgBAkpwARQAAA2AAAFotKrqAo5aBD6AApgBAkpwAROAAA2AAAFotKrqAo5aBE4gApgBAkpwARMAAA2AAAFotKrqAH0O2dQEAAAAAAACU54K7gKOWgQAAAKYAQJKcAESgAANgAABaLSq6gKOWgQPoAKYAQJKcAESAAANgAABaLSq6gKOWgQfQAKYAwJKcAENgAANgAABaLSq6gKOWgQu4AKYAQJKcAERgAANgAABaLSq6gKOWgQ+gAKYAQJKcAERAAANgAABaLSq6gKOWgROIAKYAQJKcAEQgAANgAABaLSq6gB9DtnUBAAAAAAAAlOeC0vCjloEAAACmAECSnABEIAADYAAAWi0quoCjloED6ACmAECSnABEAAADYAAAWi0quoCjloEH0ACmAECSnABD4AADYAAAWi0quoCjloELuACmAECSnABDwAADYAAAWi0quoCjloEPoACmAECSnABDoAADYAAAWi0quoCjloETiACmAECSnABDgAADYAAAWi0quoAcU7trAQAAAAAAABG7j7OBALeK94EB8YIBd/CBAw==');
  57642. video.play();
  57643. }
  57644. };
  57645. this.release = function() {
  57646. video.pause();
  57647. video.src = '';
  57648. };
  57649. }
  57650. function iOSWakeLock() {
  57651. var timer = null;
  57652. this.request = function() {
  57653. if (!timer) {
  57654. timer = setInterval(function() {
  57655. window.location.href = '/';
  57656. setTimeout(window.stop, 0);
  57657. }, 15000);
  57658. }
  57659. }
  57660. this.release = function() {
  57661. if (timer) {
  57662. clearInterval(timer);
  57663. timer = null;
  57664. }
  57665. }
  57666. }
  57667. function getWakeLock() {
  57668. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  57669. if (userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
  57670. return iOSWakeLock;
  57671. } else {
  57672. return AndroidWakeLock;
  57673. }
  57674. }
  57675. module.exports = getWakeLock();
  57676. },{"./util.js":188}]},{},[152])(152)
  57677. });
  57678. //# sourceMappingURL=aframe-master.js.map