2
0

three.js 863 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342
  1. // File:src/Three.js
  2. /**
  3. * @author mrdoob / http://mrdoob.com/
  4. */
  5. var THREE = { REVISION: '74dev' };
  6. //
  7. if ( typeof define === 'function' && define.amd ) {
  8. define( 'three', THREE );
  9. } else if ( 'undefined' !== typeof exports && 'undefined' !== typeof module ) {
  10. module.exports = THREE;
  11. }
  12. // polyfills
  13. if ( self.requestAnimationFrame === undefined || self.cancelAnimationFrame === undefined ) {
  14. // Missing in Android stock browser.
  15. ( function () {
  16. var lastTime = 0;
  17. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  18. for ( var x = 0; x < vendors.length && ! self.requestAnimationFrame; ++ x ) {
  19. self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ];
  20. self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  21. }
  22. if ( self.requestAnimationFrame === undefined && self.setTimeout !== undefined ) {
  23. self.requestAnimationFrame = function ( callback ) {
  24. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  25. var id = self.setTimeout( function () {
  26. callback( currTime + timeToCall );
  27. }, timeToCall );
  28. lastTime = currTime + timeToCall;
  29. return id;
  30. };
  31. }
  32. if ( self.cancelAnimationFrame === undefined && self.clearTimeout !== undefined ) {
  33. self.cancelAnimationFrame = function ( id ) {
  34. self.clearTimeout( id );
  35. };
  36. }
  37. } )();
  38. }
  39. //
  40. if ( self.performance === undefined ) {
  41. self.performance = {};
  42. }
  43. if ( self.performance.now === undefined ) {
  44. ( function () {
  45. var start = Date.now();
  46. self.performance.now = function () {
  47. return Date.now() - start;
  48. }
  49. } )();
  50. }
  51. //
  52. if ( Number.EPSILON === undefined ) {
  53. Number.EPSILON = Math.pow( 2, -52 );
  54. }
  55. //
  56. if ( Math.sign === undefined ) {
  57. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  58. Math.sign = function ( x ) {
  59. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  60. };
  61. }
  62. if ( Function.prototype.name === undefined && Object.defineProperty !== undefined ) {
  63. // Missing in IE9-11.
  64. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  65. Object.defineProperty( Function.prototype, 'name', {
  66. get: function () {
  67. return this.toString().match( /^\s*function\s*(\S*)\s*\(/ )[ 1 ];
  68. }
  69. } );
  70. }
  71. if ( Object.assign === undefined ) {
  72. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  73. Object.defineProperty( Object, 'assign', {
  74. writable: true,
  75. configurable: true,
  76. value: function(target) {
  77. 'use strict';
  78. if ( target === undefined || target === null ) {
  79. throw new TypeError( "Cannot convert first argument to object" );
  80. }
  81. var to = Object( target );
  82. for ( var i = 1, n = arguments.length; i !== n; ++ i ) {
  83. var nextSource = arguments[ i ];
  84. if ( nextSource === undefined || nextSource === null ) continue;
  85. nextSource = Object( nextSource );
  86. var keysArray = Object.keys( nextSource );
  87. for ( var nextIndex = 0, len = keysArray.length; nextIndex !== len; ++ nextIndex ) {
  88. var nextKey = keysArray[ nextIndex ];
  89. var desc = Object.getOwnPropertyDescriptor( nextSource, nextKey );
  90. if ( desc !== undefined && desc.enumerable ) {
  91. to[ nextKey ] = nextSource[ nextKey ];
  92. }
  93. }
  94. }
  95. return to;
  96. }
  97. } );
  98. }
  99. // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button
  100. THREE.MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  101. // GL STATE CONSTANTS
  102. THREE.CullFaceNone = 0;
  103. THREE.CullFaceBack = 1;
  104. THREE.CullFaceFront = 2;
  105. THREE.CullFaceFrontBack = 3;
  106. THREE.FrontFaceDirectionCW = 0;
  107. THREE.FrontFaceDirectionCCW = 1;
  108. // SHADOWING TYPES
  109. THREE.BasicShadowMap = 0;
  110. THREE.PCFShadowMap = 1;
  111. THREE.PCFSoftShadowMap = 2;
  112. // MATERIAL CONSTANTS
  113. // side
  114. THREE.FrontSide = 0;
  115. THREE.BackSide = 1;
  116. THREE.DoubleSide = 2;
  117. // shading
  118. THREE.FlatShading = 1;
  119. THREE.SmoothShading = 2;
  120. // colors
  121. THREE.NoColors = 0;
  122. THREE.FaceColors = 1;
  123. THREE.VertexColors = 2;
  124. // blending modes
  125. THREE.NoBlending = 0;
  126. THREE.NormalBlending = 1;
  127. THREE.AdditiveBlending = 2;
  128. THREE.SubtractiveBlending = 3;
  129. THREE.MultiplyBlending = 4;
  130. THREE.CustomBlending = 5;
  131. // custom blending equations
  132. // (numbers start from 100 not to clash with other
  133. // mappings to OpenGL constants defined in Texture.js)
  134. THREE.AddEquation = 100;
  135. THREE.SubtractEquation = 101;
  136. THREE.ReverseSubtractEquation = 102;
  137. THREE.MinEquation = 103;
  138. THREE.MaxEquation = 104;
  139. // custom blending destination factors
  140. THREE.ZeroFactor = 200;
  141. THREE.OneFactor = 201;
  142. THREE.SrcColorFactor = 202;
  143. THREE.OneMinusSrcColorFactor = 203;
  144. THREE.SrcAlphaFactor = 204;
  145. THREE.OneMinusSrcAlphaFactor = 205;
  146. THREE.DstAlphaFactor = 206;
  147. THREE.OneMinusDstAlphaFactor = 207;
  148. // custom blending source factors
  149. //THREE.ZeroFactor = 200;
  150. //THREE.OneFactor = 201;
  151. //THREE.SrcAlphaFactor = 204;
  152. //THREE.OneMinusSrcAlphaFactor = 205;
  153. //THREE.DstAlphaFactor = 206;
  154. //THREE.OneMinusDstAlphaFactor = 207;
  155. THREE.DstColorFactor = 208;
  156. THREE.OneMinusDstColorFactor = 209;
  157. THREE.SrcAlphaSaturateFactor = 210;
  158. // depth modes
  159. THREE.NeverDepth = 0;
  160. THREE.AlwaysDepth = 1;
  161. THREE.LessDepth = 2;
  162. THREE.LessEqualDepth = 3;
  163. THREE.EqualDepth = 4;
  164. THREE.GreaterEqualDepth = 5;
  165. THREE.GreaterDepth = 6;
  166. THREE.NotEqualDepth = 7;
  167. // TEXTURE CONSTANTS
  168. THREE.MultiplyOperation = 0;
  169. THREE.MixOperation = 1;
  170. THREE.AddOperation = 2;
  171. // Mapping modes
  172. THREE.UVMapping = 300;
  173. THREE.CubeReflectionMapping = 301;
  174. THREE.CubeRefractionMapping = 302;
  175. THREE.EquirectangularReflectionMapping = 303;
  176. THREE.EquirectangularRefractionMapping = 304;
  177. THREE.SphericalReflectionMapping = 305;
  178. // Wrapping modes
  179. THREE.RepeatWrapping = 1000;
  180. THREE.ClampToEdgeWrapping = 1001;
  181. THREE.MirroredRepeatWrapping = 1002;
  182. // Filters
  183. THREE.NearestFilter = 1003;
  184. THREE.NearestMipMapNearestFilter = 1004;
  185. THREE.NearestMipMapLinearFilter = 1005;
  186. THREE.LinearFilter = 1006;
  187. THREE.LinearMipMapNearestFilter = 1007;
  188. THREE.LinearMipMapLinearFilter = 1008;
  189. // Data types
  190. THREE.UnsignedByteType = 1009;
  191. THREE.ByteType = 1010;
  192. THREE.ShortType = 1011;
  193. THREE.UnsignedShortType = 1012;
  194. THREE.IntType = 1013;
  195. THREE.UnsignedIntType = 1014;
  196. THREE.FloatType = 1015;
  197. THREE.HalfFloatType = 1025;
  198. // Pixel types
  199. //THREE.UnsignedByteType = 1009;
  200. THREE.UnsignedShort4444Type = 1016;
  201. THREE.UnsignedShort5551Type = 1017;
  202. THREE.UnsignedShort565Type = 1018;
  203. // Pixel formats
  204. THREE.AlphaFormat = 1019;
  205. THREE.RGBFormat = 1020;
  206. THREE.RGBAFormat = 1021;
  207. THREE.LuminanceFormat = 1022;
  208. THREE.LuminanceAlphaFormat = 1023;
  209. // THREE.RGBEFormat handled as THREE.RGBAFormat in shaders
  210. THREE.RGBEFormat = THREE.RGBAFormat; //1024;
  211. // DDS / ST3C Compressed texture formats
  212. THREE.RGB_S3TC_DXT1_Format = 2001;
  213. THREE.RGBA_S3TC_DXT1_Format = 2002;
  214. THREE.RGBA_S3TC_DXT3_Format = 2003;
  215. THREE.RGBA_S3TC_DXT5_Format = 2004;
  216. // PVRTC compressed texture formats
  217. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  218. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  219. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  220. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  221. // Loop styles for AnimationAction
  222. THREE.LoopOnce = 2200;
  223. THREE.LoopRepeat = 2201;
  224. THREE.LoopPingPong = 2202;
  225. // Interpolation
  226. THREE.InterpolateDiscrete = 2300;
  227. THREE.InterpolateLinear = 2301;
  228. THREE.InterpolateSmooth = 2302;
  229. // Interpolant ending modes
  230. THREE.ZeroCurvatureEnding = 2400;
  231. THREE.ZeroSlopeEnding = 2401;
  232. THREE.WrapAroundEnding = 2402;
  233. // File:src/math/Color.js
  234. /**
  235. * @author mrdoob / http://mrdoob.com/
  236. */
  237. THREE.Color = function ( color ) {
  238. if ( arguments.length === 3 ) {
  239. return this.fromArray( arguments );
  240. }
  241. return this.set( color );
  242. };
  243. THREE.Color.prototype = {
  244. constructor: THREE.Color,
  245. r: 1, g: 1, b: 1,
  246. set: function ( value ) {
  247. if ( value instanceof THREE.Color ) {
  248. this.copy( value );
  249. } else if ( typeof value === 'number' ) {
  250. this.setHex( value );
  251. } else if ( typeof value === 'string' ) {
  252. this.setStyle( value );
  253. }
  254. return this;
  255. },
  256. setHex: function ( hex ) {
  257. hex = Math.floor( hex );
  258. this.r = ( hex >> 16 & 255 ) / 255;
  259. this.g = ( hex >> 8 & 255 ) / 255;
  260. this.b = ( hex & 255 ) / 255;
  261. return this;
  262. },
  263. setRGB: function ( r, g, b ) {
  264. this.r = r;
  265. this.g = g;
  266. this.b = b;
  267. return this;
  268. },
  269. setHSL: function () {
  270. function hue2rgb( p, q, t ) {
  271. if ( t < 0 ) t += 1;
  272. if ( t > 1 ) t -= 1;
  273. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  274. if ( t < 1 / 2 ) return q;
  275. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  276. return p;
  277. }
  278. return function ( h, s, l ) {
  279. // h,s,l ranges are in 0.0 - 1.0
  280. h = THREE.Math.euclideanModulo( h, 1 );
  281. s = THREE.Math.clamp( s, 0, 1 );
  282. l = THREE.Math.clamp( l, 0, 1 );
  283. if ( s === 0 ) {
  284. this.r = this.g = this.b = l;
  285. } else {
  286. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  287. var q = ( 2 * l ) - p;
  288. this.r = hue2rgb( q, p, h + 1 / 3 );
  289. this.g = hue2rgb( q, p, h );
  290. this.b = hue2rgb( q, p, h - 1 / 3 );
  291. }
  292. return this;
  293. };
  294. }(),
  295. setStyle: function ( style ) {
  296. function handleAlpha( string ) {
  297. if ( string === undefined ) return;
  298. if ( parseFloat( string ) < 1 ) {
  299. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  300. }
  301. }
  302. var m;
  303. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  304. // rgb / hsl
  305. var color;
  306. var name = m[ 1 ];
  307. var components = m[ 2 ];
  308. switch ( name ) {
  309. case 'rgb':
  310. case 'rgba':
  311. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  312. // rgb(255,0,0) rgba(255,0,0,0.5)
  313. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  314. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  315. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  316. handleAlpha( color[ 5 ] );
  317. return this;
  318. }
  319. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  320. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  321. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  322. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  323. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  324. handleAlpha( color[ 5 ] );
  325. return this;
  326. }
  327. break;
  328. case 'hsl':
  329. case 'hsla':
  330. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  331. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  332. var h = parseFloat( color[ 1 ] ) / 360;
  333. var s = parseInt( color[ 2 ], 10 ) / 100;
  334. var l = parseInt( color[ 3 ], 10 ) / 100;
  335. handleAlpha( color[ 5 ] );
  336. return this.setHSL( h, s, l );
  337. }
  338. break;
  339. }
  340. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  341. // hex color
  342. var hex = m[ 1 ];
  343. var size = hex.length;
  344. if ( size === 3 ) {
  345. // #ff0
  346. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  347. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  348. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  349. return this;
  350. } else if ( size === 6 ) {
  351. // #ff0000
  352. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  353. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  354. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  355. return this;
  356. }
  357. }
  358. if ( style && style.length > 0 ) {
  359. // color keywords
  360. var hex = THREE.ColorKeywords[ style ];
  361. if ( hex !== undefined ) {
  362. // red
  363. this.setHex( hex );
  364. } else {
  365. // unknown color
  366. console.warn( 'THREE.Color: Unknown color ' + style );
  367. }
  368. }
  369. return this;
  370. },
  371. clone: function () {
  372. return new this.constructor( this.r, this.g, this.b );
  373. },
  374. copy: function ( color ) {
  375. this.r = color.r;
  376. this.g = color.g;
  377. this.b = color.b;
  378. return this;
  379. },
  380. copyGammaToLinear: function ( color, gammaFactor ) {
  381. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  382. this.r = Math.pow( color.r, gammaFactor );
  383. this.g = Math.pow( color.g, gammaFactor );
  384. this.b = Math.pow( color.b, gammaFactor );
  385. return this;
  386. },
  387. copyLinearToGamma: function ( color, gammaFactor ) {
  388. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  389. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  390. this.r = Math.pow( color.r, safeInverse );
  391. this.g = Math.pow( color.g, safeInverse );
  392. this.b = Math.pow( color.b, safeInverse );
  393. return this;
  394. },
  395. convertGammaToLinear: function () {
  396. var r = this.r, g = this.g, b = this.b;
  397. this.r = r * r;
  398. this.g = g * g;
  399. this.b = b * b;
  400. return this;
  401. },
  402. convertLinearToGamma: function () {
  403. this.r = Math.sqrt( this.r );
  404. this.g = Math.sqrt( this.g );
  405. this.b = Math.sqrt( this.b );
  406. return this;
  407. },
  408. getHex: function () {
  409. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  410. },
  411. getHexString: function () {
  412. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  413. },
  414. getHSL: function ( optionalTarget ) {
  415. // h,s,l ranges are in 0.0 - 1.0
  416. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  417. var r = this.r, g = this.g, b = this.b;
  418. var max = Math.max( r, g, b );
  419. var min = Math.min( r, g, b );
  420. var hue, saturation;
  421. var lightness = ( min + max ) / 2.0;
  422. if ( min === max ) {
  423. hue = 0;
  424. saturation = 0;
  425. } else {
  426. var delta = max - min;
  427. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  428. switch ( max ) {
  429. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  430. case g: hue = ( b - r ) / delta + 2; break;
  431. case b: hue = ( r - g ) / delta + 4; break;
  432. }
  433. hue /= 6;
  434. }
  435. hsl.h = hue;
  436. hsl.s = saturation;
  437. hsl.l = lightness;
  438. return hsl;
  439. },
  440. getStyle: function () {
  441. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  442. },
  443. offsetHSL: function ( h, s, l ) {
  444. var hsl = this.getHSL();
  445. hsl.h += h; hsl.s += s; hsl.l += l;
  446. this.setHSL( hsl.h, hsl.s, hsl.l );
  447. return this;
  448. },
  449. add: function ( color ) {
  450. this.r += color.r;
  451. this.g += color.g;
  452. this.b += color.b;
  453. return this;
  454. },
  455. addColors: function ( color1, color2 ) {
  456. this.r = color1.r + color2.r;
  457. this.g = color1.g + color2.g;
  458. this.b = color1.b + color2.b;
  459. return this;
  460. },
  461. addScalar: function ( s ) {
  462. this.r += s;
  463. this.g += s;
  464. this.b += s;
  465. return this;
  466. },
  467. multiply: function ( color ) {
  468. this.r *= color.r;
  469. this.g *= color.g;
  470. this.b *= color.b;
  471. return this;
  472. },
  473. multiplyScalar: function ( s ) {
  474. this.r *= s;
  475. this.g *= s;
  476. this.b *= s;
  477. return this;
  478. },
  479. lerp: function ( color, alpha ) {
  480. this.r += ( color.r - this.r ) * alpha;
  481. this.g += ( color.g - this.g ) * alpha;
  482. this.b += ( color.b - this.b ) * alpha;
  483. return this;
  484. },
  485. equals: function ( c ) {
  486. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  487. },
  488. fromArray: function ( array, offset ) {
  489. if ( offset === undefined ) offset = 0;
  490. this.r = array[ offset ];
  491. this.g = array[ offset + 1 ];
  492. this.b = array[ offset + 2 ];
  493. return this;
  494. },
  495. toArray: function ( array, offset ) {
  496. if ( array === undefined ) array = [];
  497. if ( offset === undefined ) offset = 0;
  498. array[ offset ] = this.r;
  499. array[ offset + 1 ] = this.g;
  500. array[ offset + 2 ] = this.b;
  501. return array;
  502. }
  503. };
  504. THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  505. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  506. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  507. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  508. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  509. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  510. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  511. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  512. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  513. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  514. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  515. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  516. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  517. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  518. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  519. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  520. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  521. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  522. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  523. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  524. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  525. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  526. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  527. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  528. // File:src/math/Quaternion.js
  529. /**
  530. * @author mikael emtinger / http://gomo.se/
  531. * @author alteredq / http://alteredqualia.com/
  532. * @author WestLangley / http://github.com/WestLangley
  533. * @author bhouston / http://clara.io
  534. */
  535. THREE.Quaternion = function ( x, y, z, w ) {
  536. this._x = x || 0;
  537. this._y = y || 0;
  538. this._z = z || 0;
  539. this._w = ( w !== undefined ) ? w : 1;
  540. };
  541. THREE.Quaternion.prototype = {
  542. constructor: THREE.Quaternion,
  543. get x () {
  544. return this._x;
  545. },
  546. set x ( value ) {
  547. this._x = value;
  548. this.onChangeCallback();
  549. },
  550. get y () {
  551. return this._y;
  552. },
  553. set y ( value ) {
  554. this._y = value;
  555. this.onChangeCallback();
  556. },
  557. get z () {
  558. return this._z;
  559. },
  560. set z ( value ) {
  561. this._z = value;
  562. this.onChangeCallback();
  563. },
  564. get w () {
  565. return this._w;
  566. },
  567. set w ( value ) {
  568. this._w = value;
  569. this.onChangeCallback();
  570. },
  571. set: function ( x, y, z, w ) {
  572. this._x = x;
  573. this._y = y;
  574. this._z = z;
  575. this._w = w;
  576. this.onChangeCallback();
  577. return this;
  578. },
  579. clone: function () {
  580. return new this.constructor( this._x, this._y, this._z, this._w );
  581. },
  582. copy: function ( quaternion ) {
  583. this._x = quaternion.x;
  584. this._y = quaternion.y;
  585. this._z = quaternion.z;
  586. this._w = quaternion.w;
  587. this.onChangeCallback();
  588. return this;
  589. },
  590. setFromEuler: function ( euler, update ) {
  591. if ( euler instanceof THREE.Euler === false ) {
  592. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  593. }
  594. // http://www.mathworks.com/matlabcentral/fileexchange/
  595. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  596. // content/SpinCalc.m
  597. var c1 = Math.cos( euler._x / 2 );
  598. var c2 = Math.cos( euler._y / 2 );
  599. var c3 = Math.cos( euler._z / 2 );
  600. var s1 = Math.sin( euler._x / 2 );
  601. var s2 = Math.sin( euler._y / 2 );
  602. var s3 = Math.sin( euler._z / 2 );
  603. var order = euler.order;
  604. if ( order === 'XYZ' ) {
  605. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  606. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  607. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  608. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  609. } else if ( order === 'YXZ' ) {
  610. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  611. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  612. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  613. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  614. } else if ( order === 'ZXY' ) {
  615. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  616. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  617. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  618. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  619. } else if ( order === 'ZYX' ) {
  620. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  621. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  622. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  623. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  624. } else if ( order === 'YZX' ) {
  625. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  626. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  627. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  628. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  629. } else if ( order === 'XZY' ) {
  630. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  631. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  632. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  633. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  634. }
  635. if ( update !== false ) this.onChangeCallback();
  636. return this;
  637. },
  638. setFromAxisAngle: function ( axis, angle ) {
  639. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  640. // assumes axis is normalized
  641. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  642. this._x = axis.x * s;
  643. this._y = axis.y * s;
  644. this._z = axis.z * s;
  645. this._w = Math.cos( halfAngle );
  646. this.onChangeCallback();
  647. return this;
  648. },
  649. setFromRotationMatrix: function ( m ) {
  650. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  651. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  652. var te = m.elements,
  653. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  654. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  655. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  656. trace = m11 + m22 + m33,
  657. s;
  658. if ( trace > 0 ) {
  659. s = 0.5 / Math.sqrt( trace + 1.0 );
  660. this._w = 0.25 / s;
  661. this._x = ( m32 - m23 ) * s;
  662. this._y = ( m13 - m31 ) * s;
  663. this._z = ( m21 - m12 ) * s;
  664. } else if ( m11 > m22 && m11 > m33 ) {
  665. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  666. this._w = ( m32 - m23 ) / s;
  667. this._x = 0.25 * s;
  668. this._y = ( m12 + m21 ) / s;
  669. this._z = ( m13 + m31 ) / s;
  670. } else if ( m22 > m33 ) {
  671. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  672. this._w = ( m13 - m31 ) / s;
  673. this._x = ( m12 + m21 ) / s;
  674. this._y = 0.25 * s;
  675. this._z = ( m23 + m32 ) / s;
  676. } else {
  677. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  678. this._w = ( m21 - m12 ) / s;
  679. this._x = ( m13 + m31 ) / s;
  680. this._y = ( m23 + m32 ) / s;
  681. this._z = 0.25 * s;
  682. }
  683. this.onChangeCallback();
  684. return this;
  685. },
  686. setFromUnitVectors: function () {
  687. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  688. // assumes direction vectors vFrom and vTo are normalized
  689. var v1, r;
  690. var EPS = 0.000001;
  691. return function ( vFrom, vTo ) {
  692. if ( v1 === undefined ) v1 = new THREE.Vector3();
  693. r = vFrom.dot( vTo ) + 1;
  694. if ( r < EPS ) {
  695. r = 0;
  696. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  697. v1.set( - vFrom.y, vFrom.x, 0 );
  698. } else {
  699. v1.set( 0, - vFrom.z, vFrom.y );
  700. }
  701. } else {
  702. v1.crossVectors( vFrom, vTo );
  703. }
  704. this._x = v1.x;
  705. this._y = v1.y;
  706. this._z = v1.z;
  707. this._w = r;
  708. this.normalize();
  709. return this;
  710. }
  711. }(),
  712. inverse: function () {
  713. this.conjugate().normalize();
  714. return this;
  715. },
  716. conjugate: function () {
  717. this._x *= - 1;
  718. this._y *= - 1;
  719. this._z *= - 1;
  720. this.onChangeCallback();
  721. return this;
  722. },
  723. dot: function ( v ) {
  724. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  725. },
  726. lengthSq: function () {
  727. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  728. },
  729. length: function () {
  730. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  731. },
  732. normalize: function () {
  733. var l = this.length();
  734. if ( l === 0 ) {
  735. this._x = 0;
  736. this._y = 0;
  737. this._z = 0;
  738. this._w = 1;
  739. } else {
  740. l = 1 / l;
  741. this._x = this._x * l;
  742. this._y = this._y * l;
  743. this._z = this._z * l;
  744. this._w = this._w * l;
  745. }
  746. this.onChangeCallback();
  747. return this;
  748. },
  749. multiply: function ( q, p ) {
  750. if ( p !== undefined ) {
  751. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  752. return this.multiplyQuaternions( q, p );
  753. }
  754. return this.multiplyQuaternions( this, q );
  755. },
  756. multiplyQuaternions: function ( a, b ) {
  757. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  758. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  759. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  760. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  761. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  762. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  763. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  764. this.onChangeCallback();
  765. return this;
  766. },
  767. slerp: function ( qb, t ) {
  768. if ( t === 0 ) return this;
  769. if ( t === 1 ) return this.copy( qb );
  770. var x = this._x, y = this._y, z = this._z, w = this._w;
  771. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  772. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  773. if ( cosHalfTheta < 0 ) {
  774. this._w = - qb._w;
  775. this._x = - qb._x;
  776. this._y = - qb._y;
  777. this._z = - qb._z;
  778. cosHalfTheta = - cosHalfTheta;
  779. } else {
  780. this.copy( qb );
  781. }
  782. if ( cosHalfTheta >= 1.0 ) {
  783. this._w = w;
  784. this._x = x;
  785. this._y = y;
  786. this._z = z;
  787. return this;
  788. }
  789. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  790. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  791. this._w = 0.5 * ( w + this._w );
  792. this._x = 0.5 * ( x + this._x );
  793. this._y = 0.5 * ( y + this._y );
  794. this._z = 0.5 * ( z + this._z );
  795. return this;
  796. }
  797. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  798. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  799. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  800. this._w = ( w * ratioA + this._w * ratioB );
  801. this._x = ( x * ratioA + this._x * ratioB );
  802. this._y = ( y * ratioA + this._y * ratioB );
  803. this._z = ( z * ratioA + this._z * ratioB );
  804. this.onChangeCallback();
  805. return this;
  806. },
  807. equals: function ( quaternion ) {
  808. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  809. },
  810. fromArray: function ( array, offset ) {
  811. if ( offset === undefined ) offset = 0;
  812. this._x = array[ offset ];
  813. this._y = array[ offset + 1 ];
  814. this._z = array[ offset + 2 ];
  815. this._w = array[ offset + 3 ];
  816. this.onChangeCallback();
  817. return this;
  818. },
  819. toArray: function ( array, offset ) {
  820. if ( array === undefined ) array = [];
  821. if ( offset === undefined ) offset = 0;
  822. array[ offset ] = this._x;
  823. array[ offset + 1 ] = this._y;
  824. array[ offset + 2 ] = this._z;
  825. array[ offset + 3 ] = this._w;
  826. return array;
  827. },
  828. onChange: function ( callback ) {
  829. this.onChangeCallback = callback;
  830. return this;
  831. },
  832. onChangeCallback: function () {}
  833. };
  834. Object.assign( THREE.Quaternion, {
  835. slerp: function( qa, qb, qm, t ) {
  836. return qm.copy( qa ).slerp( qb, t );
  837. },
  838. slerpFlat: function(
  839. dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  840. // fuzz-free, array-based Quaternion SLERP operation
  841. var x0 = src0[ srcOffset0 ],
  842. y0 = src0[ srcOffset0 + 1 ],
  843. z0 = src0[ srcOffset0 + 2 ],
  844. w0 = src0[ srcOffset0 + 3 ],
  845. x1 = src1[ srcOffset1 ],
  846. y1 = src1[ srcOffset1 + 1 ],
  847. z1 = src1[ srcOffset1 + 2 ],
  848. w1 = src1[ srcOffset1 + 3 ];
  849. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  850. var s = 1 - t,
  851. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  852. dir = ( cos >= 0 ? 1 : -1 ),
  853. sqrSin = 1 - cos * cos;
  854. // Skip the Slerp for tiny steps to avoid numeric problems:
  855. if ( sqrSin > Number.EPSILON ) {
  856. var sin = Math.sqrt( sqrSin ),
  857. len = Math.atan2( sin, cos * dir );
  858. s = Math.sin( s * len ) / sin;
  859. t = Math.sin( t * len ) / sin;
  860. }
  861. var tDir = t * dir;
  862. x0 = x0 * s + x1 * tDir;
  863. y0 = y0 * s + y1 * tDir;
  864. z0 = z0 * s + z1 * tDir;
  865. w0 = w0 * s + w1 * tDir;
  866. // Normalize in case we just did a lerp:
  867. if ( s === 1 - t ) {
  868. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  869. x0 *= f;
  870. y0 *= f;
  871. z0 *= f;
  872. w0 *= f;
  873. }
  874. }
  875. dst[ dstOffset ] = x0;
  876. dst[ dstOffset + 1 ] = y0;
  877. dst[ dstOffset + 2 ] = z0;
  878. dst[ dstOffset + 3 ] = w0;
  879. }
  880. } );
  881. // File:src/math/Vector2.js
  882. /**
  883. * @author mrdoob / http://mrdoob.com/
  884. * @author philogb / http://blog.thejit.org/
  885. * @author egraether / http://egraether.com/
  886. * @author zz85 / http://www.lab4games.net/zz85/blog
  887. */
  888. THREE.Vector2 = function ( x, y ) {
  889. this.x = x || 0;
  890. this.y = y || 0;
  891. };
  892. THREE.Vector2.prototype = {
  893. constructor: THREE.Vector2,
  894. get width() { return this.x },
  895. set width( value ) { this.x = value },
  896. get height() { return this.y },
  897. set height( value ) { this.y = value },
  898. //
  899. set: function ( x, y ) {
  900. this.x = x;
  901. this.y = y;
  902. return this;
  903. },
  904. setX: function ( x ) {
  905. this.x = x;
  906. return this;
  907. },
  908. setY: function ( y ) {
  909. this.y = y;
  910. return this;
  911. },
  912. setComponent: function ( index, value ) {
  913. switch ( index ) {
  914. case 0: this.x = value; break;
  915. case 1: this.y = value; break;
  916. default: throw new Error( 'index is out of range: ' + index );
  917. }
  918. },
  919. getComponent: function ( index ) {
  920. switch ( index ) {
  921. case 0: return this.x;
  922. case 1: return this.y;
  923. default: throw new Error( 'index is out of range: ' + index );
  924. }
  925. },
  926. clone: function () {
  927. return new this.constructor( this.x, this.y );
  928. },
  929. copy: function ( v ) {
  930. this.x = v.x;
  931. this.y = v.y;
  932. return this;
  933. },
  934. add: function ( v, w ) {
  935. if ( w !== undefined ) {
  936. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  937. return this.addVectors( v, w );
  938. }
  939. this.x += v.x;
  940. this.y += v.y;
  941. return this;
  942. },
  943. addScalar: function ( s ) {
  944. this.x += s;
  945. this.y += s;
  946. return this;
  947. },
  948. addVectors: function ( a, b ) {
  949. this.x = a.x + b.x;
  950. this.y = a.y + b.y;
  951. return this;
  952. },
  953. addScaledVector: function ( v, s ) {
  954. this.x += v.x * s;
  955. this.y += v.y * s;
  956. return this;
  957. },
  958. sub: function ( v, w ) {
  959. if ( w !== undefined ) {
  960. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  961. return this.subVectors( v, w );
  962. }
  963. this.x -= v.x;
  964. this.y -= v.y;
  965. return this;
  966. },
  967. subScalar: function ( s ) {
  968. this.x -= s;
  969. this.y -= s;
  970. return this;
  971. },
  972. subVectors: function ( a, b ) {
  973. this.x = a.x - b.x;
  974. this.y = a.y - b.y;
  975. return this;
  976. },
  977. multiply: function ( v ) {
  978. this.x *= v.x;
  979. this.y *= v.y;
  980. return this;
  981. },
  982. multiplyScalar: function ( scalar ) {
  983. if ( isFinite( scalar ) ) {
  984. this.x *= scalar;
  985. this.y *= scalar;
  986. } else {
  987. this.x = 0;
  988. this.y = 0;
  989. }
  990. return this;
  991. },
  992. divide: function ( v ) {
  993. this.x /= v.x;
  994. this.y /= v.y;
  995. return this;
  996. },
  997. divideScalar: function ( scalar ) {
  998. return this.multiplyScalar( 1 / scalar );
  999. },
  1000. min: function ( v ) {
  1001. this.x = Math.min( this.x, v.x );
  1002. this.y = Math.min( this.y, v.y );
  1003. return this;
  1004. },
  1005. max: function ( v ) {
  1006. this.x = Math.max( this.x, v.x );
  1007. this.y = Math.max( this.y, v.y );
  1008. return this;
  1009. },
  1010. clamp: function ( min, max ) {
  1011. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1012. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1013. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1014. return this;
  1015. },
  1016. clampScalar: function () {
  1017. var min, max;
  1018. return function clampScalar( minVal, maxVal ) {
  1019. if ( min === undefined ) {
  1020. min = new THREE.Vector2();
  1021. max = new THREE.Vector2();
  1022. }
  1023. min.set( minVal, minVal );
  1024. max.set( maxVal, maxVal );
  1025. return this.clamp( min, max );
  1026. };
  1027. }(),
  1028. clampLength: function ( min, max ) {
  1029. var length = this.length();
  1030. this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  1031. return this;
  1032. },
  1033. floor: function () {
  1034. this.x = Math.floor( this.x );
  1035. this.y = Math.floor( this.y );
  1036. return this;
  1037. },
  1038. ceil: function () {
  1039. this.x = Math.ceil( this.x );
  1040. this.y = Math.ceil( this.y );
  1041. return this;
  1042. },
  1043. round: function () {
  1044. this.x = Math.round( this.x );
  1045. this.y = Math.round( this.y );
  1046. return this;
  1047. },
  1048. roundToZero: function () {
  1049. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1050. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1051. return this;
  1052. },
  1053. negate: function () {
  1054. this.x = - this.x;
  1055. this.y = - this.y;
  1056. return this;
  1057. },
  1058. dot: function ( v ) {
  1059. return this.x * v.x + this.y * v.y;
  1060. },
  1061. lengthSq: function () {
  1062. return this.x * this.x + this.y * this.y;
  1063. },
  1064. length: function () {
  1065. return Math.sqrt( this.x * this.x + this.y * this.y );
  1066. },
  1067. lengthManhattan: function() {
  1068. return Math.abs( this.x ) + Math.abs( this.y );
  1069. },
  1070. normalize: function () {
  1071. return this.divideScalar( this.length() );
  1072. },
  1073. distanceTo: function ( v ) {
  1074. return Math.sqrt( this.distanceToSquared( v ) );
  1075. },
  1076. distanceToSquared: function ( v ) {
  1077. var dx = this.x - v.x, dy = this.y - v.y;
  1078. return dx * dx + dy * dy;
  1079. },
  1080. setLength: function ( length ) {
  1081. return this.multiplyScalar( length / this.length() );
  1082. },
  1083. lerp: function ( v, alpha ) {
  1084. this.x += ( v.x - this.x ) * alpha;
  1085. this.y += ( v.y - this.y ) * alpha;
  1086. return this;
  1087. },
  1088. lerpVectors: function ( v1, v2, alpha ) {
  1089. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1090. return this;
  1091. },
  1092. equals: function ( v ) {
  1093. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  1094. },
  1095. fromArray: function ( array, offset ) {
  1096. if ( offset === undefined ) offset = 0;
  1097. this.x = array[ offset ];
  1098. this.y = array[ offset + 1 ];
  1099. return this;
  1100. },
  1101. toArray: function ( array, offset ) {
  1102. if ( array === undefined ) array = [];
  1103. if ( offset === undefined ) offset = 0;
  1104. array[ offset ] = this.x;
  1105. array[ offset + 1 ] = this.y;
  1106. return array;
  1107. },
  1108. fromAttribute: function ( attribute, index, offset ) {
  1109. if ( offset === undefined ) offset = 0;
  1110. index = index * attribute.itemSize + offset;
  1111. this.x = attribute.array[ index ];
  1112. this.y = attribute.array[ index + 1 ];
  1113. return this;
  1114. },
  1115. rotateAround: function ( center, angle ) {
  1116. var c = Math.cos( angle ), s = Math.sin( angle );
  1117. var x = this.x - center.x;
  1118. var y = this.y - center.y;
  1119. this.x = x * c - y * s + center.x;
  1120. this.y = x * s + y * c + center.y;
  1121. return this;
  1122. }
  1123. };
  1124. // File:src/math/Vector3.js
  1125. /**
  1126. * @author mrdoob / http://mrdoob.com/
  1127. * @author *kile / http://kile.stravaganza.org/
  1128. * @author philogb / http://blog.thejit.org/
  1129. * @author mikael emtinger / http://gomo.se/
  1130. * @author egraether / http://egraether.com/
  1131. * @author WestLangley / http://github.com/WestLangley
  1132. */
  1133. THREE.Vector3 = function ( x, y, z ) {
  1134. this.x = x || 0;
  1135. this.y = y || 0;
  1136. this.z = z || 0;
  1137. };
  1138. THREE.Vector3.prototype = {
  1139. constructor: THREE.Vector3,
  1140. set: function ( x, y, z ) {
  1141. this.x = x;
  1142. this.y = y;
  1143. this.z = z;
  1144. return this;
  1145. },
  1146. setX: function ( x ) {
  1147. this.x = x;
  1148. return this;
  1149. },
  1150. setY: function ( y ) {
  1151. this.y = y;
  1152. return this;
  1153. },
  1154. setZ: function ( z ) {
  1155. this.z = z;
  1156. return this;
  1157. },
  1158. setComponent: function ( index, value ) {
  1159. switch ( index ) {
  1160. case 0: this.x = value; break;
  1161. case 1: this.y = value; break;
  1162. case 2: this.z = value; break;
  1163. default: throw new Error( 'index is out of range: ' + index );
  1164. }
  1165. },
  1166. getComponent: function ( index ) {
  1167. switch ( index ) {
  1168. case 0: return this.x;
  1169. case 1: return this.y;
  1170. case 2: return this.z;
  1171. default: throw new Error( 'index is out of range: ' + index );
  1172. }
  1173. },
  1174. clone: function () {
  1175. return new this.constructor( this.x, this.y, this.z );
  1176. },
  1177. copy: function ( v ) {
  1178. this.x = v.x;
  1179. this.y = v.y;
  1180. this.z = v.z;
  1181. return this;
  1182. },
  1183. add: function ( v, w ) {
  1184. if ( w !== undefined ) {
  1185. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1186. return this.addVectors( v, w );
  1187. }
  1188. this.x += v.x;
  1189. this.y += v.y;
  1190. this.z += v.z;
  1191. return this;
  1192. },
  1193. addScalar: function ( s ) {
  1194. this.x += s;
  1195. this.y += s;
  1196. this.z += s;
  1197. return this;
  1198. },
  1199. addVectors: function ( a, b ) {
  1200. this.x = a.x + b.x;
  1201. this.y = a.y + b.y;
  1202. this.z = a.z + b.z;
  1203. return this;
  1204. },
  1205. addScaledVector: function ( v, s ) {
  1206. this.x += v.x * s;
  1207. this.y += v.y * s;
  1208. this.z += v.z * s;
  1209. return this;
  1210. },
  1211. sub: function ( v, w ) {
  1212. if ( w !== undefined ) {
  1213. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1214. return this.subVectors( v, w );
  1215. }
  1216. this.x -= v.x;
  1217. this.y -= v.y;
  1218. this.z -= v.z;
  1219. return this;
  1220. },
  1221. subScalar: function ( s ) {
  1222. this.x -= s;
  1223. this.y -= s;
  1224. this.z -= s;
  1225. return this;
  1226. },
  1227. subVectors: function ( a, b ) {
  1228. this.x = a.x - b.x;
  1229. this.y = a.y - b.y;
  1230. this.z = a.z - b.z;
  1231. return this;
  1232. },
  1233. multiply: function ( v, w ) {
  1234. if ( w !== undefined ) {
  1235. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1236. return this.multiplyVectors( v, w );
  1237. }
  1238. this.x *= v.x;
  1239. this.y *= v.y;
  1240. this.z *= v.z;
  1241. return this;
  1242. },
  1243. multiplyScalar: function ( scalar ) {
  1244. if ( isFinite( scalar ) ) {
  1245. this.x *= scalar;
  1246. this.y *= scalar;
  1247. this.z *= scalar;
  1248. } else {
  1249. this.x = 0;
  1250. this.y = 0;
  1251. this.z = 0;
  1252. }
  1253. return this;
  1254. },
  1255. multiplyVectors: function ( a, b ) {
  1256. this.x = a.x * b.x;
  1257. this.y = a.y * b.y;
  1258. this.z = a.z * b.z;
  1259. return this;
  1260. },
  1261. applyEuler: function () {
  1262. var quaternion;
  1263. return function applyEuler( euler ) {
  1264. if ( euler instanceof THREE.Euler === false ) {
  1265. console.error( 'THREE.Vector3: .applyEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  1266. }
  1267. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1268. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1269. return this;
  1270. };
  1271. }(),
  1272. applyAxisAngle: function () {
  1273. var quaternion;
  1274. return function applyAxisAngle( axis, angle ) {
  1275. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1276. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1277. return this;
  1278. };
  1279. }(),
  1280. applyMatrix3: function ( m ) {
  1281. var x = this.x;
  1282. var y = this.y;
  1283. var z = this.z;
  1284. var e = m.elements;
  1285. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1286. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1287. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1288. return this;
  1289. },
  1290. applyMatrix4: function ( m ) {
  1291. // input: THREE.Matrix4 affine matrix
  1292. var x = this.x, y = this.y, z = this.z;
  1293. var e = m.elements;
  1294. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1295. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1296. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1297. return this;
  1298. },
  1299. applyProjection: function ( m ) {
  1300. // input: THREE.Matrix4 projection matrix
  1301. var x = this.x, y = this.y, z = this.z;
  1302. var e = m.elements;
  1303. var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
  1304. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
  1305. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
  1306. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
  1307. return this;
  1308. },
  1309. applyQuaternion: function ( q ) {
  1310. var x = this.x;
  1311. var y = this.y;
  1312. var z = this.z;
  1313. var qx = q.x;
  1314. var qy = q.y;
  1315. var qz = q.z;
  1316. var qw = q.w;
  1317. // calculate quat * vector
  1318. var ix = qw * x + qy * z - qz * y;
  1319. var iy = qw * y + qz * x - qx * z;
  1320. var iz = qw * z + qx * y - qy * x;
  1321. var iw = - qx * x - qy * y - qz * z;
  1322. // calculate result * inverse quat
  1323. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1324. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1325. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1326. return this;
  1327. },
  1328. project: function () {
  1329. var matrix;
  1330. return function project( camera ) {
  1331. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1332. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1333. return this.applyProjection( matrix );
  1334. };
  1335. }(),
  1336. unproject: function () {
  1337. var matrix;
  1338. return function unproject( camera ) {
  1339. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1340. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1341. return this.applyProjection( matrix );
  1342. };
  1343. }(),
  1344. transformDirection: function ( m ) {
  1345. // input: THREE.Matrix4 affine matrix
  1346. // vector interpreted as a direction
  1347. var x = this.x, y = this.y, z = this.z;
  1348. var e = m.elements;
  1349. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1350. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1351. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1352. this.normalize();
  1353. return this;
  1354. },
  1355. divide: function ( v ) {
  1356. this.x /= v.x;
  1357. this.y /= v.y;
  1358. this.z /= v.z;
  1359. return this;
  1360. },
  1361. divideScalar: function ( scalar ) {
  1362. return this.multiplyScalar( 1 / scalar );
  1363. },
  1364. min: function ( v ) {
  1365. this.x = Math.min( this.x, v.x );
  1366. this.y = Math.min( this.y, v.y );
  1367. this.z = Math.min( this.z, v.z );
  1368. return this;
  1369. },
  1370. max: function ( v ) {
  1371. this.x = Math.max( this.x, v.x );
  1372. this.y = Math.max( this.y, v.y );
  1373. this.z = Math.max( this.z, v.z );
  1374. return this;
  1375. },
  1376. clamp: function ( min, max ) {
  1377. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1378. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1379. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1380. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1381. return this;
  1382. },
  1383. clampScalar: function () {
  1384. var min, max;
  1385. return function clampScalar( minVal, maxVal ) {
  1386. if ( min === undefined ) {
  1387. min = new THREE.Vector3();
  1388. max = new THREE.Vector3();
  1389. }
  1390. min.set( minVal, minVal, minVal );
  1391. max.set( maxVal, maxVal, maxVal );
  1392. return this.clamp( min, max );
  1393. };
  1394. }(),
  1395. clampLength: function ( min, max ) {
  1396. var length = this.length();
  1397. this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  1398. return this;
  1399. },
  1400. floor: function () {
  1401. this.x = Math.floor( this.x );
  1402. this.y = Math.floor( this.y );
  1403. this.z = Math.floor( this.z );
  1404. return this;
  1405. },
  1406. ceil: function () {
  1407. this.x = Math.ceil( this.x );
  1408. this.y = Math.ceil( this.y );
  1409. this.z = Math.ceil( this.z );
  1410. return this;
  1411. },
  1412. round: function () {
  1413. this.x = Math.round( this.x );
  1414. this.y = Math.round( this.y );
  1415. this.z = Math.round( this.z );
  1416. return this;
  1417. },
  1418. roundToZero: function () {
  1419. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1420. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1421. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1422. return this;
  1423. },
  1424. negate: function () {
  1425. this.x = - this.x;
  1426. this.y = - this.y;
  1427. this.z = - this.z;
  1428. return this;
  1429. },
  1430. dot: function ( v ) {
  1431. return this.x * v.x + this.y * v.y + this.z * v.z;
  1432. },
  1433. lengthSq: function () {
  1434. return this.x * this.x + this.y * this.y + this.z * this.z;
  1435. },
  1436. length: function () {
  1437. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1438. },
  1439. lengthManhattan: function () {
  1440. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1441. },
  1442. normalize: function () {
  1443. return this.divideScalar( this.length() );
  1444. },
  1445. setLength: function ( length ) {
  1446. return this.multiplyScalar( length / this.length() );
  1447. },
  1448. lerp: function ( v, alpha ) {
  1449. this.x += ( v.x - this.x ) * alpha;
  1450. this.y += ( v.y - this.y ) * alpha;
  1451. this.z += ( v.z - this.z ) * alpha;
  1452. return this;
  1453. },
  1454. lerpVectors: function ( v1, v2, alpha ) {
  1455. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1456. return this;
  1457. },
  1458. cross: function ( v, w ) {
  1459. if ( w !== undefined ) {
  1460. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1461. return this.crossVectors( v, w );
  1462. }
  1463. var x = this.x, y = this.y, z = this.z;
  1464. this.x = y * v.z - z * v.y;
  1465. this.y = z * v.x - x * v.z;
  1466. this.z = x * v.y - y * v.x;
  1467. return this;
  1468. },
  1469. crossVectors: function ( a, b ) {
  1470. var ax = a.x, ay = a.y, az = a.z;
  1471. var bx = b.x, by = b.y, bz = b.z;
  1472. this.x = ay * bz - az * by;
  1473. this.y = az * bx - ax * bz;
  1474. this.z = ax * by - ay * bx;
  1475. return this;
  1476. },
  1477. projectOnVector: function () {
  1478. var v1, dot;
  1479. return function projectOnVector( vector ) {
  1480. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1481. v1.copy( vector ).normalize();
  1482. dot = this.dot( v1 );
  1483. return this.copy( v1 ).multiplyScalar( dot );
  1484. };
  1485. }(),
  1486. projectOnPlane: function () {
  1487. var v1;
  1488. return function projectOnPlane( planeNormal ) {
  1489. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1490. v1.copy( this ).projectOnVector( planeNormal );
  1491. return this.sub( v1 );
  1492. }
  1493. }(),
  1494. reflect: function () {
  1495. // reflect incident vector off plane orthogonal to normal
  1496. // normal is assumed to have unit length
  1497. var v1;
  1498. return function reflect( normal ) {
  1499. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1500. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1501. }
  1502. }(),
  1503. angleTo: function ( v ) {
  1504. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  1505. // clamp, to handle numerical problems
  1506. return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) );
  1507. },
  1508. distanceTo: function ( v ) {
  1509. return Math.sqrt( this.distanceToSquared( v ) );
  1510. },
  1511. distanceToSquared: function ( v ) {
  1512. var dx = this.x - v.x;
  1513. var dy = this.y - v.y;
  1514. var dz = this.z - v.z;
  1515. return dx * dx + dy * dy + dz * dz;
  1516. },
  1517. setFromMatrixPosition: function ( m ) {
  1518. this.x = m.elements[ 12 ];
  1519. this.y = m.elements[ 13 ];
  1520. this.z = m.elements[ 14 ];
  1521. return this;
  1522. },
  1523. setFromMatrixScale: function ( m ) {
  1524. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1525. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1526. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1527. this.x = sx;
  1528. this.y = sy;
  1529. this.z = sz;
  1530. return this;
  1531. },
  1532. setFromMatrixColumn: function ( index, matrix ) {
  1533. var offset = index * 4;
  1534. var me = matrix.elements;
  1535. this.x = me[ offset ];
  1536. this.y = me[ offset + 1 ];
  1537. this.z = me[ offset + 2 ];
  1538. return this;
  1539. },
  1540. equals: function ( v ) {
  1541. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1542. },
  1543. fromArray: function ( array, offset ) {
  1544. if ( offset === undefined ) offset = 0;
  1545. this.x = array[ offset ];
  1546. this.y = array[ offset + 1 ];
  1547. this.z = array[ offset + 2 ];
  1548. return this;
  1549. },
  1550. toArray: function ( array, offset ) {
  1551. if ( array === undefined ) array = [];
  1552. if ( offset === undefined ) offset = 0;
  1553. array[ offset ] = this.x;
  1554. array[ offset + 1 ] = this.y;
  1555. array[ offset + 2 ] = this.z;
  1556. return array;
  1557. },
  1558. fromAttribute: function ( attribute, index, offset ) {
  1559. if ( offset === undefined ) offset = 0;
  1560. index = index * attribute.itemSize + offset;
  1561. this.x = attribute.array[ index ];
  1562. this.y = attribute.array[ index + 1 ];
  1563. this.z = attribute.array[ index + 2 ];
  1564. return this;
  1565. }
  1566. };
  1567. // File:src/math/Vector4.js
  1568. /**
  1569. * @author supereggbert / http://www.paulbrunt.co.uk/
  1570. * @author philogb / http://blog.thejit.org/
  1571. * @author mikael emtinger / http://gomo.se/
  1572. * @author egraether / http://egraether.com/
  1573. * @author WestLangley / http://github.com/WestLangley
  1574. */
  1575. THREE.Vector4 = function ( x, y, z, w ) {
  1576. this.x = x || 0;
  1577. this.y = y || 0;
  1578. this.z = z || 0;
  1579. this.w = ( w !== undefined ) ? w : 1;
  1580. };
  1581. THREE.Vector4.prototype = {
  1582. constructor: THREE.Vector4,
  1583. set: function ( x, y, z, w ) {
  1584. this.x = x;
  1585. this.y = y;
  1586. this.z = z;
  1587. this.w = w;
  1588. return this;
  1589. },
  1590. setX: function ( x ) {
  1591. this.x = x;
  1592. return this;
  1593. },
  1594. setY: function ( y ) {
  1595. this.y = y;
  1596. return this;
  1597. },
  1598. setZ: function ( z ) {
  1599. this.z = z;
  1600. return this;
  1601. },
  1602. setW: function ( w ) {
  1603. this.w = w;
  1604. return this;
  1605. },
  1606. setComponent: function ( index, value ) {
  1607. switch ( index ) {
  1608. case 0: this.x = value; break;
  1609. case 1: this.y = value; break;
  1610. case 2: this.z = value; break;
  1611. case 3: this.w = value; break;
  1612. default: throw new Error( 'index is out of range: ' + index );
  1613. }
  1614. },
  1615. getComponent: function ( index ) {
  1616. switch ( index ) {
  1617. case 0: return this.x;
  1618. case 1: return this.y;
  1619. case 2: return this.z;
  1620. case 3: return this.w;
  1621. default: throw new Error( 'index is out of range: ' + index );
  1622. }
  1623. },
  1624. clone: function () {
  1625. return new this.constructor( this.x, this.y, this.z, this.w );
  1626. },
  1627. copy: function ( v ) {
  1628. this.x = v.x;
  1629. this.y = v.y;
  1630. this.z = v.z;
  1631. this.w = ( v.w !== undefined ) ? v.w : 1;
  1632. return this;
  1633. },
  1634. add: function ( v, w ) {
  1635. if ( w !== undefined ) {
  1636. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1637. return this.addVectors( v, w );
  1638. }
  1639. this.x += v.x;
  1640. this.y += v.y;
  1641. this.z += v.z;
  1642. this.w += v.w;
  1643. return this;
  1644. },
  1645. addScalar: function ( s ) {
  1646. this.x += s;
  1647. this.y += s;
  1648. this.z += s;
  1649. this.w += s;
  1650. return this;
  1651. },
  1652. addVectors: function ( a, b ) {
  1653. this.x = a.x + b.x;
  1654. this.y = a.y + b.y;
  1655. this.z = a.z + b.z;
  1656. this.w = a.w + b.w;
  1657. return this;
  1658. },
  1659. addScaledVector: function ( v, s ) {
  1660. this.x += v.x * s;
  1661. this.y += v.y * s;
  1662. this.z += v.z * s;
  1663. this.w += v.w * s;
  1664. return this;
  1665. },
  1666. sub: function ( v, w ) {
  1667. if ( w !== undefined ) {
  1668. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1669. return this.subVectors( v, w );
  1670. }
  1671. this.x -= v.x;
  1672. this.y -= v.y;
  1673. this.z -= v.z;
  1674. this.w -= v.w;
  1675. return this;
  1676. },
  1677. subScalar: function ( s ) {
  1678. this.x -= s;
  1679. this.y -= s;
  1680. this.z -= s;
  1681. this.w -= s;
  1682. return this;
  1683. },
  1684. subVectors: function ( a, b ) {
  1685. this.x = a.x - b.x;
  1686. this.y = a.y - b.y;
  1687. this.z = a.z - b.z;
  1688. this.w = a.w - b.w;
  1689. return this;
  1690. },
  1691. multiplyScalar: function ( scalar ) {
  1692. if ( isFinite( scalar ) ) {
  1693. this.x *= scalar;
  1694. this.y *= scalar;
  1695. this.z *= scalar;
  1696. this.w *= scalar;
  1697. } else {
  1698. this.x = 0;
  1699. this.y = 0;
  1700. this.z = 0;
  1701. this.w = 0;
  1702. }
  1703. return this;
  1704. },
  1705. applyMatrix4: function ( m ) {
  1706. var x = this.x;
  1707. var y = this.y;
  1708. var z = this.z;
  1709. var w = this.w;
  1710. var e = m.elements;
  1711. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1712. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1713. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1714. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1715. return this;
  1716. },
  1717. divideScalar: function ( scalar ) {
  1718. return this.multiplyScalar( 1 / scalar );
  1719. },
  1720. setAxisAngleFromQuaternion: function ( q ) {
  1721. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1722. // q is assumed to be normalized
  1723. this.w = 2 * Math.acos( q.w );
  1724. var s = Math.sqrt( 1 - q.w * q.w );
  1725. if ( s < 0.0001 ) {
  1726. this.x = 1;
  1727. this.y = 0;
  1728. this.z = 0;
  1729. } else {
  1730. this.x = q.x / s;
  1731. this.y = q.y / s;
  1732. this.z = q.z / s;
  1733. }
  1734. return this;
  1735. },
  1736. setAxisAngleFromRotationMatrix: function ( m ) {
  1737. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1738. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1739. var angle, x, y, z, // variables for result
  1740. epsilon = 0.01, // margin to allow for rounding errors
  1741. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1742. te = m.elements,
  1743. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1744. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1745. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1746. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1747. && ( Math.abs( m13 - m31 ) < epsilon )
  1748. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1749. // singularity found
  1750. // first check for identity matrix which must have +1 for all terms
  1751. // in leading diagonal and zero in other terms
  1752. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1753. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1754. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1755. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1756. // this singularity is identity matrix so angle = 0
  1757. this.set( 1, 0, 0, 0 );
  1758. return this; // zero angle, arbitrary axis
  1759. }
  1760. // otherwise this singularity is angle = 180
  1761. angle = Math.PI;
  1762. var xx = ( m11 + 1 ) / 2;
  1763. var yy = ( m22 + 1 ) / 2;
  1764. var zz = ( m33 + 1 ) / 2;
  1765. var xy = ( m12 + m21 ) / 4;
  1766. var xz = ( m13 + m31 ) / 4;
  1767. var yz = ( m23 + m32 ) / 4;
  1768. if ( ( xx > yy ) && ( xx > zz ) ) {
  1769. // m11 is the largest diagonal term
  1770. if ( xx < epsilon ) {
  1771. x = 0;
  1772. y = 0.707106781;
  1773. z = 0.707106781;
  1774. } else {
  1775. x = Math.sqrt( xx );
  1776. y = xy / x;
  1777. z = xz / x;
  1778. }
  1779. } else if ( yy > zz ) {
  1780. // m22 is the largest diagonal term
  1781. if ( yy < epsilon ) {
  1782. x = 0.707106781;
  1783. y = 0;
  1784. z = 0.707106781;
  1785. } else {
  1786. y = Math.sqrt( yy );
  1787. x = xy / y;
  1788. z = yz / y;
  1789. }
  1790. } else {
  1791. // m33 is the largest diagonal term so base result on this
  1792. if ( zz < epsilon ) {
  1793. x = 0.707106781;
  1794. y = 0.707106781;
  1795. z = 0;
  1796. } else {
  1797. z = Math.sqrt( zz );
  1798. x = xz / z;
  1799. y = yz / z;
  1800. }
  1801. }
  1802. this.set( x, y, z, angle );
  1803. return this; // return 180 deg rotation
  1804. }
  1805. // as we have reached here there are no singularities so we can handle normally
  1806. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1807. + ( m13 - m31 ) * ( m13 - m31 )
  1808. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1809. if ( Math.abs( s ) < 0.001 ) s = 1;
  1810. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1811. // caught by singularity test above, but I've left it in just in case
  1812. this.x = ( m32 - m23 ) / s;
  1813. this.y = ( m13 - m31 ) / s;
  1814. this.z = ( m21 - m12 ) / s;
  1815. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1816. return this;
  1817. },
  1818. min: function ( v ) {
  1819. this.x = Math.min( this.x, v.x );
  1820. this.y = Math.min( this.y, v.y );
  1821. this.z = Math.min( this.z, v.z );
  1822. this.w = Math.min( this.w, v.w );
  1823. return this;
  1824. },
  1825. max: function ( v ) {
  1826. this.x = Math.max( this.x, v.x );
  1827. this.y = Math.max( this.y, v.y );
  1828. this.z = Math.max( this.z, v.z );
  1829. this.w = Math.max( this.w, v.w );
  1830. return this;
  1831. },
  1832. clamp: function ( min, max ) {
  1833. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1834. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1835. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1836. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1837. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1838. return this;
  1839. },
  1840. clampScalar: function () {
  1841. var min, max;
  1842. return function clampScalar( minVal, maxVal ) {
  1843. if ( min === undefined ) {
  1844. min = new THREE.Vector4();
  1845. max = new THREE.Vector4();
  1846. }
  1847. min.set( minVal, minVal, minVal, minVal );
  1848. max.set( maxVal, maxVal, maxVal, maxVal );
  1849. return this.clamp( min, max );
  1850. };
  1851. }(),
  1852. floor: function () {
  1853. this.x = Math.floor( this.x );
  1854. this.y = Math.floor( this.y );
  1855. this.z = Math.floor( this.z );
  1856. this.w = Math.floor( this.w );
  1857. return this;
  1858. },
  1859. ceil: function () {
  1860. this.x = Math.ceil( this.x );
  1861. this.y = Math.ceil( this.y );
  1862. this.z = Math.ceil( this.z );
  1863. this.w = Math.ceil( this.w );
  1864. return this;
  1865. },
  1866. round: function () {
  1867. this.x = Math.round( this.x );
  1868. this.y = Math.round( this.y );
  1869. this.z = Math.round( this.z );
  1870. this.w = Math.round( this.w );
  1871. return this;
  1872. },
  1873. roundToZero: function () {
  1874. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1875. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1876. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1877. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1878. return this;
  1879. },
  1880. negate: function () {
  1881. this.x = - this.x;
  1882. this.y = - this.y;
  1883. this.z = - this.z;
  1884. this.w = - this.w;
  1885. return this;
  1886. },
  1887. dot: function ( v ) {
  1888. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1889. },
  1890. lengthSq: function () {
  1891. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1892. },
  1893. length: function () {
  1894. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1895. },
  1896. lengthManhattan: function () {
  1897. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1898. },
  1899. normalize: function () {
  1900. return this.divideScalar( this.length() );
  1901. },
  1902. setLength: function ( length ) {
  1903. return this.multiplyScalar( length / this.length() );
  1904. },
  1905. lerp: function ( v, alpha ) {
  1906. this.x += ( v.x - this.x ) * alpha;
  1907. this.y += ( v.y - this.y ) * alpha;
  1908. this.z += ( v.z - this.z ) * alpha;
  1909. this.w += ( v.w - this.w ) * alpha;
  1910. return this;
  1911. },
  1912. lerpVectors: function ( v1, v2, alpha ) {
  1913. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1914. return this;
  1915. },
  1916. equals: function ( v ) {
  1917. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1918. },
  1919. fromArray: function ( array, offset ) {
  1920. if ( offset === undefined ) offset = 0;
  1921. this.x = array[ offset ];
  1922. this.y = array[ offset + 1 ];
  1923. this.z = array[ offset + 2 ];
  1924. this.w = array[ offset + 3 ];
  1925. return this;
  1926. },
  1927. toArray: function ( array, offset ) {
  1928. if ( array === undefined ) array = [];
  1929. if ( offset === undefined ) offset = 0;
  1930. array[ offset ] = this.x;
  1931. array[ offset + 1 ] = this.y;
  1932. array[ offset + 2 ] = this.z;
  1933. array[ offset + 3 ] = this.w;
  1934. return array;
  1935. },
  1936. fromAttribute: function ( attribute, index, offset ) {
  1937. if ( offset === undefined ) offset = 0;
  1938. index = index * attribute.itemSize + offset;
  1939. this.x = attribute.array[ index ];
  1940. this.y = attribute.array[ index + 1 ];
  1941. this.z = attribute.array[ index + 2 ];
  1942. this.w = attribute.array[ index + 3 ];
  1943. return this;
  1944. }
  1945. };
  1946. // File:src/math/Euler.js
  1947. /**
  1948. * @author mrdoob / http://mrdoob.com/
  1949. * @author WestLangley / http://github.com/WestLangley
  1950. * @author bhouston / http://clara.io
  1951. */
  1952. THREE.Euler = function ( x, y, z, order ) {
  1953. this._x = x || 0;
  1954. this._y = y || 0;
  1955. this._z = z || 0;
  1956. this._order = order || THREE.Euler.DefaultOrder;
  1957. };
  1958. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1959. THREE.Euler.DefaultOrder = 'XYZ';
  1960. THREE.Euler.prototype = {
  1961. constructor: THREE.Euler,
  1962. get x () {
  1963. return this._x;
  1964. },
  1965. set x ( value ) {
  1966. this._x = value;
  1967. this.onChangeCallback();
  1968. },
  1969. get y () {
  1970. return this._y;
  1971. },
  1972. set y ( value ) {
  1973. this._y = value;
  1974. this.onChangeCallback();
  1975. },
  1976. get z () {
  1977. return this._z;
  1978. },
  1979. set z ( value ) {
  1980. this._z = value;
  1981. this.onChangeCallback();
  1982. },
  1983. get order () {
  1984. return this._order;
  1985. },
  1986. set order ( value ) {
  1987. this._order = value;
  1988. this.onChangeCallback();
  1989. },
  1990. set: function ( x, y, z, order ) {
  1991. this._x = x;
  1992. this._y = y;
  1993. this._z = z;
  1994. this._order = order || this._order;
  1995. this.onChangeCallback();
  1996. return this;
  1997. },
  1998. clone: function () {
  1999. return new this.constructor( this._x, this._y, this._z, this._order);
  2000. },
  2001. copy: function ( euler ) {
  2002. this._x = euler._x;
  2003. this._y = euler._y;
  2004. this._z = euler._z;
  2005. this._order = euler._order;
  2006. this.onChangeCallback();
  2007. return this;
  2008. },
  2009. setFromRotationMatrix: function ( m, order, update ) {
  2010. var clamp = THREE.Math.clamp;
  2011. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2012. var te = m.elements;
  2013. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  2014. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  2015. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  2016. order = order || this._order;
  2017. if ( order === 'XYZ' ) {
  2018. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  2019. if ( Math.abs( m13 ) < 0.99999 ) {
  2020. this._x = Math.atan2( - m23, m33 );
  2021. this._z = Math.atan2( - m12, m11 );
  2022. } else {
  2023. this._x = Math.atan2( m32, m22 );
  2024. this._z = 0;
  2025. }
  2026. } else if ( order === 'YXZ' ) {
  2027. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  2028. if ( Math.abs( m23 ) < 0.99999 ) {
  2029. this._y = Math.atan2( m13, m33 );
  2030. this._z = Math.atan2( m21, m22 );
  2031. } else {
  2032. this._y = Math.atan2( - m31, m11 );
  2033. this._z = 0;
  2034. }
  2035. } else if ( order === 'ZXY' ) {
  2036. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  2037. if ( Math.abs( m32 ) < 0.99999 ) {
  2038. this._y = Math.atan2( - m31, m33 );
  2039. this._z = Math.atan2( - m12, m22 );
  2040. } else {
  2041. this._y = 0;
  2042. this._z = Math.atan2( m21, m11 );
  2043. }
  2044. } else if ( order === 'ZYX' ) {
  2045. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  2046. if ( Math.abs( m31 ) < 0.99999 ) {
  2047. this._x = Math.atan2( m32, m33 );
  2048. this._z = Math.atan2( m21, m11 );
  2049. } else {
  2050. this._x = 0;
  2051. this._z = Math.atan2( - m12, m22 );
  2052. }
  2053. } else if ( order === 'YZX' ) {
  2054. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  2055. if ( Math.abs( m21 ) < 0.99999 ) {
  2056. this._x = Math.atan2( - m23, m22 );
  2057. this._y = Math.atan2( - m31, m11 );
  2058. } else {
  2059. this._x = 0;
  2060. this._y = Math.atan2( m13, m33 );
  2061. }
  2062. } else if ( order === 'XZY' ) {
  2063. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  2064. if ( Math.abs( m12 ) < 0.99999 ) {
  2065. this._x = Math.atan2( m32, m22 );
  2066. this._y = Math.atan2( m13, m11 );
  2067. } else {
  2068. this._x = Math.atan2( - m23, m33 );
  2069. this._y = 0;
  2070. }
  2071. } else {
  2072. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order )
  2073. }
  2074. this._order = order;
  2075. if ( update !== false ) this.onChangeCallback();
  2076. return this;
  2077. },
  2078. setFromQuaternion: function () {
  2079. var matrix;
  2080. return function ( q, order, update ) {
  2081. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  2082. matrix.makeRotationFromQuaternion( q );
  2083. this.setFromRotationMatrix( matrix, order, update );
  2084. return this;
  2085. };
  2086. }(),
  2087. setFromVector3: function ( v, order ) {
  2088. return this.set( v.x, v.y, v.z, order || this._order );
  2089. },
  2090. reorder: function () {
  2091. // WARNING: this discards revolution information -bhouston
  2092. var q = new THREE.Quaternion();
  2093. return function ( newOrder ) {
  2094. q.setFromEuler( this );
  2095. this.setFromQuaternion( q, newOrder );
  2096. };
  2097. }(),
  2098. equals: function ( euler ) {
  2099. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  2100. },
  2101. fromArray: function ( array ) {
  2102. this._x = array[ 0 ];
  2103. this._y = array[ 1 ];
  2104. this._z = array[ 2 ];
  2105. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  2106. this.onChangeCallback();
  2107. return this;
  2108. },
  2109. toArray: function ( array, offset ) {
  2110. if ( array === undefined ) array = [];
  2111. if ( offset === undefined ) offset = 0;
  2112. array[ offset ] = this._x;
  2113. array[ offset + 1 ] = this._y;
  2114. array[ offset + 2 ] = this._z;
  2115. array[ offset + 3 ] = this._order;
  2116. return array;
  2117. },
  2118. toVector3: function ( optionalResult ) {
  2119. if ( optionalResult ) {
  2120. return optionalResult.set( this._x, this._y, this._z );
  2121. } else {
  2122. return new THREE.Vector3( this._x, this._y, this._z );
  2123. }
  2124. },
  2125. onChange: function ( callback ) {
  2126. this.onChangeCallback = callback;
  2127. return this;
  2128. },
  2129. onChangeCallback: function () {}
  2130. };
  2131. // File:src/math/Line3.js
  2132. /**
  2133. * @author bhouston / http://clara.io
  2134. */
  2135. THREE.Line3 = function ( start, end ) {
  2136. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  2137. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  2138. };
  2139. THREE.Line3.prototype = {
  2140. constructor: THREE.Line3,
  2141. set: function ( start, end ) {
  2142. this.start.copy( start );
  2143. this.end.copy( end );
  2144. return this;
  2145. },
  2146. clone: function () {
  2147. return new this.constructor().copy( this );
  2148. },
  2149. copy: function ( line ) {
  2150. this.start.copy( line.start );
  2151. this.end.copy( line.end );
  2152. return this;
  2153. },
  2154. center: function ( optionalTarget ) {
  2155. var result = optionalTarget || new THREE.Vector3();
  2156. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  2157. },
  2158. delta: function ( optionalTarget ) {
  2159. var result = optionalTarget || new THREE.Vector3();
  2160. return result.subVectors( this.end, this.start );
  2161. },
  2162. distanceSq: function () {
  2163. return this.start.distanceToSquared( this.end );
  2164. },
  2165. distance: function () {
  2166. return this.start.distanceTo( this.end );
  2167. },
  2168. at: function ( t, optionalTarget ) {
  2169. var result = optionalTarget || new THREE.Vector3();
  2170. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2171. },
  2172. closestPointToPointParameter: function () {
  2173. var startP = new THREE.Vector3();
  2174. var startEnd = new THREE.Vector3();
  2175. return function ( point, clampToLine ) {
  2176. startP.subVectors( point, this.start );
  2177. startEnd.subVectors( this.end, this.start );
  2178. var startEnd2 = startEnd.dot( startEnd );
  2179. var startEnd_startP = startEnd.dot( startP );
  2180. var t = startEnd_startP / startEnd2;
  2181. if ( clampToLine ) {
  2182. t = THREE.Math.clamp( t, 0, 1 );
  2183. }
  2184. return t;
  2185. };
  2186. }(),
  2187. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  2188. var t = this.closestPointToPointParameter( point, clampToLine );
  2189. var result = optionalTarget || new THREE.Vector3();
  2190. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2191. },
  2192. applyMatrix4: function ( matrix ) {
  2193. this.start.applyMatrix4( matrix );
  2194. this.end.applyMatrix4( matrix );
  2195. return this;
  2196. },
  2197. equals: function ( line ) {
  2198. return line.start.equals( this.start ) && line.end.equals( this.end );
  2199. }
  2200. };
  2201. // File:src/math/Box2.js
  2202. /**
  2203. * @author bhouston / http://clara.io
  2204. */
  2205. THREE.Box2 = function ( min, max ) {
  2206. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  2207. this.max = ( max !== undefined ) ? max : new THREE.Vector2( - Infinity, - Infinity );
  2208. };
  2209. THREE.Box2.prototype = {
  2210. constructor: THREE.Box2,
  2211. set: function ( min, max ) {
  2212. this.min.copy( min );
  2213. this.max.copy( max );
  2214. return this;
  2215. },
  2216. setFromPoints: function ( points ) {
  2217. this.makeEmpty();
  2218. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2219. this.expandByPoint( points[ i ] )
  2220. }
  2221. return this;
  2222. },
  2223. setFromCenterAndSize: function () {
  2224. var v1 = new THREE.Vector2();
  2225. return function ( center, size ) {
  2226. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2227. this.min.copy( center ).sub( halfSize );
  2228. this.max.copy( center ).add( halfSize );
  2229. return this;
  2230. };
  2231. }(),
  2232. clone: function () {
  2233. return new this.constructor().copy( this );
  2234. },
  2235. copy: function ( box ) {
  2236. this.min.copy( box.min );
  2237. this.max.copy( box.max );
  2238. return this;
  2239. },
  2240. makeEmpty: function () {
  2241. this.min.x = this.min.y = Infinity;
  2242. this.max.x = this.max.y = - Infinity;
  2243. return this;
  2244. },
  2245. empty: function () {
  2246. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2247. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2248. },
  2249. center: function ( optionalTarget ) {
  2250. var result = optionalTarget || new THREE.Vector2();
  2251. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2252. },
  2253. size: function ( optionalTarget ) {
  2254. var result = optionalTarget || new THREE.Vector2();
  2255. return result.subVectors( this.max, this.min );
  2256. },
  2257. expandByPoint: function ( point ) {
  2258. this.min.min( point );
  2259. this.max.max( point );
  2260. return this;
  2261. },
  2262. expandByVector: function ( vector ) {
  2263. this.min.sub( vector );
  2264. this.max.add( vector );
  2265. return this;
  2266. },
  2267. expandByScalar: function ( scalar ) {
  2268. this.min.addScalar( - scalar );
  2269. this.max.addScalar( scalar );
  2270. return this;
  2271. },
  2272. containsPoint: function ( point ) {
  2273. if ( point.x < this.min.x || point.x > this.max.x ||
  2274. point.y < this.min.y || point.y > this.max.y ) {
  2275. return false;
  2276. }
  2277. return true;
  2278. },
  2279. containsBox: function ( box ) {
  2280. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2281. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2282. return true;
  2283. }
  2284. return false;
  2285. },
  2286. getParameter: function ( point, optionalTarget ) {
  2287. // This can potentially have a divide by zero if the box
  2288. // has a size dimension of 0.
  2289. var result = optionalTarget || new THREE.Vector2();
  2290. return result.set(
  2291. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2292. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2293. );
  2294. },
  2295. intersectsBox: function ( box ) {
  2296. // using 6 splitting planes to rule out intersections.
  2297. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2298. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2299. return false;
  2300. }
  2301. return true;
  2302. },
  2303. clampPoint: function ( point, optionalTarget ) {
  2304. var result = optionalTarget || new THREE.Vector2();
  2305. return result.copy( point ).clamp( this.min, this.max );
  2306. },
  2307. distanceToPoint: function () {
  2308. var v1 = new THREE.Vector2();
  2309. return function ( point ) {
  2310. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2311. return clampedPoint.sub( point ).length();
  2312. };
  2313. }(),
  2314. intersect: function ( box ) {
  2315. this.min.max( box.min );
  2316. this.max.min( box.max );
  2317. return this;
  2318. },
  2319. union: function ( box ) {
  2320. this.min.min( box.min );
  2321. this.max.max( box.max );
  2322. return this;
  2323. },
  2324. translate: function ( offset ) {
  2325. this.min.add( offset );
  2326. this.max.add( offset );
  2327. return this;
  2328. },
  2329. equals: function ( box ) {
  2330. return box.min.equals( this.min ) && box.max.equals( this.max );
  2331. }
  2332. };
  2333. // File:src/math/Box3.js
  2334. /**
  2335. * @author bhouston / http://clara.io
  2336. * @author WestLangley / http://github.com/WestLangley
  2337. */
  2338. THREE.Box3 = function ( min, max ) {
  2339. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2340. this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity );
  2341. };
  2342. THREE.Box3.prototype = {
  2343. constructor: THREE.Box3,
  2344. set: function ( min, max ) {
  2345. this.min.copy( min );
  2346. this.max.copy( max );
  2347. return this;
  2348. },
  2349. setFromPoints: function ( points ) {
  2350. this.makeEmpty();
  2351. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2352. this.expandByPoint( points[ i ] );
  2353. }
  2354. return this;
  2355. },
  2356. setFromCenterAndSize: function () {
  2357. var v1 = new THREE.Vector3();
  2358. return function ( center, size ) {
  2359. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2360. this.min.copy( center ).sub( halfSize );
  2361. this.max.copy( center ).add( halfSize );
  2362. return this;
  2363. };
  2364. }(),
  2365. setFromObject: function () {
  2366. // Computes the world-axis-aligned bounding box of an object (including its children),
  2367. // accounting for both the object's, and children's, world transforms
  2368. var v1 = new THREE.Vector3();
  2369. return function ( object ) {
  2370. var scope = this;
  2371. object.updateMatrixWorld( true );
  2372. this.makeEmpty();
  2373. object.traverse( function ( node ) {
  2374. var geometry = node.geometry;
  2375. if ( geometry !== undefined ) {
  2376. if ( geometry instanceof THREE.Geometry ) {
  2377. var vertices = geometry.vertices;
  2378. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  2379. v1.copy( vertices[ i ] );
  2380. v1.applyMatrix4( node.matrixWorld );
  2381. scope.expandByPoint( v1 );
  2382. }
  2383. } else if ( geometry instanceof THREE.BufferGeometry && geometry.attributes[ 'position' ] !== undefined ) {
  2384. var positions = geometry.attributes[ 'position' ].array;
  2385. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  2386. v1.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  2387. v1.applyMatrix4( node.matrixWorld );
  2388. scope.expandByPoint( v1 );
  2389. }
  2390. }
  2391. }
  2392. } );
  2393. return this;
  2394. };
  2395. }(),
  2396. clone: function () {
  2397. return new this.constructor().copy( this );
  2398. },
  2399. copy: function ( box ) {
  2400. this.min.copy( box.min );
  2401. this.max.copy( box.max );
  2402. return this;
  2403. },
  2404. makeEmpty: function () {
  2405. this.min.x = this.min.y = this.min.z = Infinity;
  2406. this.max.x = this.max.y = this.max.z = - Infinity;
  2407. return this;
  2408. },
  2409. empty: function () {
  2410. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2411. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2412. },
  2413. center: function ( optionalTarget ) {
  2414. var result = optionalTarget || new THREE.Vector3();
  2415. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2416. },
  2417. size: function ( optionalTarget ) {
  2418. var result = optionalTarget || new THREE.Vector3();
  2419. return result.subVectors( this.max, this.min );
  2420. },
  2421. expandByPoint: function ( point ) {
  2422. this.min.min( point );
  2423. this.max.max( point );
  2424. return this;
  2425. },
  2426. expandByVector: function ( vector ) {
  2427. this.min.sub( vector );
  2428. this.max.add( vector );
  2429. return this;
  2430. },
  2431. expandByScalar: function ( scalar ) {
  2432. this.min.addScalar( - scalar );
  2433. this.max.addScalar( scalar );
  2434. return this;
  2435. },
  2436. containsPoint: function ( point ) {
  2437. if ( point.x < this.min.x || point.x > this.max.x ||
  2438. point.y < this.min.y || point.y > this.max.y ||
  2439. point.z < this.min.z || point.z > this.max.z ) {
  2440. return false;
  2441. }
  2442. return true;
  2443. },
  2444. containsBox: function ( box ) {
  2445. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2446. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2447. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2448. return true;
  2449. }
  2450. return false;
  2451. },
  2452. getParameter: function ( point, optionalTarget ) {
  2453. // This can potentially have a divide by zero if the box
  2454. // has a size dimension of 0.
  2455. var result = optionalTarget || new THREE.Vector3();
  2456. return result.set(
  2457. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2458. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2459. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2460. );
  2461. },
  2462. intersectsBox: function ( box ) {
  2463. // using 6 splitting planes to rule out intersections.
  2464. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2465. box.max.y < this.min.y || box.min.y > this.max.y ||
  2466. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2467. return false;
  2468. }
  2469. return true;
  2470. },
  2471. intersectsSphere: ( function () {
  2472. var closestPoint;
  2473. return function intersectsSphere( sphere ) {
  2474. if ( closestPoint === undefined ) closestPoint = new THREE.Vector3();
  2475. // Find the point on the AABB closest to the sphere center.
  2476. this.clampPoint( sphere.center, closestPoint );
  2477. // If that point is inside the sphere, the AABB and sphere intersect.
  2478. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2479. };
  2480. } )(),
  2481. intersectsPlane: function ( plane ) {
  2482. // We compute the minimum and maximum dot product values. If those values
  2483. // are on the same side (back or front) of the plane, then there is no intersection.
  2484. var min, max;
  2485. if( plane.normal.x > 0 ) {
  2486. min = plane.normal.x * this.min.x;
  2487. max = plane.normal.x * this.max.x;
  2488. } else {
  2489. min = plane.normal.x * this.max.x;
  2490. max = plane.normal.x * this.min.x;
  2491. }
  2492. if( plane.normal.y > 0 ) {
  2493. min += plane.normal.y * this.min.y;
  2494. max += plane.normal.y * this.max.y;
  2495. } else {
  2496. min += plane.normal.y * this.max.y;
  2497. max += plane.normal.y * this.min.y;
  2498. }
  2499. if( plane.normal.z > 0 ) {
  2500. min += plane.normal.z * this.min.z;
  2501. max += plane.normal.z * this.max.z;
  2502. } else {
  2503. min += plane.normal.z * this.max.z;
  2504. max += plane.normal.z * this.min.z;
  2505. }
  2506. return ( min <= plane.constant && max >= plane.constant );
  2507. },
  2508. clampPoint: function ( point, optionalTarget ) {
  2509. var result = optionalTarget || new THREE.Vector3();
  2510. return result.copy( point ).clamp( this.min, this.max );
  2511. },
  2512. distanceToPoint: function () {
  2513. var v1 = new THREE.Vector3();
  2514. return function ( point ) {
  2515. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2516. return clampedPoint.sub( point ).length();
  2517. };
  2518. }(),
  2519. getBoundingSphere: function () {
  2520. var v1 = new THREE.Vector3();
  2521. return function ( optionalTarget ) {
  2522. var result = optionalTarget || new THREE.Sphere();
  2523. result.center = this.center();
  2524. result.radius = this.size( v1 ).length() * 0.5;
  2525. return result;
  2526. };
  2527. }(),
  2528. intersect: function ( box ) {
  2529. this.min.max( box.min );
  2530. this.max.min( box.max );
  2531. return this;
  2532. },
  2533. union: function ( box ) {
  2534. this.min.min( box.min );
  2535. this.max.max( box.max );
  2536. return this;
  2537. },
  2538. applyMatrix4: function () {
  2539. var points = [
  2540. new THREE.Vector3(),
  2541. new THREE.Vector3(),
  2542. new THREE.Vector3(),
  2543. new THREE.Vector3(),
  2544. new THREE.Vector3(),
  2545. new THREE.Vector3(),
  2546. new THREE.Vector3(),
  2547. new THREE.Vector3()
  2548. ];
  2549. return function ( matrix ) {
  2550. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2551. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2552. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2553. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2554. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2555. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2556. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2557. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2558. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2559. this.makeEmpty();
  2560. this.setFromPoints( points );
  2561. return this;
  2562. };
  2563. }(),
  2564. translate: function ( offset ) {
  2565. this.min.add( offset );
  2566. this.max.add( offset );
  2567. return this;
  2568. },
  2569. equals: function ( box ) {
  2570. return box.min.equals( this.min ) && box.max.equals( this.max );
  2571. }
  2572. };
  2573. // File:src/math/Matrix3.js
  2574. /**
  2575. * @author alteredq / http://alteredqualia.com/
  2576. * @author WestLangley / http://github.com/WestLangley
  2577. * @author bhouston / http://clara.io
  2578. */
  2579. THREE.Matrix3 = function () {
  2580. this.elements = new Float32Array( [
  2581. 1, 0, 0,
  2582. 0, 1, 0,
  2583. 0, 0, 1
  2584. ] );
  2585. if ( arguments.length > 0 ) {
  2586. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  2587. }
  2588. };
  2589. THREE.Matrix3.prototype = {
  2590. constructor: THREE.Matrix3,
  2591. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2592. var te = this.elements;
  2593. te[ 0 ] = n11; te[ 3 ] = n12; te[ 6 ] = n13;
  2594. te[ 1 ] = n21; te[ 4 ] = n22; te[ 7 ] = n23;
  2595. te[ 2 ] = n31; te[ 5 ] = n32; te[ 8 ] = n33;
  2596. return this;
  2597. },
  2598. identity: function () {
  2599. this.set(
  2600. 1, 0, 0,
  2601. 0, 1, 0,
  2602. 0, 0, 1
  2603. );
  2604. return this;
  2605. },
  2606. clone: function () {
  2607. return new this.constructor().fromArray( this.elements );
  2608. },
  2609. copy: function ( m ) {
  2610. var me = m.elements;
  2611. this.set(
  2612. me[ 0 ], me[ 3 ], me[ 6 ],
  2613. me[ 1 ], me[ 4 ], me[ 7 ],
  2614. me[ 2 ], me[ 5 ], me[ 8 ]
  2615. );
  2616. return this;
  2617. },
  2618. applyToVector3Array: function () {
  2619. var v1;
  2620. return function ( array, offset, length ) {
  2621. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2622. if ( offset === undefined ) offset = 0;
  2623. if ( length === undefined ) length = array.length;
  2624. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  2625. v1.fromArray( array, j );
  2626. v1.applyMatrix3( this );
  2627. v1.toArray( array, j );
  2628. }
  2629. return array;
  2630. };
  2631. }(),
  2632. applyToBuffer: function () {
  2633. var v1;
  2634. return function applyToBuffer( buffer, offset, length ) {
  2635. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2636. if ( offset === undefined ) offset = 0;
  2637. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  2638. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  2639. v1.x = buffer.getX( j );
  2640. v1.y = buffer.getY( j );
  2641. v1.z = buffer.getZ( j );
  2642. v1.applyMatrix3( this );
  2643. buffer.setXYZ( v1.x, v1.y, v1.z );
  2644. }
  2645. return buffer;
  2646. };
  2647. }(),
  2648. multiplyScalar: function ( s ) {
  2649. var te = this.elements;
  2650. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  2651. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  2652. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  2653. return this;
  2654. },
  2655. determinant: function () {
  2656. var te = this.elements;
  2657. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  2658. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  2659. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  2660. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  2661. },
  2662. getInverse: function ( matrix, throwOnInvertible ) {
  2663. // input: THREE.Matrix4
  2664. // ( based on http://code.google.com/p/webgl-mjs/ )
  2665. var me = matrix.elements;
  2666. var te = this.elements;
  2667. te[ 0 ] = me[ 10 ] * me[ 5 ] - me[ 6 ] * me[ 9 ];
  2668. te[ 1 ] = - me[ 10 ] * me[ 1 ] + me[ 2 ] * me[ 9 ];
  2669. te[ 2 ] = me[ 6 ] * me[ 1 ] - me[ 2 ] * me[ 5 ];
  2670. te[ 3 ] = - me[ 10 ] * me[ 4 ] + me[ 6 ] * me[ 8 ];
  2671. te[ 4 ] = me[ 10 ] * me[ 0 ] - me[ 2 ] * me[ 8 ];
  2672. te[ 5 ] = - me[ 6 ] * me[ 0 ] + me[ 2 ] * me[ 4 ];
  2673. te[ 6 ] = me[ 9 ] * me[ 4 ] - me[ 5 ] * me[ 8 ];
  2674. te[ 7 ] = - me[ 9 ] * me[ 0 ] + me[ 1 ] * me[ 8 ];
  2675. te[ 8 ] = me[ 5 ] * me[ 0 ] - me[ 1 ] * me[ 4 ];
  2676. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2677. // no inverse
  2678. if ( det === 0 ) {
  2679. var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2680. if ( throwOnInvertible || false ) {
  2681. throw new Error( msg );
  2682. } else {
  2683. console.warn( msg );
  2684. }
  2685. this.identity();
  2686. return this;
  2687. }
  2688. this.multiplyScalar( 1.0 / det );
  2689. return this;
  2690. },
  2691. transpose: function () {
  2692. var tmp, m = this.elements;
  2693. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  2694. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  2695. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  2696. return this;
  2697. },
  2698. flattenToArrayOffset: function ( array, offset ) {
  2699. var te = this.elements;
  2700. array[ offset ] = te[ 0 ];
  2701. array[ offset + 1 ] = te[ 1 ];
  2702. array[ offset + 2 ] = te[ 2 ];
  2703. array[ offset + 3 ] = te[ 3 ];
  2704. array[ offset + 4 ] = te[ 4 ];
  2705. array[ offset + 5 ] = te[ 5 ];
  2706. array[ offset + 6 ] = te[ 6 ];
  2707. array[ offset + 7 ] = te[ 7 ];
  2708. array[ offset + 8 ] = te[ 8 ];
  2709. return array;
  2710. },
  2711. getNormalMatrix: function ( m ) {
  2712. // input: THREE.Matrix4
  2713. this.getInverse( m ).transpose();
  2714. return this;
  2715. },
  2716. transposeIntoArray: function ( r ) {
  2717. var m = this.elements;
  2718. r[ 0 ] = m[ 0 ];
  2719. r[ 1 ] = m[ 3 ];
  2720. r[ 2 ] = m[ 6 ];
  2721. r[ 3 ] = m[ 1 ];
  2722. r[ 4 ] = m[ 4 ];
  2723. r[ 5 ] = m[ 7 ];
  2724. r[ 6 ] = m[ 2 ];
  2725. r[ 7 ] = m[ 5 ];
  2726. r[ 8 ] = m[ 8 ];
  2727. return this;
  2728. },
  2729. fromArray: function ( array ) {
  2730. this.elements.set( array );
  2731. return this;
  2732. },
  2733. toArray: function () {
  2734. var te = this.elements;
  2735. return [
  2736. te[ 0 ], te[ 1 ], te[ 2 ],
  2737. te[ 3 ], te[ 4 ], te[ 5 ],
  2738. te[ 6 ], te[ 7 ], te[ 8 ]
  2739. ];
  2740. }
  2741. };
  2742. // File:src/math/Matrix4.js
  2743. /**
  2744. * @author mrdoob / http://mrdoob.com/
  2745. * @author supereggbert / http://www.paulbrunt.co.uk/
  2746. * @author philogb / http://blog.thejit.org/
  2747. * @author jordi_ros / http://plattsoft.com
  2748. * @author D1plo1d / http://github.com/D1plo1d
  2749. * @author alteredq / http://alteredqualia.com/
  2750. * @author mikael emtinger / http://gomo.se/
  2751. * @author timknip / http://www.floorplanner.com/
  2752. * @author bhouston / http://clara.io
  2753. * @author WestLangley / http://github.com/WestLangley
  2754. */
  2755. THREE.Matrix4 = function () {
  2756. this.elements = new Float32Array( [
  2757. 1, 0, 0, 0,
  2758. 0, 1, 0, 0,
  2759. 0, 0, 1, 0,
  2760. 0, 0, 0, 1
  2761. ] );
  2762. if ( arguments.length > 0 ) {
  2763. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  2764. }
  2765. };
  2766. THREE.Matrix4.prototype = {
  2767. constructor: THREE.Matrix4,
  2768. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2769. var te = this.elements;
  2770. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  2771. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  2772. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  2773. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  2774. return this;
  2775. },
  2776. identity: function () {
  2777. this.set(
  2778. 1, 0, 0, 0,
  2779. 0, 1, 0, 0,
  2780. 0, 0, 1, 0,
  2781. 0, 0, 0, 1
  2782. );
  2783. return this;
  2784. },
  2785. clone: function () {
  2786. return new THREE.Matrix4().fromArray( this.elements );
  2787. },
  2788. copy: function ( m ) {
  2789. this.elements.set( m.elements );
  2790. return this;
  2791. },
  2792. copyPosition: function ( m ) {
  2793. var te = this.elements;
  2794. var me = m.elements;
  2795. te[ 12 ] = me[ 12 ];
  2796. te[ 13 ] = me[ 13 ];
  2797. te[ 14 ] = me[ 14 ];
  2798. return this;
  2799. },
  2800. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2801. var te = this.elements;
  2802. xAxis.set( te[ 0 ], te[ 1 ], te[ 2 ] );
  2803. yAxis.set( te[ 4 ], te[ 5 ], te[ 6 ] );
  2804. zAxis.set( te[ 8 ], te[ 9 ], te[ 10 ] );
  2805. return this;
  2806. },
  2807. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2808. this.set(
  2809. xAxis.x, yAxis.x, zAxis.x, 0,
  2810. xAxis.y, yAxis.y, zAxis.y, 0,
  2811. xAxis.z, yAxis.z, zAxis.z, 0,
  2812. 0, 0, 0, 1
  2813. );
  2814. return this;
  2815. },
  2816. extractRotation: function () {
  2817. var v1;
  2818. return function ( m ) {
  2819. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2820. var te = this.elements;
  2821. var me = m.elements;
  2822. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  2823. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  2824. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  2825. te[ 0 ] = me[ 0 ] * scaleX;
  2826. te[ 1 ] = me[ 1 ] * scaleX;
  2827. te[ 2 ] = me[ 2 ] * scaleX;
  2828. te[ 4 ] = me[ 4 ] * scaleY;
  2829. te[ 5 ] = me[ 5 ] * scaleY;
  2830. te[ 6 ] = me[ 6 ] * scaleY;
  2831. te[ 8 ] = me[ 8 ] * scaleZ;
  2832. te[ 9 ] = me[ 9 ] * scaleZ;
  2833. te[ 10 ] = me[ 10 ] * scaleZ;
  2834. return this;
  2835. };
  2836. }(),
  2837. makeRotationFromEuler: function ( euler ) {
  2838. if ( euler instanceof THREE.Euler === false ) {
  2839. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2840. }
  2841. var te = this.elements;
  2842. var x = euler.x, y = euler.y, z = euler.z;
  2843. var a = Math.cos( x ), b = Math.sin( x );
  2844. var c = Math.cos( y ), d = Math.sin( y );
  2845. var e = Math.cos( z ), f = Math.sin( z );
  2846. if ( euler.order === 'XYZ' ) {
  2847. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2848. te[ 0 ] = c * e;
  2849. te[ 4 ] = - c * f;
  2850. te[ 8 ] = d;
  2851. te[ 1 ] = af + be * d;
  2852. te[ 5 ] = ae - bf * d;
  2853. te[ 9 ] = - b * c;
  2854. te[ 2 ] = bf - ae * d;
  2855. te[ 6 ] = be + af * d;
  2856. te[ 10 ] = a * c;
  2857. } else if ( euler.order === 'YXZ' ) {
  2858. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2859. te[ 0 ] = ce + df * b;
  2860. te[ 4 ] = de * b - cf;
  2861. te[ 8 ] = a * d;
  2862. te[ 1 ] = a * f;
  2863. te[ 5 ] = a * e;
  2864. te[ 9 ] = - b;
  2865. te[ 2 ] = cf * b - de;
  2866. te[ 6 ] = df + ce * b;
  2867. te[ 10 ] = a * c;
  2868. } else if ( euler.order === 'ZXY' ) {
  2869. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2870. te[ 0 ] = ce - df * b;
  2871. te[ 4 ] = - a * f;
  2872. te[ 8 ] = de + cf * b;
  2873. te[ 1 ] = cf + de * b;
  2874. te[ 5 ] = a * e;
  2875. te[ 9 ] = df - ce * b;
  2876. te[ 2 ] = - a * d;
  2877. te[ 6 ] = b;
  2878. te[ 10 ] = a * c;
  2879. } else if ( euler.order === 'ZYX' ) {
  2880. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2881. te[ 0 ] = c * e;
  2882. te[ 4 ] = be * d - af;
  2883. te[ 8 ] = ae * d + bf;
  2884. te[ 1 ] = c * f;
  2885. te[ 5 ] = bf * d + ae;
  2886. te[ 9 ] = af * d - be;
  2887. te[ 2 ] = - d;
  2888. te[ 6 ] = b * c;
  2889. te[ 10 ] = a * c;
  2890. } else if ( euler.order === 'YZX' ) {
  2891. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2892. te[ 0 ] = c * e;
  2893. te[ 4 ] = bd - ac * f;
  2894. te[ 8 ] = bc * f + ad;
  2895. te[ 1 ] = f;
  2896. te[ 5 ] = a * e;
  2897. te[ 9 ] = - b * e;
  2898. te[ 2 ] = - d * e;
  2899. te[ 6 ] = ad * f + bc;
  2900. te[ 10 ] = ac - bd * f;
  2901. } else if ( euler.order === 'XZY' ) {
  2902. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2903. te[ 0 ] = c * e;
  2904. te[ 4 ] = - f;
  2905. te[ 8 ] = d * e;
  2906. te[ 1 ] = ac * f + bd;
  2907. te[ 5 ] = a * e;
  2908. te[ 9 ] = ad * f - bc;
  2909. te[ 2 ] = bc * f - ad;
  2910. te[ 6 ] = b * e;
  2911. te[ 10 ] = bd * f + ac;
  2912. }
  2913. // last column
  2914. te[ 3 ] = 0;
  2915. te[ 7 ] = 0;
  2916. te[ 11 ] = 0;
  2917. // bottom row
  2918. te[ 12 ] = 0;
  2919. te[ 13 ] = 0;
  2920. te[ 14 ] = 0;
  2921. te[ 15 ] = 1;
  2922. return this;
  2923. },
  2924. makeRotationFromQuaternion: function ( q ) {
  2925. var te = this.elements;
  2926. var x = q.x, y = q.y, z = q.z, w = q.w;
  2927. var x2 = x + x, y2 = y + y, z2 = z + z;
  2928. var xx = x * x2, xy = x * y2, xz = x * z2;
  2929. var yy = y * y2, yz = y * z2, zz = z * z2;
  2930. var wx = w * x2, wy = w * y2, wz = w * z2;
  2931. te[ 0 ] = 1 - ( yy + zz );
  2932. te[ 4 ] = xy - wz;
  2933. te[ 8 ] = xz + wy;
  2934. te[ 1 ] = xy + wz;
  2935. te[ 5 ] = 1 - ( xx + zz );
  2936. te[ 9 ] = yz - wx;
  2937. te[ 2 ] = xz - wy;
  2938. te[ 6 ] = yz + wx;
  2939. te[ 10 ] = 1 - ( xx + yy );
  2940. // last column
  2941. te[ 3 ] = 0;
  2942. te[ 7 ] = 0;
  2943. te[ 11 ] = 0;
  2944. // bottom row
  2945. te[ 12 ] = 0;
  2946. te[ 13 ] = 0;
  2947. te[ 14 ] = 0;
  2948. te[ 15 ] = 1;
  2949. return this;
  2950. },
  2951. lookAt: function () {
  2952. var x, y, z;
  2953. return function ( eye, target, up ) {
  2954. if ( x === undefined ) x = new THREE.Vector3();
  2955. if ( y === undefined ) y = new THREE.Vector3();
  2956. if ( z === undefined ) z = new THREE.Vector3();
  2957. var te = this.elements;
  2958. z.subVectors( eye, target ).normalize();
  2959. if ( z.lengthSq() === 0 ) {
  2960. z.z = 1;
  2961. }
  2962. x.crossVectors( up, z ).normalize();
  2963. if ( x.lengthSq() === 0 ) {
  2964. z.x += 0.0001;
  2965. x.crossVectors( up, z ).normalize();
  2966. }
  2967. y.crossVectors( z, x );
  2968. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2969. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2970. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2971. return this;
  2972. };
  2973. }(),
  2974. multiply: function ( m, n ) {
  2975. if ( n !== undefined ) {
  2976. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2977. return this.multiplyMatrices( m, n );
  2978. }
  2979. return this.multiplyMatrices( this, m );
  2980. },
  2981. multiplyMatrices: function ( a, b ) {
  2982. var ae = a.elements;
  2983. var be = b.elements;
  2984. var te = this.elements;
  2985. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  2986. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  2987. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  2988. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  2989. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  2990. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  2991. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  2992. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  2993. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2994. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2995. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2996. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2997. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2998. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2999. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3000. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3001. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3002. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3003. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3004. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3005. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3006. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3007. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3008. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3009. return this;
  3010. },
  3011. multiplyToArray: function ( a, b, r ) {
  3012. var te = this.elements;
  3013. this.multiplyMatrices( a, b );
  3014. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  3015. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  3016. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  3017. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  3018. return this;
  3019. },
  3020. multiplyScalar: function ( s ) {
  3021. var te = this.elements;
  3022. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3023. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3024. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3025. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3026. return this;
  3027. },
  3028. applyToVector3Array: function () {
  3029. var v1;
  3030. return function ( array, offset, length ) {
  3031. if ( v1 === undefined ) v1 = new THREE.Vector3();
  3032. if ( offset === undefined ) offset = 0;
  3033. if ( length === undefined ) length = array.length;
  3034. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  3035. v1.fromArray( array, j );
  3036. v1.applyMatrix4( this );
  3037. v1.toArray( array, j );
  3038. }
  3039. return array;
  3040. };
  3041. }(),
  3042. applyToBuffer: function () {
  3043. var v1;
  3044. return function applyToBuffer( buffer, offset, length ) {
  3045. if ( v1 === undefined ) v1 = new THREE.Vector3();
  3046. if ( offset === undefined ) offset = 0;
  3047. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  3048. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  3049. v1.x = buffer.getX( j );
  3050. v1.y = buffer.getY( j );
  3051. v1.z = buffer.getZ( j );
  3052. v1.applyMatrix4( this );
  3053. buffer.setXYZ( v1.x, v1.y, v1.z );
  3054. }
  3055. return buffer;
  3056. };
  3057. }(),
  3058. determinant: function () {
  3059. var te = this.elements;
  3060. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3061. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3062. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3063. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3064. //TODO: make this more efficient
  3065. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3066. return (
  3067. n41 * (
  3068. + n14 * n23 * n32
  3069. - n13 * n24 * n32
  3070. - n14 * n22 * n33
  3071. + n12 * n24 * n33
  3072. + n13 * n22 * n34
  3073. - n12 * n23 * n34
  3074. ) +
  3075. n42 * (
  3076. + n11 * n23 * n34
  3077. - n11 * n24 * n33
  3078. + n14 * n21 * n33
  3079. - n13 * n21 * n34
  3080. + n13 * n24 * n31
  3081. - n14 * n23 * n31
  3082. ) +
  3083. n43 * (
  3084. + n11 * n24 * n32
  3085. - n11 * n22 * n34
  3086. - n14 * n21 * n32
  3087. + n12 * n21 * n34
  3088. + n14 * n22 * n31
  3089. - n12 * n24 * n31
  3090. ) +
  3091. n44 * (
  3092. - n13 * n22 * n31
  3093. - n11 * n23 * n32
  3094. + n11 * n22 * n33
  3095. + n13 * n21 * n32
  3096. - n12 * n21 * n33
  3097. + n12 * n23 * n31
  3098. )
  3099. );
  3100. },
  3101. transpose: function () {
  3102. var te = this.elements;
  3103. var tmp;
  3104. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3105. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3106. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3107. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3108. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3109. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3110. return this;
  3111. },
  3112. flattenToArrayOffset: function ( array, offset ) {
  3113. var te = this.elements;
  3114. array[ offset ] = te[ 0 ];
  3115. array[ offset + 1 ] = te[ 1 ];
  3116. array[ offset + 2 ] = te[ 2 ];
  3117. array[ offset + 3 ] = te[ 3 ];
  3118. array[ offset + 4 ] = te[ 4 ];
  3119. array[ offset + 5 ] = te[ 5 ];
  3120. array[ offset + 6 ] = te[ 6 ];
  3121. array[ offset + 7 ] = te[ 7 ];
  3122. array[ offset + 8 ] = te[ 8 ];
  3123. array[ offset + 9 ] = te[ 9 ];
  3124. array[ offset + 10 ] = te[ 10 ];
  3125. array[ offset + 11 ] = te[ 11 ];
  3126. array[ offset + 12 ] = te[ 12 ];
  3127. array[ offset + 13 ] = te[ 13 ];
  3128. array[ offset + 14 ] = te[ 14 ];
  3129. array[ offset + 15 ] = te[ 15 ];
  3130. return array;
  3131. },
  3132. getPosition: function () {
  3133. var v1;
  3134. return function () {
  3135. if ( v1 === undefined ) v1 = new THREE.Vector3();
  3136. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  3137. var te = this.elements;
  3138. return v1.set( te[ 12 ], te[ 13 ], te[ 14 ] );
  3139. };
  3140. }(),
  3141. setPosition: function ( v ) {
  3142. var te = this.elements;
  3143. te[ 12 ] = v.x;
  3144. te[ 13 ] = v.y;
  3145. te[ 14 ] = v.z;
  3146. return this;
  3147. },
  3148. getInverse: function ( m, throwOnInvertible ) {
  3149. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3150. var te = this.elements;
  3151. var me = m.elements;
  3152. var n11 = me[ 0 ], n12 = me[ 4 ], n13 = me[ 8 ], n14 = me[ 12 ];
  3153. var n21 = me[ 1 ], n22 = me[ 5 ], n23 = me[ 9 ], n24 = me[ 13 ];
  3154. var n31 = me[ 2 ], n32 = me[ 6 ], n33 = me[ 10 ], n34 = me[ 14 ];
  3155. var n41 = me[ 3 ], n42 = me[ 7 ], n43 = me[ 11 ], n44 = me[ 15 ];
  3156. te[ 0 ] = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44;
  3157. te[ 4 ] = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44;
  3158. te[ 8 ] = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44;
  3159. te[ 12 ] = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3160. te[ 1 ] = n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44;
  3161. te[ 5 ] = n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44;
  3162. te[ 9 ] = n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44;
  3163. te[ 13 ] = n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34;
  3164. te[ 2 ] = n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44;
  3165. te[ 6 ] = n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44;
  3166. te[ 10 ] = n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44;
  3167. te[ 14 ] = n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34;
  3168. te[ 3 ] = n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43;
  3169. te[ 7 ] = n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43;
  3170. te[ 11 ] = n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43;
  3171. te[ 15 ] = n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33;
  3172. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  3173. if ( det === 0 ) {
  3174. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  3175. if ( throwOnInvertible || false ) {
  3176. throw new Error( msg );
  3177. } else {
  3178. console.warn( msg );
  3179. }
  3180. this.identity();
  3181. return this;
  3182. }
  3183. this.multiplyScalar( 1 / det );
  3184. return this;
  3185. },
  3186. scale: function ( v ) {
  3187. var te = this.elements;
  3188. var x = v.x, y = v.y, z = v.z;
  3189. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3190. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3191. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3192. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3193. return this;
  3194. },
  3195. getMaxScaleOnAxis: function () {
  3196. var te = this.elements;
  3197. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3198. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3199. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3200. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3201. },
  3202. makeTranslation: function ( x, y, z ) {
  3203. this.set(
  3204. 1, 0, 0, x,
  3205. 0, 1, 0, y,
  3206. 0, 0, 1, z,
  3207. 0, 0, 0, 1
  3208. );
  3209. return this;
  3210. },
  3211. makeRotationX: function ( theta ) {
  3212. var c = Math.cos( theta ), s = Math.sin( theta );
  3213. this.set(
  3214. 1, 0, 0, 0,
  3215. 0, c, - s, 0,
  3216. 0, s, c, 0,
  3217. 0, 0, 0, 1
  3218. );
  3219. return this;
  3220. },
  3221. makeRotationY: function ( theta ) {
  3222. var c = Math.cos( theta ), s = Math.sin( theta );
  3223. this.set(
  3224. c, 0, s, 0,
  3225. 0, 1, 0, 0,
  3226. - s, 0, c, 0,
  3227. 0, 0, 0, 1
  3228. );
  3229. return this;
  3230. },
  3231. makeRotationZ: function ( theta ) {
  3232. var c = Math.cos( theta ), s = Math.sin( theta );
  3233. this.set(
  3234. c, - s, 0, 0,
  3235. s, c, 0, 0,
  3236. 0, 0, 1, 0,
  3237. 0, 0, 0, 1
  3238. );
  3239. return this;
  3240. },
  3241. makeRotationAxis: function ( axis, angle ) {
  3242. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3243. var c = Math.cos( angle );
  3244. var s = Math.sin( angle );
  3245. var t = 1 - c;
  3246. var x = axis.x, y = axis.y, z = axis.z;
  3247. var tx = t * x, ty = t * y;
  3248. this.set(
  3249. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3250. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3251. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3252. 0, 0, 0, 1
  3253. );
  3254. return this;
  3255. },
  3256. makeScale: function ( x, y, z ) {
  3257. this.set(
  3258. x, 0, 0, 0,
  3259. 0, y, 0, 0,
  3260. 0, 0, z, 0,
  3261. 0, 0, 0, 1
  3262. );
  3263. return this;
  3264. },
  3265. compose: function ( position, quaternion, scale ) {
  3266. this.makeRotationFromQuaternion( quaternion );
  3267. this.scale( scale );
  3268. this.setPosition( position );
  3269. return this;
  3270. },
  3271. decompose: function () {
  3272. var vector, matrix;
  3273. return function ( position, quaternion, scale ) {
  3274. if ( vector === undefined ) vector = new THREE.Vector3();
  3275. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  3276. var te = this.elements;
  3277. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3278. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3279. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3280. // if determine is negative, we need to invert one scale
  3281. var det = this.determinant();
  3282. if ( det < 0 ) {
  3283. sx = - sx;
  3284. }
  3285. position.x = te[ 12 ];
  3286. position.y = te[ 13 ];
  3287. position.z = te[ 14 ];
  3288. // scale the rotation part
  3289. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  3290. var invSX = 1 / sx;
  3291. var invSY = 1 / sy;
  3292. var invSZ = 1 / sz;
  3293. matrix.elements[ 0 ] *= invSX;
  3294. matrix.elements[ 1 ] *= invSX;
  3295. matrix.elements[ 2 ] *= invSX;
  3296. matrix.elements[ 4 ] *= invSY;
  3297. matrix.elements[ 5 ] *= invSY;
  3298. matrix.elements[ 6 ] *= invSY;
  3299. matrix.elements[ 8 ] *= invSZ;
  3300. matrix.elements[ 9 ] *= invSZ;
  3301. matrix.elements[ 10 ] *= invSZ;
  3302. quaternion.setFromRotationMatrix( matrix );
  3303. scale.x = sx;
  3304. scale.y = sy;
  3305. scale.z = sz;
  3306. return this;
  3307. };
  3308. }(),
  3309. makeFrustum: function ( left, right, bottom, top, near, far ) {
  3310. var te = this.elements;
  3311. var x = 2 * near / ( right - left );
  3312. var y = 2 * near / ( top - bottom );
  3313. var a = ( right + left ) / ( right - left );
  3314. var b = ( top + bottom ) / ( top - bottom );
  3315. var c = - ( far + near ) / ( far - near );
  3316. var d = - 2 * far * near / ( far - near );
  3317. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3318. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3319. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3320. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3321. return this;
  3322. },
  3323. makePerspective: function ( fov, aspect, near, far ) {
  3324. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  3325. var ymin = - ymax;
  3326. var xmin = ymin * aspect;
  3327. var xmax = ymax * aspect;
  3328. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  3329. },
  3330. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  3331. var te = this.elements;
  3332. var w = right - left;
  3333. var h = top - bottom;
  3334. var p = far - near;
  3335. var x = ( right + left ) / w;
  3336. var y = ( top + bottom ) / h;
  3337. var z = ( far + near ) / p;
  3338. te[ 0 ] = 2 / w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3339. te[ 1 ] = 0; te[ 5 ] = 2 / h; te[ 9 ] = 0; te[ 13 ] = - y;
  3340. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 / p; te[ 14 ] = - z;
  3341. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3342. return this;
  3343. },
  3344. equals: function ( matrix ) {
  3345. var te = this.elements;
  3346. var me = matrix.elements;
  3347. for ( var i = 0; i < 16; i ++ ) {
  3348. if ( te[ i ] !== me[ i ] ) return false;
  3349. }
  3350. return true;
  3351. },
  3352. fromArray: function ( array ) {
  3353. this.elements.set( array );
  3354. return this;
  3355. },
  3356. toArray: function () {
  3357. var te = this.elements;
  3358. return [
  3359. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  3360. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  3361. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  3362. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  3363. ];
  3364. }
  3365. };
  3366. // File:src/math/Ray.js
  3367. /**
  3368. * @author bhouston / http://clara.io
  3369. */
  3370. THREE.Ray = function ( origin, direction ) {
  3371. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3372. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3373. };
  3374. THREE.Ray.prototype = {
  3375. constructor: THREE.Ray,
  3376. set: function ( origin, direction ) {
  3377. this.origin.copy( origin );
  3378. this.direction.copy( direction );
  3379. return this;
  3380. },
  3381. clone: function () {
  3382. return new this.constructor().copy( this );
  3383. },
  3384. copy: function ( ray ) {
  3385. this.origin.copy( ray.origin );
  3386. this.direction.copy( ray.direction );
  3387. return this;
  3388. },
  3389. at: function ( t, optionalTarget ) {
  3390. var result = optionalTarget || new THREE.Vector3();
  3391. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3392. },
  3393. recast: function () {
  3394. var v1 = new THREE.Vector3();
  3395. return function ( t ) {
  3396. this.origin.copy( this.at( t, v1 ) );
  3397. return this;
  3398. };
  3399. }(),
  3400. closestPointToPoint: function ( point, optionalTarget ) {
  3401. var result = optionalTarget || new THREE.Vector3();
  3402. result.subVectors( point, this.origin );
  3403. var directionDistance = result.dot( this.direction );
  3404. if ( directionDistance < 0 ) {
  3405. return result.copy( this.origin );
  3406. }
  3407. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3408. },
  3409. distanceToPoint: function ( point ) {
  3410. return Math.sqrt( this.distanceSqToPoint( point ) );
  3411. },
  3412. distanceSqToPoint: function () {
  3413. var v1 = new THREE.Vector3();
  3414. return function ( point ) {
  3415. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3416. // point behind the ray
  3417. if ( directionDistance < 0 ) {
  3418. return this.origin.distanceToSquared( point );
  3419. }
  3420. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3421. return v1.distanceToSquared( point );
  3422. };
  3423. }(),
  3424. distanceSqToSegment: function () {
  3425. var segCenter = new THREE.Vector3();
  3426. var segDir = new THREE.Vector3();
  3427. var diff = new THREE.Vector3();
  3428. return function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3429. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3430. // It returns the min distance between the ray and the segment
  3431. // defined by v0 and v1
  3432. // It can also set two optional targets :
  3433. // - The closest point on the ray
  3434. // - The closest point on the segment
  3435. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3436. segDir.copy( v1 ).sub( v0 ).normalize();
  3437. diff.copy( this.origin ).sub( segCenter );
  3438. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3439. var a01 = - this.direction.dot( segDir );
  3440. var b0 = diff.dot( this.direction );
  3441. var b1 = - diff.dot( segDir );
  3442. var c = diff.lengthSq();
  3443. var det = Math.abs( 1 - a01 * a01 );
  3444. var s0, s1, sqrDist, extDet;
  3445. if ( det > 0 ) {
  3446. // The ray and segment are not parallel.
  3447. s0 = a01 * b1 - b0;
  3448. s1 = a01 * b0 - b1;
  3449. extDet = segExtent * det;
  3450. if ( s0 >= 0 ) {
  3451. if ( s1 >= - extDet ) {
  3452. if ( s1 <= extDet ) {
  3453. // region 0
  3454. // Minimum at interior points of ray and segment.
  3455. var invDet = 1 / det;
  3456. s0 *= invDet;
  3457. s1 *= invDet;
  3458. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3459. } else {
  3460. // region 1
  3461. s1 = segExtent;
  3462. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3463. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3464. }
  3465. } else {
  3466. // region 5
  3467. s1 = - segExtent;
  3468. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3469. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3470. }
  3471. } else {
  3472. if ( s1 <= - extDet ) {
  3473. // region 4
  3474. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3475. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3476. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3477. } else if ( s1 <= extDet ) {
  3478. // region 3
  3479. s0 = 0;
  3480. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3481. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3482. } else {
  3483. // region 2
  3484. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3485. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3486. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3487. }
  3488. }
  3489. } else {
  3490. // Ray and segment are parallel.
  3491. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3492. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3493. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3494. }
  3495. if ( optionalPointOnRay ) {
  3496. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3497. }
  3498. if ( optionalPointOnSegment ) {
  3499. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  3500. }
  3501. return sqrDist;
  3502. };
  3503. }(),
  3504. intersectSphere: function () {
  3505. // from http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-sphere-intersection/
  3506. var v1 = new THREE.Vector3();
  3507. return function ( sphere, optionalTarget ) {
  3508. v1.subVectors( sphere.center, this.origin );
  3509. var tca = v1.dot( this.direction );
  3510. var d2 = v1.dot( v1 ) - tca * tca;
  3511. var radius2 = sphere.radius * sphere.radius;
  3512. if ( d2 > radius2 ) return null;
  3513. var thc = Math.sqrt( radius2 - d2 );
  3514. // t0 = first intersect point - entrance on front of sphere
  3515. var t0 = tca - thc;
  3516. // t1 = second intersect point - exit point on back of sphere
  3517. var t1 = tca + thc;
  3518. // test to see if both t0 and t1 are behind the ray - if so, return null
  3519. if ( t0 < 0 && t1 < 0 ) return null;
  3520. // test to see if t0 is behind the ray:
  3521. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3522. // in order to always return an intersect point that is in front of the ray.
  3523. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  3524. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3525. return this.at( t0, optionalTarget );
  3526. }
  3527. }(),
  3528. intersectsSphere: function ( sphere ) {
  3529. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3530. },
  3531. distanceToPlane: function ( plane ) {
  3532. var denominator = plane.normal.dot( this.direction );
  3533. if ( denominator === 0 ) {
  3534. // line is coplanar, return origin
  3535. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3536. return 0;
  3537. }
  3538. // Null is preferable to undefined since undefined means.... it is undefined
  3539. return null;
  3540. }
  3541. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3542. // Return if the ray never intersects the plane
  3543. return t >= 0 ? t : null;
  3544. },
  3545. intersectPlane: function ( plane, optionalTarget ) {
  3546. var t = this.distanceToPlane( plane );
  3547. if ( t === null ) {
  3548. return null;
  3549. }
  3550. return this.at( t, optionalTarget );
  3551. },
  3552. intersectsPlane: function ( plane ) {
  3553. // check if the ray lies on the plane first
  3554. var distToPoint = plane.distanceToPoint( this.origin );
  3555. if ( distToPoint === 0 ) {
  3556. return true;
  3557. }
  3558. var denominator = plane.normal.dot( this.direction );
  3559. if ( denominator * distToPoint < 0 ) {
  3560. return true;
  3561. }
  3562. // ray origin is behind the plane (and is pointing behind it)
  3563. return false;
  3564. },
  3565. intersectBox: function ( box, optionalTarget ) {
  3566. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3567. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  3568. var invdirx = 1 / this.direction.x,
  3569. invdiry = 1 / this.direction.y,
  3570. invdirz = 1 / this.direction.z;
  3571. var origin = this.origin;
  3572. if ( invdirx >= 0 ) {
  3573. tmin = ( box.min.x - origin.x ) * invdirx;
  3574. tmax = ( box.max.x - origin.x ) * invdirx;
  3575. } else {
  3576. tmin = ( box.max.x - origin.x ) * invdirx;
  3577. tmax = ( box.min.x - origin.x ) * invdirx;
  3578. }
  3579. if ( invdiry >= 0 ) {
  3580. tymin = ( box.min.y - origin.y ) * invdiry;
  3581. tymax = ( box.max.y - origin.y ) * invdiry;
  3582. } else {
  3583. tymin = ( box.max.y - origin.y ) * invdiry;
  3584. tymax = ( box.min.y - origin.y ) * invdiry;
  3585. }
  3586. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3587. // These lines also handle the case where tmin or tmax is NaN
  3588. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3589. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3590. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3591. if ( invdirz >= 0 ) {
  3592. tzmin = ( box.min.z - origin.z ) * invdirz;
  3593. tzmax = ( box.max.z - origin.z ) * invdirz;
  3594. } else {
  3595. tzmin = ( box.max.z - origin.z ) * invdirz;
  3596. tzmax = ( box.min.z - origin.z ) * invdirz;
  3597. }
  3598. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3599. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3600. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3601. //return point closest to the ray (positive side)
  3602. if ( tmax < 0 ) return null;
  3603. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3604. },
  3605. intersectsBox: ( function () {
  3606. var v = new THREE.Vector3();
  3607. return function ( box ) {
  3608. return this.intersectBox( box, v ) !== null;
  3609. };
  3610. } )(),
  3611. intersectTriangle: function () {
  3612. // Compute the offset origin, edges, and normal.
  3613. var diff = new THREE.Vector3();
  3614. var edge1 = new THREE.Vector3();
  3615. var edge2 = new THREE.Vector3();
  3616. var normal = new THREE.Vector3();
  3617. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3618. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3619. edge1.subVectors( b, a );
  3620. edge2.subVectors( c, a );
  3621. normal.crossVectors( edge1, edge2 );
  3622. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3623. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3624. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3625. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3626. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3627. var DdN = this.direction.dot( normal );
  3628. var sign;
  3629. if ( DdN > 0 ) {
  3630. if ( backfaceCulling ) return null;
  3631. sign = 1;
  3632. } else if ( DdN < 0 ) {
  3633. sign = - 1;
  3634. DdN = - DdN;
  3635. } else {
  3636. return null;
  3637. }
  3638. diff.subVectors( this.origin, a );
  3639. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3640. // b1 < 0, no intersection
  3641. if ( DdQxE2 < 0 ) {
  3642. return null;
  3643. }
  3644. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3645. // b2 < 0, no intersection
  3646. if ( DdE1xQ < 0 ) {
  3647. return null;
  3648. }
  3649. // b1+b2 > 1, no intersection
  3650. if ( DdQxE2 + DdE1xQ > DdN ) {
  3651. return null;
  3652. }
  3653. // Line intersects triangle, check if ray does.
  3654. var QdN = - sign * diff.dot( normal );
  3655. // t < 0, no intersection
  3656. if ( QdN < 0 ) {
  3657. return null;
  3658. }
  3659. // Ray intersects triangle.
  3660. return this.at( QdN / DdN, optionalTarget );
  3661. };
  3662. }(),
  3663. applyMatrix4: function ( matrix4 ) {
  3664. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3665. this.origin.applyMatrix4( matrix4 );
  3666. this.direction.sub( this.origin );
  3667. this.direction.normalize();
  3668. return this;
  3669. },
  3670. equals: function ( ray ) {
  3671. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3672. }
  3673. };
  3674. // File:src/math/Sphere.js
  3675. /**
  3676. * @author bhouston / http://clara.io
  3677. * @author mrdoob / http://mrdoob.com/
  3678. */
  3679. THREE.Sphere = function ( center, radius ) {
  3680. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3681. this.radius = ( radius !== undefined ) ? radius : 0;
  3682. };
  3683. THREE.Sphere.prototype = {
  3684. constructor: THREE.Sphere,
  3685. set: function ( center, radius ) {
  3686. this.center.copy( center );
  3687. this.radius = radius;
  3688. return this;
  3689. },
  3690. setFromPoints: function () {
  3691. var box = new THREE.Box3();
  3692. return function ( points, optionalCenter ) {
  3693. var center = this.center;
  3694. if ( optionalCenter !== undefined ) {
  3695. center.copy( optionalCenter );
  3696. } else {
  3697. box.setFromPoints( points ).center( center );
  3698. }
  3699. var maxRadiusSq = 0;
  3700. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3701. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3702. }
  3703. this.radius = Math.sqrt( maxRadiusSq );
  3704. return this;
  3705. };
  3706. }(),
  3707. clone: function () {
  3708. return new this.constructor().copy( this );
  3709. },
  3710. copy: function ( sphere ) {
  3711. this.center.copy( sphere.center );
  3712. this.radius = sphere.radius;
  3713. return this;
  3714. },
  3715. empty: function () {
  3716. return ( this.radius <= 0 );
  3717. },
  3718. containsPoint: function ( point ) {
  3719. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3720. },
  3721. distanceToPoint: function ( point ) {
  3722. return ( point.distanceTo( this.center ) - this.radius );
  3723. },
  3724. intersectsSphere: function ( sphere ) {
  3725. var radiusSum = this.radius + sphere.radius;
  3726. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3727. },
  3728. intersectsBox: function ( box ) {
  3729. return box.intersectsSphere( this );
  3730. },
  3731. intersectsPlane: function ( plane ) {
  3732. // We use the following equation to compute the signed distance from
  3733. // the center of the sphere to the plane.
  3734. //
  3735. // distance = q * n - d
  3736. //
  3737. // If this distance is greater than the radius of the sphere,
  3738. // then there is no intersection.
  3739. return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius;
  3740. },
  3741. clampPoint: function ( point, optionalTarget ) {
  3742. var deltaLengthSq = this.center.distanceToSquared( point );
  3743. var result = optionalTarget || new THREE.Vector3();
  3744. result.copy( point );
  3745. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3746. result.sub( this.center ).normalize();
  3747. result.multiplyScalar( this.radius ).add( this.center );
  3748. }
  3749. return result;
  3750. },
  3751. getBoundingBox: function ( optionalTarget ) {
  3752. var box = optionalTarget || new THREE.Box3();
  3753. box.set( this.center, this.center );
  3754. box.expandByScalar( this.radius );
  3755. return box;
  3756. },
  3757. applyMatrix4: function ( matrix ) {
  3758. this.center.applyMatrix4( matrix );
  3759. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3760. return this;
  3761. },
  3762. translate: function ( offset ) {
  3763. this.center.add( offset );
  3764. return this;
  3765. },
  3766. equals: function ( sphere ) {
  3767. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3768. }
  3769. };
  3770. // File:src/math/Frustum.js
  3771. /**
  3772. * @author mrdoob / http://mrdoob.com/
  3773. * @author alteredq / http://alteredqualia.com/
  3774. * @author bhouston / http://clara.io
  3775. */
  3776. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3777. this.planes = [
  3778. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3779. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3780. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3781. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3782. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3783. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3784. ];
  3785. };
  3786. THREE.Frustum.prototype = {
  3787. constructor: THREE.Frustum,
  3788. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3789. var planes = this.planes;
  3790. planes[ 0 ].copy( p0 );
  3791. planes[ 1 ].copy( p1 );
  3792. planes[ 2 ].copy( p2 );
  3793. planes[ 3 ].copy( p3 );
  3794. planes[ 4 ].copy( p4 );
  3795. planes[ 5 ].copy( p5 );
  3796. return this;
  3797. },
  3798. clone: function () {
  3799. return new this.constructor().copy( this );
  3800. },
  3801. copy: function ( frustum ) {
  3802. var planes = this.planes;
  3803. for ( var i = 0; i < 6; i ++ ) {
  3804. planes[ i ].copy( frustum.planes[ i ] );
  3805. }
  3806. return this;
  3807. },
  3808. setFromMatrix: function ( m ) {
  3809. var planes = this.planes;
  3810. var me = m.elements;
  3811. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  3812. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  3813. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  3814. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  3815. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3816. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3817. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3818. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3819. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3820. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3821. return this;
  3822. },
  3823. intersectsObject: function () {
  3824. var sphere = new THREE.Sphere();
  3825. return function ( object ) {
  3826. var geometry = object.geometry;
  3827. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3828. sphere.copy( geometry.boundingSphere );
  3829. sphere.applyMatrix4( object.matrixWorld );
  3830. return this.intersectsSphere( sphere );
  3831. };
  3832. }(),
  3833. intersectsSphere: function ( sphere ) {
  3834. var planes = this.planes;
  3835. var center = sphere.center;
  3836. var negRadius = - sphere.radius;
  3837. for ( var i = 0; i < 6; i ++ ) {
  3838. var distance = planes[ i ].distanceToPoint( center );
  3839. if ( distance < negRadius ) {
  3840. return false;
  3841. }
  3842. }
  3843. return true;
  3844. },
  3845. intersectsBox: function () {
  3846. var p1 = new THREE.Vector3(),
  3847. p2 = new THREE.Vector3();
  3848. return function ( box ) {
  3849. var planes = this.planes;
  3850. for ( var i = 0; i < 6 ; i ++ ) {
  3851. var plane = planes[ i ];
  3852. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3853. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3854. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3855. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3856. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3857. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3858. var d1 = plane.distanceToPoint( p1 );
  3859. var d2 = plane.distanceToPoint( p2 );
  3860. // if both outside plane, no intersection
  3861. if ( d1 < 0 && d2 < 0 ) {
  3862. return false;
  3863. }
  3864. }
  3865. return true;
  3866. };
  3867. }(),
  3868. containsPoint: function ( point ) {
  3869. var planes = this.planes;
  3870. for ( var i = 0; i < 6; i ++ ) {
  3871. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3872. return false;
  3873. }
  3874. }
  3875. return true;
  3876. }
  3877. };
  3878. // File:src/math/Plane.js
  3879. /**
  3880. * @author bhouston / http://clara.io
  3881. */
  3882. THREE.Plane = function ( normal, constant ) {
  3883. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3884. this.constant = ( constant !== undefined ) ? constant : 0;
  3885. };
  3886. THREE.Plane.prototype = {
  3887. constructor: THREE.Plane,
  3888. set: function ( normal, constant ) {
  3889. this.normal.copy( normal );
  3890. this.constant = constant;
  3891. return this;
  3892. },
  3893. setComponents: function ( x, y, z, w ) {
  3894. this.normal.set( x, y, z );
  3895. this.constant = w;
  3896. return this;
  3897. },
  3898. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3899. this.normal.copy( normal );
  3900. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3901. return this;
  3902. },
  3903. setFromCoplanarPoints: function () {
  3904. var v1 = new THREE.Vector3();
  3905. var v2 = new THREE.Vector3();
  3906. return function ( a, b, c ) {
  3907. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3908. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3909. this.setFromNormalAndCoplanarPoint( normal, a );
  3910. return this;
  3911. };
  3912. }(),
  3913. clone: function () {
  3914. return new this.constructor().copy( this );
  3915. },
  3916. copy: function ( plane ) {
  3917. this.normal.copy( plane.normal );
  3918. this.constant = plane.constant;
  3919. return this;
  3920. },
  3921. normalize: function () {
  3922. // Note: will lead to a divide by zero if the plane is invalid.
  3923. var inverseNormalLength = 1.0 / this.normal.length();
  3924. this.normal.multiplyScalar( inverseNormalLength );
  3925. this.constant *= inverseNormalLength;
  3926. return this;
  3927. },
  3928. negate: function () {
  3929. this.constant *= - 1;
  3930. this.normal.negate();
  3931. return this;
  3932. },
  3933. distanceToPoint: function ( point ) {
  3934. return this.normal.dot( point ) + this.constant;
  3935. },
  3936. distanceToSphere: function ( sphere ) {
  3937. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3938. },
  3939. projectPoint: function ( point, optionalTarget ) {
  3940. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3941. },
  3942. orthoPoint: function ( point, optionalTarget ) {
  3943. var perpendicularMagnitude = this.distanceToPoint( point );
  3944. var result = optionalTarget || new THREE.Vector3();
  3945. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3946. },
  3947. intersectLine: function () {
  3948. var v1 = new THREE.Vector3();
  3949. return function ( line, optionalTarget ) {
  3950. var result = optionalTarget || new THREE.Vector3();
  3951. var direction = line.delta( v1 );
  3952. var denominator = this.normal.dot( direction );
  3953. if ( denominator === 0 ) {
  3954. // line is coplanar, return origin
  3955. if ( this.distanceToPoint( line.start ) === 0 ) {
  3956. return result.copy( line.start );
  3957. }
  3958. // Unsure if this is the correct method to handle this case.
  3959. return undefined;
  3960. }
  3961. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3962. if ( t < 0 || t > 1 ) {
  3963. return undefined;
  3964. }
  3965. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3966. };
  3967. }(),
  3968. intersectsLine: function ( line ) {
  3969. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3970. var startSign = this.distanceToPoint( line.start );
  3971. var endSign = this.distanceToPoint( line.end );
  3972. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3973. },
  3974. intersectsBox: function ( box ) {
  3975. return box.intersectsPlane( this );
  3976. },
  3977. intersectsSphere: function ( sphere ) {
  3978. return sphere.intersectsPlane( this );
  3979. },
  3980. coplanarPoint: function ( optionalTarget ) {
  3981. var result = optionalTarget || new THREE.Vector3();
  3982. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3983. },
  3984. applyMatrix4: function () {
  3985. var v1 = new THREE.Vector3();
  3986. var v2 = new THREE.Vector3();
  3987. var m1 = new THREE.Matrix3();
  3988. return function ( matrix, optionalNormalMatrix ) {
  3989. // compute new normal based on theory here:
  3990. // http://www.songho.ca/opengl/gl_normaltransform.html
  3991. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3992. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3993. var newCoplanarPoint = this.coplanarPoint( v2 );
  3994. newCoplanarPoint.applyMatrix4( matrix );
  3995. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3996. return this;
  3997. };
  3998. }(),
  3999. translate: function ( offset ) {
  4000. this.constant = this.constant - offset.dot( this.normal );
  4001. return this;
  4002. },
  4003. equals: function ( plane ) {
  4004. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  4005. }
  4006. };
  4007. // File:src/math/Math.js
  4008. /**
  4009. * @author alteredq / http://alteredqualia.com/
  4010. * @author mrdoob / http://mrdoob.com/
  4011. */
  4012. THREE.Math = {
  4013. generateUUID: function () {
  4014. // http://www.broofa.com/Tools/Math.uuid.htm
  4015. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  4016. var uuid = new Array( 36 );
  4017. var rnd = 0, r;
  4018. return function () {
  4019. for ( var i = 0; i < 36; i ++ ) {
  4020. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  4021. uuid[ i ] = '-';
  4022. } else if ( i === 14 ) {
  4023. uuid[ i ] = '4';
  4024. } else {
  4025. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  4026. r = rnd & 0xf;
  4027. rnd = rnd >> 4;
  4028. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  4029. }
  4030. }
  4031. return uuid.join( '' );
  4032. };
  4033. }(),
  4034. clamp: function ( value, min, max ) {
  4035. return Math.max( min, Math.min( max, value ) );
  4036. },
  4037. // compute euclidian modulo of m % n
  4038. // https://en.wikipedia.org/wiki/Modulo_operation
  4039. euclideanModulo: function ( n, m ) {
  4040. return ( ( n % m ) + m ) % m;
  4041. },
  4042. // Linear mapping from range <a1, a2> to range <b1, b2>
  4043. mapLinear: function ( x, a1, a2, b1, b2 ) {
  4044. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  4045. },
  4046. // http://en.wikipedia.org/wiki/Smoothstep
  4047. smoothstep: function ( x, min, max ) {
  4048. if ( x <= min ) return 0;
  4049. if ( x >= max ) return 1;
  4050. x = ( x - min ) / ( max - min );
  4051. return x * x * ( 3 - 2 * x );
  4052. },
  4053. smootherstep: function ( x, min, max ) {
  4054. if ( x <= min ) return 0;
  4055. if ( x >= max ) return 1;
  4056. x = ( x - min ) / ( max - min );
  4057. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  4058. },
  4059. // Random float from <0, 1> with 16 bits of randomness
  4060. // (standard Math.random() creates repetitive patterns when applied over larger space)
  4061. random16: function () {
  4062. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  4063. },
  4064. // Random integer from <low, high> interval
  4065. randInt: function ( low, high ) {
  4066. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  4067. },
  4068. // Random float from <low, high> interval
  4069. randFloat: function ( low, high ) {
  4070. return low + Math.random() * ( high - low );
  4071. },
  4072. // Random float from <-range/2, range/2> interval
  4073. randFloatSpread: function ( range ) {
  4074. return range * ( 0.5 - Math.random() );
  4075. },
  4076. degToRad: function () {
  4077. var degreeToRadiansFactor = Math.PI / 180;
  4078. return function ( degrees ) {
  4079. return degrees * degreeToRadiansFactor;
  4080. };
  4081. }(),
  4082. radToDeg: function () {
  4083. var radianToDegreesFactor = 180 / Math.PI;
  4084. return function ( radians ) {
  4085. return radians * radianToDegreesFactor;
  4086. };
  4087. }(),
  4088. isPowerOfTwo: function ( value ) {
  4089. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  4090. },
  4091. nearestPowerOfTwo: function ( value ) {
  4092. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  4093. },
  4094. nextPowerOfTwo: function ( value ) {
  4095. value --;
  4096. value |= value >> 1;
  4097. value |= value >> 2;
  4098. value |= value >> 4;
  4099. value |= value >> 8;
  4100. value |= value >> 16;
  4101. value ++;
  4102. return value;
  4103. }
  4104. };
  4105. // File:src/math/Spline.js
  4106. /**
  4107. * Spline from Tween.js, slightly optimized (and trashed)
  4108. * http://sole.github.com/tween.js/examples/05_spline.html
  4109. *
  4110. * @author mrdoob / http://mrdoob.com/
  4111. * @author alteredq / http://alteredqualia.com/
  4112. */
  4113. THREE.Spline = function ( points ) {
  4114. this.points = points;
  4115. var c = [], v3 = { x: 0, y: 0, z: 0 },
  4116. point, intPoint, weight, w2, w3,
  4117. pa, pb, pc, pd;
  4118. this.initFromArray = function ( a ) {
  4119. this.points = [];
  4120. for ( var i = 0; i < a.length; i ++ ) {
  4121. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  4122. }
  4123. };
  4124. this.getPoint = function ( k ) {
  4125. point = ( this.points.length - 1 ) * k;
  4126. intPoint = Math.floor( point );
  4127. weight = point - intPoint;
  4128. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  4129. c[ 1 ] = intPoint;
  4130. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  4131. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  4132. pa = this.points[ c[ 0 ] ];
  4133. pb = this.points[ c[ 1 ] ];
  4134. pc = this.points[ c[ 2 ] ];
  4135. pd = this.points[ c[ 3 ] ];
  4136. w2 = weight * weight;
  4137. w3 = weight * w2;
  4138. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  4139. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  4140. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  4141. return v3;
  4142. };
  4143. this.getControlPointsArray = function () {
  4144. var i, p, l = this.points.length,
  4145. coords = [];
  4146. for ( i = 0; i < l; i ++ ) {
  4147. p = this.points[ i ];
  4148. coords[ i ] = [ p.x, p.y, p.z ];
  4149. }
  4150. return coords;
  4151. };
  4152. // approximate length by summing linear segments
  4153. this.getLength = function ( nSubDivisions ) {
  4154. var i, index, nSamples, position,
  4155. point = 0, intPoint = 0, oldIntPoint = 0,
  4156. oldPosition = new THREE.Vector3(),
  4157. tmpVec = new THREE.Vector3(),
  4158. chunkLengths = [],
  4159. totalLength = 0;
  4160. // first point has 0 length
  4161. chunkLengths[ 0 ] = 0;
  4162. if ( ! nSubDivisions ) nSubDivisions = 100;
  4163. nSamples = this.points.length * nSubDivisions;
  4164. oldPosition.copy( this.points[ 0 ] );
  4165. for ( i = 1; i < nSamples; i ++ ) {
  4166. index = i / nSamples;
  4167. position = this.getPoint( index );
  4168. tmpVec.copy( position );
  4169. totalLength += tmpVec.distanceTo( oldPosition );
  4170. oldPosition.copy( position );
  4171. point = ( this.points.length - 1 ) * index;
  4172. intPoint = Math.floor( point );
  4173. if ( intPoint !== oldIntPoint ) {
  4174. chunkLengths[ intPoint ] = totalLength;
  4175. oldIntPoint = intPoint;
  4176. }
  4177. }
  4178. // last point ends with total length
  4179. chunkLengths[ chunkLengths.length ] = totalLength;
  4180. return { chunks: chunkLengths, total: totalLength };
  4181. };
  4182. this.reparametrizeByArcLength = function ( samplingCoef ) {
  4183. var i, j,
  4184. index, indexCurrent, indexNext,
  4185. realDistance,
  4186. sampling, position,
  4187. newpoints = [],
  4188. tmpVec = new THREE.Vector3(),
  4189. sl = this.getLength();
  4190. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  4191. for ( i = 1; i < this.points.length; i ++ ) {
  4192. //tmpVec.copy( this.points[ i - 1 ] );
  4193. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  4194. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  4195. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  4196. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  4197. indexNext = i / ( this.points.length - 1 );
  4198. for ( j = 1; j < sampling - 1; j ++ ) {
  4199. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  4200. position = this.getPoint( index );
  4201. newpoints.push( tmpVec.copy( position ).clone() );
  4202. }
  4203. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  4204. }
  4205. this.points = newpoints;
  4206. };
  4207. // Catmull-Rom
  4208. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  4209. var v0 = ( p2 - p0 ) * 0.5,
  4210. v1 = ( p3 - p1 ) * 0.5;
  4211. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  4212. }
  4213. };
  4214. // File:src/math/Triangle.js
  4215. /**
  4216. * @author bhouston / http://clara.io
  4217. * @author mrdoob / http://mrdoob.com/
  4218. */
  4219. THREE.Triangle = function ( a, b, c ) {
  4220. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  4221. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  4222. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  4223. };
  4224. THREE.Triangle.normal = function () {
  4225. var v0 = new THREE.Vector3();
  4226. return function ( a, b, c, optionalTarget ) {
  4227. var result = optionalTarget || new THREE.Vector3();
  4228. result.subVectors( c, b );
  4229. v0.subVectors( a, b );
  4230. result.cross( v0 );
  4231. var resultLengthSq = result.lengthSq();
  4232. if ( resultLengthSq > 0 ) {
  4233. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  4234. }
  4235. return result.set( 0, 0, 0 );
  4236. };
  4237. }();
  4238. // static/instance method to calculate barycentric coordinates
  4239. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4240. THREE.Triangle.barycoordFromPoint = function () {
  4241. var v0 = new THREE.Vector3();
  4242. var v1 = new THREE.Vector3();
  4243. var v2 = new THREE.Vector3();
  4244. return function ( point, a, b, c, optionalTarget ) {
  4245. v0.subVectors( c, a );
  4246. v1.subVectors( b, a );
  4247. v2.subVectors( point, a );
  4248. var dot00 = v0.dot( v0 );
  4249. var dot01 = v0.dot( v1 );
  4250. var dot02 = v0.dot( v2 );
  4251. var dot11 = v1.dot( v1 );
  4252. var dot12 = v1.dot( v2 );
  4253. var denom = ( dot00 * dot11 - dot01 * dot01 );
  4254. var result = optionalTarget || new THREE.Vector3();
  4255. // collinear or singular triangle
  4256. if ( denom === 0 ) {
  4257. // arbitrary location outside of triangle?
  4258. // not sure if this is the best idea, maybe should be returning undefined
  4259. return result.set( - 2, - 1, - 1 );
  4260. }
  4261. var invDenom = 1 / denom;
  4262. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4263. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4264. // barycentric coordinates must always sum to 1
  4265. return result.set( 1 - u - v, v, u );
  4266. };
  4267. }();
  4268. THREE.Triangle.containsPoint = function () {
  4269. var v1 = new THREE.Vector3();
  4270. return function ( point, a, b, c ) {
  4271. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  4272. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  4273. };
  4274. }();
  4275. THREE.Triangle.prototype = {
  4276. constructor: THREE.Triangle,
  4277. set: function ( a, b, c ) {
  4278. this.a.copy( a );
  4279. this.b.copy( b );
  4280. this.c.copy( c );
  4281. return this;
  4282. },
  4283. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  4284. this.a.copy( points[ i0 ] );
  4285. this.b.copy( points[ i1 ] );
  4286. this.c.copy( points[ i2 ] );
  4287. return this;
  4288. },
  4289. clone: function () {
  4290. return new this.constructor().copy( this );
  4291. },
  4292. copy: function ( triangle ) {
  4293. this.a.copy( triangle.a );
  4294. this.b.copy( triangle.b );
  4295. this.c.copy( triangle.c );
  4296. return this;
  4297. },
  4298. area: function () {
  4299. var v0 = new THREE.Vector3();
  4300. var v1 = new THREE.Vector3();
  4301. return function () {
  4302. v0.subVectors( this.c, this.b );
  4303. v1.subVectors( this.a, this.b );
  4304. return v0.cross( v1 ).length() * 0.5;
  4305. };
  4306. }(),
  4307. midpoint: function ( optionalTarget ) {
  4308. var result = optionalTarget || new THREE.Vector3();
  4309. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4310. },
  4311. normal: function ( optionalTarget ) {
  4312. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  4313. },
  4314. plane: function ( optionalTarget ) {
  4315. var result = optionalTarget || new THREE.Plane();
  4316. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  4317. },
  4318. barycoordFromPoint: function ( point, optionalTarget ) {
  4319. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  4320. },
  4321. containsPoint: function ( point ) {
  4322. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  4323. },
  4324. equals: function ( triangle ) {
  4325. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4326. }
  4327. };
  4328. // File:src/math/Interpolant.js
  4329. /**
  4330. * Abstract base class of interpolants over parametric samples.
  4331. *
  4332. * The parameter domain is one dimensional, typically the time or a path
  4333. * along a curve defined by the data.
  4334. *
  4335. * The sample values can have any dimensionality and derived classes may
  4336. * apply special interpretations to the data.
  4337. *
  4338. * This class provides the interval seek in a Template Method, deferring
  4339. * the actual interpolation to derived classes.
  4340. *
  4341. * Time complexity is O(1) for linear access crossing at most two points
  4342. * and O(log N) for random access, where N is the number of positions.
  4343. *
  4344. * References:
  4345. *
  4346. * http://www.oodesign.com/template-method-pattern.html
  4347. *
  4348. * @author tschw
  4349. */
  4350. THREE.Interpolant = function(
  4351. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4352. this.parameterPositions = parameterPositions;
  4353. this._cachedIndex = 0;
  4354. this.resultBuffer = resultBuffer !== undefined ?
  4355. resultBuffer : new sampleValues.constructor( sampleSize );
  4356. this.sampleValues = sampleValues;
  4357. this.valueSize = sampleSize;
  4358. };
  4359. THREE.Interpolant.prototype = {
  4360. constructor: THREE.Intepolant,
  4361. evaluate: function( t ) {
  4362. var pp = this.parameterPositions,
  4363. i1 = this._cachedIndex,
  4364. t1 = pp[ i1 ],
  4365. t0 = pp[ i1 - 1 ];
  4366. validate_interval: {
  4367. seek: {
  4368. var right;
  4369. linear_scan: {
  4370. //- See http://jsperf.com/comparison-to-undefined/3
  4371. //- slower code:
  4372. //-
  4373. //- if ( t >= t1 || t1 === undefined ) {
  4374. forward_scan: if ( ! ( t < t1 ) ) {
  4375. for ( var giveUpAt = i1 + 2; ;) {
  4376. if ( t1 === undefined ) {
  4377. if ( t < t0 ) break forward_scan;
  4378. // after end
  4379. i1 = pp.length;
  4380. this._cachedIndex = i1;
  4381. return this.afterEnd_( i1 - 1, t, t0 );
  4382. }
  4383. if ( i1 === giveUpAt ) break; // this loop
  4384. t0 = t1;
  4385. t1 = pp[ ++ i1 ];
  4386. if ( t < t1 ) {
  4387. // we have arrived at the sought interval
  4388. break seek;
  4389. }
  4390. }
  4391. // prepare binary search on the right side of the index
  4392. right = pp.length;
  4393. break linear_scan;
  4394. }
  4395. //- slower code:
  4396. //- if ( t < t0 || t0 === undefined ) {
  4397. if ( ! ( t >= t0 ) ) {
  4398. // looping?
  4399. var t1global = pp[ 1 ];
  4400. if ( t < t1global ) {
  4401. i1 = 2; // + 1, using the scan for the details
  4402. t0 = t1global;
  4403. }
  4404. // linear reverse scan
  4405. for ( var giveUpAt = i1 - 2; ;) {
  4406. if ( t0 === undefined ) {
  4407. // before start
  4408. this._cachedIndex = 0;
  4409. return this.beforeStart_( 0, t, t1 );
  4410. }
  4411. if ( i1 === giveUpAt ) break; // this loop
  4412. t1 = t0;
  4413. t0 = pp[ -- i1 - 1 ];
  4414. if ( t >= t0 ) {
  4415. // we have arrived at the sought interval
  4416. break seek;
  4417. }
  4418. }
  4419. // prepare binary search on the left side of the index
  4420. right = i1;
  4421. i1 = 0;
  4422. break linear_scan;
  4423. }
  4424. // the interval is valid
  4425. break validate_interval;
  4426. } // linear scan
  4427. // binary search
  4428. while ( i1 < right ) {
  4429. var mid = ( i1 + right ) >>> 1;
  4430. if ( t < pp[ mid ] ) {
  4431. right = mid;
  4432. } else {
  4433. i1 = mid + 1;
  4434. }
  4435. }
  4436. t1 = pp[ i1 ];
  4437. t0 = pp[ i1 - 1 ];
  4438. // check boundary cases, again
  4439. if ( t0 === undefined ) {
  4440. this._cachedIndex = 0;
  4441. return this.beforeStart_( 0, t, t1 );
  4442. }
  4443. if ( t1 === undefined ) {
  4444. i1 = pp.length;
  4445. this._cachedIndex = i1;
  4446. return this.afterEnd_( i1 - 1, t0, t );
  4447. }
  4448. } // seek
  4449. this._cachedIndex = i1;
  4450. this.intervalChanged_( i1, t0, t1 );
  4451. } // validate_interval
  4452. return this.interpolate_( i1, t0, t, t1 );
  4453. },
  4454. settings: null, // optional, subclass-specific settings structure
  4455. // Note: The indirection allows central control of many interpolants.
  4456. // --- Protected interface
  4457. DefaultSettings_: {},
  4458. getSettings_: function() {
  4459. return this.settings || this.DefaultSettings_;
  4460. },
  4461. copySampleValue_: function( index ) {
  4462. // copies a sample value to the result buffer
  4463. var result = this.resultBuffer,
  4464. values = this.sampleValues,
  4465. stride = this.valueSize,
  4466. offset = index * stride;
  4467. for ( var i = 0; i !== stride; ++ i ) {
  4468. result[ i ] = values[ offset + i ];
  4469. }
  4470. return result;
  4471. },
  4472. // Template methods for derived classes:
  4473. interpolate_: function( i1, t0, t, t1 ) {
  4474. throw new Error( "call to abstract method" );
  4475. // implementations shall return this.resultBuffer
  4476. },
  4477. intervalChanged_: function( i1, t0, t1 ) {
  4478. // empty
  4479. }
  4480. };
  4481. Object.assign( THREE.Interpolant.prototype, {
  4482. beforeStart_: //( 0, t, t0 ), returns this.resultBuffer
  4483. THREE.Interpolant.prototype.copySampleValue_,
  4484. afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer
  4485. THREE.Interpolant.prototype.copySampleValue_
  4486. } );
  4487. // File:src/math/interpolants/CubicInterpolant.js
  4488. /**
  4489. * Fast and simple cubic spline interpolant.
  4490. *
  4491. * It was derived from a Hermitian construction setting the first derivative
  4492. * at each sample position to the linear slope between neighboring positions
  4493. * over their parameter interval.
  4494. *
  4495. * @author tschw
  4496. */
  4497. THREE.CubicInterpolant = function(
  4498. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4499. THREE.Interpolant.call(
  4500. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4501. this._weightPrev = -0;
  4502. this._offsetPrev = -0;
  4503. this._weightNext = -0;
  4504. this._offsetNext = -0;
  4505. };
  4506. THREE.CubicInterpolant.prototype =
  4507. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4508. constructor: THREE.CubicInterpolant,
  4509. DefaultSettings_: {
  4510. endingStart: THREE.ZeroCurvatureEnding,
  4511. endingEnd: THREE.ZeroCurvatureEnding
  4512. },
  4513. intervalChanged_: function( i1, t0, t1 ) {
  4514. var pp = this.parameterPositions,
  4515. iPrev = i1 - 2,
  4516. iNext = i1 + 1,
  4517. tPrev = pp[ iPrev ],
  4518. tNext = pp[ iNext ];
  4519. if ( tPrev === undefined ) {
  4520. switch ( this.getSettings_().endingStart ) {
  4521. case THREE.ZeroSlopeEnding:
  4522. // f'(t0) = 0
  4523. iPrev = i1;
  4524. tPrev = 2 * t0 - t1;
  4525. break;
  4526. case THREE.WrapAroundEnding:
  4527. // use the other end of the curve
  4528. iPrev = pp.length - 2;
  4529. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  4530. break;
  4531. default: // ZeroCurvatureEnding
  4532. // f''(t0) = 0 a.k.a. Natural Spline
  4533. iPrev = i1;
  4534. tPrev = t1;
  4535. }
  4536. }
  4537. if ( tNext === undefined ) {
  4538. switch ( this.getSettings_().endingEnd ) {
  4539. case THREE.ZeroSlopeEnding:
  4540. // f'(tN) = 0
  4541. iNext = i1;
  4542. tNext = 2 * t1 - t0;
  4543. break;
  4544. case THREE.WrapAroundEnding:
  4545. // use the other end of the curve
  4546. iNext = 1;
  4547. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  4548. break;
  4549. default: // ZeroCurvatureEnding
  4550. // f''(tN) = 0, a.k.a. Natural Spline
  4551. iNext = i1 - 1;
  4552. tNext = t0;
  4553. }
  4554. }
  4555. var halfDt = ( t1 - t0 ) * 0.5,
  4556. stride = this.valueSize;
  4557. this._weightPrev = halfDt / ( t0 - tPrev );
  4558. this._weightNext = halfDt / ( tNext - t1 );
  4559. this._offsetPrev = iPrev * stride;
  4560. this._offsetNext = iNext * stride;
  4561. },
  4562. interpolate_: function( i1, t0, t, t1 ) {
  4563. var result = this.resultBuffer,
  4564. values = this.sampleValues,
  4565. stride = this.valueSize,
  4566. o1 = i1 * stride, o0 = o1 - stride,
  4567. oP = this._offsetPrev, oN = this._offsetNext,
  4568. wP = this._weightPrev, wN = this._weightNext,
  4569. p = ( t - t0 ) / ( t1 - t0 ),
  4570. pp = p * p,
  4571. ppp = pp * p;
  4572. // evaluate polynomials
  4573. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  4574. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  4575. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  4576. var sN = wN * ppp - wN * pp;
  4577. // combine data linearly
  4578. for ( var i = 0; i !== stride; ++ i ) {
  4579. result[ i ] =
  4580. sP * values[ oP + i ] +
  4581. s0 * values[ o0 + i ] +
  4582. s1 * values[ o1 + i ] +
  4583. sN * values[ oN + i ];
  4584. }
  4585. return result;
  4586. }
  4587. } );
  4588. // File:src/math/interpolants/DiscreteInterpolant.js
  4589. /**
  4590. *
  4591. * Interpolant that evaluates to the sample value at the position preceeding
  4592. * the parameter.
  4593. *
  4594. * @author tschw
  4595. */
  4596. THREE.DiscreteInterpolant = function(
  4597. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4598. THREE.Interpolant.call(
  4599. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4600. };
  4601. THREE.DiscreteInterpolant.prototype =
  4602. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4603. constructor: THREE.DiscreteInterpolant,
  4604. interpolate_: function( i1, t0, t, t1 ) {
  4605. return this.copySampleValue_( i1 - 1 );
  4606. }
  4607. } );
  4608. // File:src/math/interpolants/LinearInterpolant.js
  4609. /**
  4610. * @author tschw
  4611. */
  4612. THREE.LinearInterpolant = function(
  4613. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4614. THREE.Interpolant.call(
  4615. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4616. };
  4617. THREE.LinearInterpolant.prototype =
  4618. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4619. constructor: THREE.LinearInterpolant,
  4620. interpolate_: function( i1, t0, t, t1 ) {
  4621. var result = this.resultBuffer,
  4622. values = this.sampleValues,
  4623. stride = this.valueSize,
  4624. offset1 = i1 * stride,
  4625. offset0 = offset1 - stride,
  4626. weight1 = ( t - t0 ) / ( t1 - t0 ),
  4627. weight0 = 1 - weight1;
  4628. for ( var i = 0; i !== stride; ++ i ) {
  4629. result[ i ] =
  4630. values[ offset0 + i ] * weight0 +
  4631. values[ offset1 + i ] * weight1;
  4632. }
  4633. return result;
  4634. }
  4635. } );
  4636. // File:src/math/interpolants/QuaternionLinearInterpolant.js
  4637. /**
  4638. * Spherical linear unit quaternion interpolant.
  4639. *
  4640. * @author tschw
  4641. */
  4642. THREE.QuaternionLinearInterpolant = function(
  4643. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4644. THREE.Interpolant.call(
  4645. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4646. };
  4647. THREE.QuaternionLinearInterpolant.prototype =
  4648. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4649. constructor: THREE.QuaternionLinearInterpolant,
  4650. interpolate_: function( i1, t0, t, t1 ) {
  4651. var result = this.resultBuffer,
  4652. values = this.sampleValues,
  4653. stride = this.valueSize,
  4654. offset = i1 * stride,
  4655. alpha = ( t - t0 ) / ( t1 - t0 );
  4656. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  4657. THREE.Quaternion.slerpFlat( result, 0,
  4658. values, offset - stride, values, offset, alpha );
  4659. }
  4660. return result;
  4661. }
  4662. } );
  4663. // File:src/core/Clock.js
  4664. /**
  4665. * @author alteredq / http://alteredqualia.com/
  4666. */
  4667. THREE.Clock = function ( autoStart ) {
  4668. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4669. this.startTime = 0;
  4670. this.oldTime = 0;
  4671. this.elapsedTime = 0;
  4672. this.running = false;
  4673. };
  4674. THREE.Clock.prototype = {
  4675. constructor: THREE.Clock,
  4676. start: function () {
  4677. this.startTime = self.performance.now();
  4678. this.oldTime = this.startTime;
  4679. this.running = true;
  4680. },
  4681. stop: function () {
  4682. this.getElapsedTime();
  4683. this.running = false;
  4684. },
  4685. getElapsedTime: function () {
  4686. this.getDelta();
  4687. return this.elapsedTime;
  4688. },
  4689. getDelta: function () {
  4690. var diff = 0;
  4691. if ( this.autoStart && ! this.running ) {
  4692. this.start();
  4693. }
  4694. if ( this.running ) {
  4695. var newTime = self.performance.now();
  4696. diff = 0.001 * ( newTime - this.oldTime );
  4697. this.oldTime = newTime;
  4698. this.elapsedTime += diff;
  4699. }
  4700. return diff;
  4701. }
  4702. };
  4703. // File:src/core/EventDispatcher.js
  4704. /**
  4705. * https://github.com/mrdoob/eventdispatcher.js/
  4706. */
  4707. THREE.EventDispatcher = function () {};
  4708. THREE.EventDispatcher.prototype = {
  4709. constructor: THREE.EventDispatcher,
  4710. apply: function ( object ) {
  4711. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  4712. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  4713. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  4714. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  4715. },
  4716. addEventListener: function ( type, listener ) {
  4717. if ( this._listeners === undefined ) this._listeners = {};
  4718. var listeners = this._listeners;
  4719. if ( listeners[ type ] === undefined ) {
  4720. listeners[ type ] = [];
  4721. }
  4722. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4723. listeners[ type ].push( listener );
  4724. }
  4725. },
  4726. hasEventListener: function ( type, listener ) {
  4727. if ( this._listeners === undefined ) return false;
  4728. var listeners = this._listeners;
  4729. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  4730. return true;
  4731. }
  4732. return false;
  4733. },
  4734. removeEventListener: function ( type, listener ) {
  4735. if ( this._listeners === undefined ) return;
  4736. var listeners = this._listeners;
  4737. var listenerArray = listeners[ type ];
  4738. if ( listenerArray !== undefined ) {
  4739. var index = listenerArray.indexOf( listener );
  4740. if ( index !== - 1 ) {
  4741. listenerArray.splice( index, 1 );
  4742. }
  4743. }
  4744. },
  4745. dispatchEvent: function ( event ) {
  4746. if ( this._listeners === undefined ) return;
  4747. var listeners = this._listeners;
  4748. var listenerArray = listeners[ event.type ];
  4749. if ( listenerArray !== undefined ) {
  4750. event.target = this;
  4751. var array = [];
  4752. var length = listenerArray.length;
  4753. for ( var i = 0; i < length; i ++ ) {
  4754. array[ i ] = listenerArray[ i ];
  4755. }
  4756. for ( var i = 0; i < length; i ++ ) {
  4757. array[ i ].call( this, event );
  4758. }
  4759. }
  4760. }
  4761. };
  4762. // File:src/core/Layers.js
  4763. /**
  4764. * @author mrdoob / http://mrdoob.com/
  4765. */
  4766. THREE.Layers = function () {
  4767. this.mask = 1;
  4768. };
  4769. THREE.Layers.prototype = {
  4770. constructor: THREE.Layers,
  4771. set: function ( channel ) {
  4772. this.mask = 1 << channel;
  4773. },
  4774. enable: function ( channel ) {
  4775. this.mask |= 1 << channel;
  4776. },
  4777. toggle: function ( channel ) {
  4778. this.mask ^= 1 << channel;
  4779. },
  4780. disable: function ( channel ) {
  4781. this.mask &= ~ ( 1 << channel );
  4782. },
  4783. test: function ( layers ) {
  4784. return ( this.mask & layers.mask ) !== 0;
  4785. }
  4786. };
  4787. // File:src/core/Raycaster.js
  4788. /**
  4789. * @author mrdoob / http://mrdoob.com/
  4790. * @author bhouston / http://clara.io/
  4791. * @author stephomi / http://stephaneginier.com/
  4792. */
  4793. ( function ( THREE ) {
  4794. THREE.Raycaster = function ( origin, direction, near, far ) {
  4795. this.ray = new THREE.Ray( origin, direction );
  4796. // direction is assumed to be normalized (for accurate distance calculations)
  4797. this.near = near || 0;
  4798. this.far = far || Infinity;
  4799. this.params = {
  4800. Mesh: {},
  4801. Line: {},
  4802. LOD: {},
  4803. Points: { threshold: 1 },
  4804. Sprite: {}
  4805. };
  4806. Object.defineProperties( this.params, {
  4807. PointCloud: {
  4808. get: function () {
  4809. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  4810. return this.Points;
  4811. }
  4812. }
  4813. } );
  4814. };
  4815. function descSort( a, b ) {
  4816. return a.distance - b.distance;
  4817. }
  4818. function intersectObject( object, raycaster, intersects, recursive ) {
  4819. if ( object.visible === false ) return;
  4820. object.raycast( raycaster, intersects );
  4821. if ( recursive === true ) {
  4822. var children = object.children;
  4823. for ( var i = 0, l = children.length; i < l; i ++ ) {
  4824. intersectObject( children[ i ], raycaster, intersects, true );
  4825. }
  4826. }
  4827. }
  4828. //
  4829. THREE.Raycaster.prototype = {
  4830. constructor: THREE.Raycaster,
  4831. linePrecision: 1,
  4832. set: function ( origin, direction ) {
  4833. // direction is assumed to be normalized (for accurate distance calculations)
  4834. this.ray.set( origin, direction );
  4835. },
  4836. setFromCamera: function ( coords, camera ) {
  4837. if ( camera instanceof THREE.PerspectiveCamera ) {
  4838. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  4839. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  4840. } else if ( camera instanceof THREE.OrthographicCamera ) {
  4841. this.ray.origin.set( coords.x, coords.y, - 1 ).unproject( camera );
  4842. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  4843. } else {
  4844. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  4845. }
  4846. },
  4847. intersectObject: function ( object, recursive ) {
  4848. var intersects = [];
  4849. intersectObject( object, this, intersects, recursive );
  4850. intersects.sort( descSort );
  4851. return intersects;
  4852. },
  4853. intersectObjects: function ( objects, recursive ) {
  4854. var intersects = [];
  4855. if ( Array.isArray( objects ) === false ) {
  4856. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  4857. return intersects;
  4858. }
  4859. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4860. intersectObject( objects[ i ], this, intersects, recursive );
  4861. }
  4862. intersects.sort( descSort );
  4863. return intersects;
  4864. }
  4865. };
  4866. }( THREE ) );
  4867. // File:src/core/Object3D.js
  4868. /**
  4869. * @author mrdoob / http://mrdoob.com/
  4870. * @author mikael emtinger / http://gomo.se/
  4871. * @author alteredq / http://alteredqualia.com/
  4872. * @author WestLangley / http://github.com/WestLangley
  4873. * @author elephantatwork / www.elephantatwork.ch
  4874. */
  4875. THREE.Object3D = function () {
  4876. Object.defineProperty( this, 'id', { value: THREE.Object3DIdCount ++ } );
  4877. this.uuid = THREE.Math.generateUUID();
  4878. this.name = '';
  4879. this.type = 'Object3D';
  4880. this.parent = null;
  4881. this.children = [];
  4882. this.up = THREE.Object3D.DefaultUp.clone();
  4883. var position = new THREE.Vector3();
  4884. var rotation = new THREE.Euler();
  4885. var quaternion = new THREE.Quaternion();
  4886. var scale = new THREE.Vector3( 1, 1, 1 );
  4887. function onRotationChange() {
  4888. quaternion.setFromEuler( rotation, false );
  4889. }
  4890. function onQuaternionChange() {
  4891. rotation.setFromQuaternion( quaternion, undefined, false );
  4892. }
  4893. rotation.onChange( onRotationChange );
  4894. quaternion.onChange( onQuaternionChange );
  4895. Object.defineProperties( this, {
  4896. position: {
  4897. enumerable: true,
  4898. value: position
  4899. },
  4900. rotation: {
  4901. enumerable: true,
  4902. value: rotation
  4903. },
  4904. quaternion: {
  4905. enumerable: true,
  4906. value: quaternion
  4907. },
  4908. scale: {
  4909. enumerable: true,
  4910. value: scale
  4911. },
  4912. modelViewMatrix: {
  4913. value: new THREE.Matrix4()
  4914. },
  4915. normalMatrix: {
  4916. value: new THREE.Matrix3()
  4917. }
  4918. } );
  4919. this.rotationAutoUpdate = true;
  4920. this.matrix = new THREE.Matrix4();
  4921. this.matrixWorld = new THREE.Matrix4();
  4922. this.matrixAutoUpdate = THREE.Object3D.DefaultMatrixAutoUpdate;
  4923. this.matrixWorldNeedsUpdate = false;
  4924. this.layers = new THREE.Layers();
  4925. this.visible = true;
  4926. this.castShadow = false;
  4927. this.receiveShadow = false;
  4928. this.frustumCulled = true;
  4929. this.renderOrder = 0;
  4930. this.userData = {};
  4931. };
  4932. THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 );
  4933. THREE.Object3D.DefaultMatrixAutoUpdate = true;
  4934. THREE.Object3D.prototype = {
  4935. constructor: THREE.Object3D,
  4936. applyMatrix: function ( matrix ) {
  4937. this.matrix.multiplyMatrices( matrix, this.matrix );
  4938. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4939. },
  4940. setRotationFromAxisAngle: function ( axis, angle ) {
  4941. // assumes axis is normalized
  4942. this.quaternion.setFromAxisAngle( axis, angle );
  4943. },
  4944. setRotationFromEuler: function ( euler ) {
  4945. this.quaternion.setFromEuler( euler, true );
  4946. },
  4947. setRotationFromMatrix: function ( m ) {
  4948. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4949. this.quaternion.setFromRotationMatrix( m );
  4950. },
  4951. setRotationFromQuaternion: function ( q ) {
  4952. // assumes q is normalized
  4953. this.quaternion.copy( q );
  4954. },
  4955. rotateOnAxis: function () {
  4956. // rotate object on axis in object space
  4957. // axis is assumed to be normalized
  4958. var q1 = new THREE.Quaternion();
  4959. return function ( axis, angle ) {
  4960. q1.setFromAxisAngle( axis, angle );
  4961. this.quaternion.multiply( q1 );
  4962. return this;
  4963. };
  4964. }(),
  4965. rotateX: function () {
  4966. var v1 = new THREE.Vector3( 1, 0, 0 );
  4967. return function ( angle ) {
  4968. return this.rotateOnAxis( v1, angle );
  4969. };
  4970. }(),
  4971. rotateY: function () {
  4972. var v1 = new THREE.Vector3( 0, 1, 0 );
  4973. return function ( angle ) {
  4974. return this.rotateOnAxis( v1, angle );
  4975. };
  4976. }(),
  4977. rotateZ: function () {
  4978. var v1 = new THREE.Vector3( 0, 0, 1 );
  4979. return function ( angle ) {
  4980. return this.rotateOnAxis( v1, angle );
  4981. };
  4982. }(),
  4983. translateOnAxis: function () {
  4984. // translate object by distance along axis in object space
  4985. // axis is assumed to be normalized
  4986. var v1 = new THREE.Vector3();
  4987. return function ( axis, distance ) {
  4988. v1.copy( axis ).applyQuaternion( this.quaternion );
  4989. this.position.add( v1.multiplyScalar( distance ) );
  4990. return this;
  4991. };
  4992. }(),
  4993. translateX: function () {
  4994. var v1 = new THREE.Vector3( 1, 0, 0 );
  4995. return function ( distance ) {
  4996. return this.translateOnAxis( v1, distance );
  4997. };
  4998. }(),
  4999. translateY: function () {
  5000. var v1 = new THREE.Vector3( 0, 1, 0 );
  5001. return function ( distance ) {
  5002. return this.translateOnAxis( v1, distance );
  5003. };
  5004. }(),
  5005. translateZ: function () {
  5006. var v1 = new THREE.Vector3( 0, 0, 1 );
  5007. return function ( distance ) {
  5008. return this.translateOnAxis( v1, distance );
  5009. };
  5010. }(),
  5011. localToWorld: function ( vector ) {
  5012. return vector.applyMatrix4( this.matrixWorld );
  5013. },
  5014. worldToLocal: function () {
  5015. var m1 = new THREE.Matrix4();
  5016. return function ( vector ) {
  5017. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  5018. };
  5019. }(),
  5020. lookAt: function () {
  5021. // This routine does not support objects with rotated and/or translated parent(s)
  5022. var m1 = new THREE.Matrix4();
  5023. return function ( vector ) {
  5024. m1.lookAt( vector, this.position, this.up );
  5025. this.quaternion.setFromRotationMatrix( m1 );
  5026. };
  5027. }(),
  5028. add: function ( object ) {
  5029. if ( arguments.length > 1 ) {
  5030. for ( var i = 0; i < arguments.length; i ++ ) {
  5031. this.add( arguments[ i ] );
  5032. }
  5033. return this;
  5034. }
  5035. if ( object === this ) {
  5036. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  5037. return this;
  5038. }
  5039. if ( object instanceof THREE.Object3D ) {
  5040. if ( object.parent !== null ) {
  5041. object.parent.remove( object );
  5042. }
  5043. object.parent = this;
  5044. object.dispatchEvent( { type: 'added' } );
  5045. this.children.push( object );
  5046. } else {
  5047. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  5048. }
  5049. return this;
  5050. },
  5051. remove: function ( object ) {
  5052. if ( arguments.length > 1 ) {
  5053. for ( var i = 0; i < arguments.length; i ++ ) {
  5054. this.remove( arguments[ i ] );
  5055. }
  5056. }
  5057. var index = this.children.indexOf( object );
  5058. if ( index !== - 1 ) {
  5059. object.parent = null;
  5060. object.dispatchEvent( { type: 'removed' } );
  5061. this.children.splice( index, 1 );
  5062. }
  5063. },
  5064. getObjectById: function ( id ) {
  5065. return this.getObjectByProperty( 'id', id );
  5066. },
  5067. getObjectByName: function ( name ) {
  5068. return this.getObjectByProperty( 'name', name );
  5069. },
  5070. getObjectByProperty: function ( name, value ) {
  5071. if ( this[ name ] === value ) return this;
  5072. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  5073. var child = this.children[ i ];
  5074. var object = child.getObjectByProperty( name, value );
  5075. if ( object !== undefined ) {
  5076. return object;
  5077. }
  5078. }
  5079. return undefined;
  5080. },
  5081. getWorldPosition: function ( optionalTarget ) {
  5082. var result = optionalTarget || new THREE.Vector3();
  5083. this.updateMatrixWorld( true );
  5084. return result.setFromMatrixPosition( this.matrixWorld );
  5085. },
  5086. getWorldQuaternion: function () {
  5087. var position = new THREE.Vector3();
  5088. var scale = new THREE.Vector3();
  5089. return function ( optionalTarget ) {
  5090. var result = optionalTarget || new THREE.Quaternion();
  5091. this.updateMatrixWorld( true );
  5092. this.matrixWorld.decompose( position, result, scale );
  5093. return result;
  5094. };
  5095. }(),
  5096. getWorldRotation: function () {
  5097. var quaternion = new THREE.Quaternion();
  5098. return function ( optionalTarget ) {
  5099. var result = optionalTarget || new THREE.Euler();
  5100. this.getWorldQuaternion( quaternion );
  5101. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  5102. };
  5103. }(),
  5104. getWorldScale: function () {
  5105. var position = new THREE.Vector3();
  5106. var quaternion = new THREE.Quaternion();
  5107. return function ( optionalTarget ) {
  5108. var result = optionalTarget || new THREE.Vector3();
  5109. this.updateMatrixWorld( true );
  5110. this.matrixWorld.decompose( position, quaternion, result );
  5111. return result;
  5112. };
  5113. }(),
  5114. getWorldDirection: function () {
  5115. var quaternion = new THREE.Quaternion();
  5116. return function ( optionalTarget ) {
  5117. var result = optionalTarget || new THREE.Vector3();
  5118. this.getWorldQuaternion( quaternion );
  5119. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  5120. };
  5121. }(),
  5122. raycast: function () {},
  5123. traverse: function ( callback ) {
  5124. callback( this );
  5125. var children = this.children;
  5126. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5127. children[ i ].traverse( callback );
  5128. }
  5129. },
  5130. traverseVisible: function ( callback ) {
  5131. if ( this.visible === false ) return;
  5132. callback( this );
  5133. var children = this.children;
  5134. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5135. children[ i ].traverseVisible( callback );
  5136. }
  5137. },
  5138. traverseAncestors: function ( callback ) {
  5139. var parent = this.parent;
  5140. if ( parent !== null ) {
  5141. callback( parent );
  5142. parent.traverseAncestors( callback );
  5143. }
  5144. },
  5145. updateMatrix: function () {
  5146. this.matrix.compose( this.position, this.quaternion, this.scale );
  5147. this.matrixWorldNeedsUpdate = true;
  5148. },
  5149. updateMatrixWorld: function ( force ) {
  5150. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  5151. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  5152. if ( this.parent === null ) {
  5153. this.matrixWorld.copy( this.matrix );
  5154. } else {
  5155. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  5156. }
  5157. this.matrixWorldNeedsUpdate = false;
  5158. force = true;
  5159. }
  5160. // update children
  5161. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  5162. this.children[ i ].updateMatrixWorld( force );
  5163. }
  5164. },
  5165. toJSON: function ( meta ) {
  5166. var isRootObject = ( meta === undefined );
  5167. var output = {};
  5168. // meta is a hash used to collect geometries, materials.
  5169. // not providing it implies that this is the root object
  5170. // being serialized.
  5171. if ( isRootObject ) {
  5172. // initialize meta obj
  5173. meta = {
  5174. geometries: {},
  5175. materials: {},
  5176. textures: {},
  5177. images: {}
  5178. };
  5179. output.metadata = {
  5180. version: 4.4,
  5181. type: 'Object',
  5182. generator: 'Object3D.toJSON'
  5183. };
  5184. }
  5185. // standard Object3D serialization
  5186. var object = {};
  5187. object.uuid = this.uuid;
  5188. object.type = this.type;
  5189. if ( this.name !== '' ) object.name = this.name;
  5190. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  5191. if ( this.castShadow === true ) object.castShadow = true;
  5192. if ( this.receiveShadow === true ) object.receiveShadow = true;
  5193. if ( this.visible === false ) object.visible = false;
  5194. object.matrix = this.matrix.toArray();
  5195. //
  5196. if ( this.geometry !== undefined ) {
  5197. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  5198. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta );
  5199. }
  5200. object.geometry = this.geometry.uuid;
  5201. }
  5202. if ( this.material !== undefined ) {
  5203. if ( meta.materials[ this.material.uuid ] === undefined ) {
  5204. meta.materials[ this.material.uuid ] = this.material.toJSON( meta );
  5205. }
  5206. object.material = this.material.uuid;
  5207. }
  5208. //
  5209. if ( this.children.length > 0 ) {
  5210. object.children = [];
  5211. for ( var i = 0; i < this.children.length; i ++ ) {
  5212. object.children.push( this.children[ i ].toJSON( meta ).object );
  5213. }
  5214. }
  5215. if ( isRootObject ) {
  5216. var geometries = extractFromCache( meta.geometries );
  5217. var materials = extractFromCache( meta.materials );
  5218. var textures = extractFromCache( meta.textures );
  5219. var images = extractFromCache( meta.images );
  5220. if ( geometries.length > 0 ) output.geometries = geometries;
  5221. if ( materials.length > 0 ) output.materials = materials;
  5222. if ( textures.length > 0 ) output.textures = textures;
  5223. if ( images.length > 0 ) output.images = images;
  5224. }
  5225. output.object = object;
  5226. return output;
  5227. // extract data from the cache hash
  5228. // remove metadata on each item
  5229. // and return as array
  5230. function extractFromCache ( cache ) {
  5231. var values = [];
  5232. for ( var key in cache ) {
  5233. var data = cache[ key ];
  5234. delete data.metadata;
  5235. values.push( data );
  5236. }
  5237. return values;
  5238. }
  5239. },
  5240. clone: function ( recursive ) {
  5241. return new this.constructor().copy( this, recursive );
  5242. },
  5243. copy: function ( source, recursive ) {
  5244. if ( recursive === undefined ) recursive = true;
  5245. this.name = source.name;
  5246. this.up.copy( source.up );
  5247. this.position.copy( source.position );
  5248. this.quaternion.copy( source.quaternion );
  5249. this.scale.copy( source.scale );
  5250. this.rotationAutoUpdate = source.rotationAutoUpdate;
  5251. this.matrix.copy( source.matrix );
  5252. this.matrixWorld.copy( source.matrixWorld );
  5253. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5254. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5255. this.visible = source.visible;
  5256. this.castShadow = source.castShadow;
  5257. this.receiveShadow = source.receiveShadow;
  5258. this.frustumCulled = source.frustumCulled;
  5259. this.renderOrder = source.renderOrder;
  5260. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5261. if ( recursive === true ) {
  5262. for ( var i = 0; i < source.children.length; i ++ ) {
  5263. var child = source.children[ i ];
  5264. this.add( child.clone() );
  5265. }
  5266. }
  5267. return this;
  5268. }
  5269. };
  5270. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  5271. THREE.Object3DIdCount = 0;
  5272. // File:src/core/Face3.js
  5273. /**
  5274. * @author mrdoob / http://mrdoob.com/
  5275. * @author alteredq / http://alteredqualia.com/
  5276. */
  5277. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  5278. this.a = a;
  5279. this.b = b;
  5280. this.c = c;
  5281. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  5282. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  5283. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  5284. this.vertexColors = Array.isArray( color ) ? color : [];
  5285. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5286. };
  5287. THREE.Face3.prototype = {
  5288. constructor: THREE.Face3,
  5289. clone: function () {
  5290. return new this.constructor().copy( this );
  5291. },
  5292. copy: function ( source ) {
  5293. this.a = source.a;
  5294. this.b = source.b;
  5295. this.c = source.c;
  5296. this.normal.copy( source.normal );
  5297. this.color.copy( source.color );
  5298. this.materialIndex = source.materialIndex;
  5299. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  5300. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  5301. }
  5302. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  5303. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  5304. }
  5305. return this;
  5306. }
  5307. };
  5308. // File:src/core/Face4.js
  5309. /**
  5310. * @author mrdoob / http://mrdoob.com/
  5311. */
  5312. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  5313. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  5314. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  5315. };
  5316. // File:src/core/BufferAttribute.js
  5317. /**
  5318. * @author mrdoob / http://mrdoob.com/
  5319. */
  5320. THREE.BufferAttribute = function ( array, itemSize ) {
  5321. this.uuid = THREE.Math.generateUUID();
  5322. this.array = array;
  5323. this.itemSize = itemSize;
  5324. this.dynamic = false;
  5325. this.updateRange = { offset: 0, count: - 1 };
  5326. this.version = 0;
  5327. };
  5328. THREE.BufferAttribute.prototype = {
  5329. constructor: THREE.BufferAttribute,
  5330. get length() {
  5331. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' );
  5332. return this.array.length;
  5333. },
  5334. get count() {
  5335. return this.array.length / this.itemSize;
  5336. },
  5337. set needsUpdate( value ) {
  5338. if ( value === true ) this.version ++;
  5339. },
  5340. setDynamic: function ( value ) {
  5341. this.dynamic = value;
  5342. return this;
  5343. },
  5344. copy: function ( source ) {
  5345. this.array = new source.array.constructor( source.array );
  5346. this.itemSize = source.itemSize;
  5347. this.dynamic = source.dynamic;
  5348. return this;
  5349. },
  5350. copyAt: function ( index1, attribute, index2 ) {
  5351. index1 *= this.itemSize;
  5352. index2 *= attribute.itemSize;
  5353. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  5354. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5355. }
  5356. return this;
  5357. },
  5358. copyArray: function ( array ) {
  5359. this.array.set( array );
  5360. return this;
  5361. },
  5362. copyColorsArray: function ( colors ) {
  5363. var array = this.array, offset = 0;
  5364. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  5365. var color = colors[ i ];
  5366. if ( color === undefined ) {
  5367. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  5368. color = new THREE.Color();
  5369. }
  5370. array[ offset ++ ] = color.r;
  5371. array[ offset ++ ] = color.g;
  5372. array[ offset ++ ] = color.b;
  5373. }
  5374. return this;
  5375. },
  5376. copyIndicesArray: function ( indices ) {
  5377. var array = this.array, offset = 0;
  5378. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  5379. var index = indices[ i ];
  5380. array[ offset ++ ] = index.a;
  5381. array[ offset ++ ] = index.b;
  5382. array[ offset ++ ] = index.c;
  5383. }
  5384. return this;
  5385. },
  5386. copyVector2sArray: function ( vectors ) {
  5387. var array = this.array, offset = 0;
  5388. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5389. var vector = vectors[ i ];
  5390. if ( vector === undefined ) {
  5391. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  5392. vector = new THREE.Vector2();
  5393. }
  5394. array[ offset ++ ] = vector.x;
  5395. array[ offset ++ ] = vector.y;
  5396. }
  5397. return this;
  5398. },
  5399. copyVector3sArray: function ( vectors ) {
  5400. var array = this.array, offset = 0;
  5401. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5402. var vector = vectors[ i ];
  5403. if ( vector === undefined ) {
  5404. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  5405. vector = new THREE.Vector3();
  5406. }
  5407. array[ offset ++ ] = vector.x;
  5408. array[ offset ++ ] = vector.y;
  5409. array[ offset ++ ] = vector.z;
  5410. }
  5411. return this;
  5412. },
  5413. copyVector4sArray: function ( vectors ) {
  5414. var array = this.array, offset = 0;
  5415. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5416. var vector = vectors[ i ];
  5417. if ( vector === undefined ) {
  5418. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  5419. vector = new THREE.Vector4();
  5420. }
  5421. array[ offset ++ ] = vector.x;
  5422. array[ offset ++ ] = vector.y;
  5423. array[ offset ++ ] = vector.z;
  5424. array[ offset ++ ] = vector.w;
  5425. }
  5426. return this;
  5427. },
  5428. set: function ( value, offset ) {
  5429. if ( offset === undefined ) offset = 0;
  5430. this.array.set( value, offset );
  5431. return this;
  5432. },
  5433. getX: function ( index ) {
  5434. return this.array[ index * this.itemSize ];
  5435. },
  5436. setX: function ( index, x ) {
  5437. this.array[ index * this.itemSize ] = x;
  5438. return this;
  5439. },
  5440. getY: function ( index ) {
  5441. return this.array[ index * this.itemSize + 1 ];
  5442. },
  5443. setY: function ( index, y ) {
  5444. this.array[ index * this.itemSize + 1 ] = y;
  5445. return this;
  5446. },
  5447. getZ: function ( index ) {
  5448. return this.array[ index * this.itemSize + 2 ];
  5449. },
  5450. setZ: function ( index, z ) {
  5451. this.array[ index * this.itemSize + 2 ] = z;
  5452. return this;
  5453. },
  5454. getW: function ( index ) {
  5455. return this.array[ index * this.itemSize + 3 ];
  5456. },
  5457. setW: function ( index, w ) {
  5458. this.array[ index * this.itemSize + 3 ] = w;
  5459. return this;
  5460. },
  5461. setXY: function ( index, x, y ) {
  5462. index *= this.itemSize;
  5463. this.array[ index + 0 ] = x;
  5464. this.array[ index + 1 ] = y;
  5465. return this;
  5466. },
  5467. setXYZ: function ( index, x, y, z ) {
  5468. index *= this.itemSize;
  5469. this.array[ index + 0 ] = x;
  5470. this.array[ index + 1 ] = y;
  5471. this.array[ index + 2 ] = z;
  5472. return this;
  5473. },
  5474. setXYZW: function ( index, x, y, z, w ) {
  5475. index *= this.itemSize;
  5476. this.array[ index + 0 ] = x;
  5477. this.array[ index + 1 ] = y;
  5478. this.array[ index + 2 ] = z;
  5479. this.array[ index + 3 ] = w;
  5480. return this;
  5481. },
  5482. clone: function () {
  5483. return new this.constructor().copy( this );
  5484. }
  5485. };
  5486. //
  5487. THREE.Int8Attribute = function ( array, itemSize ) {
  5488. return new THREE.BufferAttribute( new Int8Array( array ), itemSize );
  5489. };
  5490. THREE.Uint8Attribute = function ( array, itemSize ) {
  5491. return new THREE.BufferAttribute( new Uint8Array( array ), itemSize );
  5492. };
  5493. THREE.Uint8ClampedAttribute = function ( array, itemSize ) {
  5494. return new THREE.BufferAttribute( new Uint8ClampedArray( array ), itemSize );
  5495. };
  5496. THREE.Int16Attribute = function ( array, itemSize ) {
  5497. return new THREE.BufferAttribute( new Int16Array( array ), itemSize );
  5498. };
  5499. THREE.Uint16Attribute = function ( array, itemSize ) {
  5500. return new THREE.BufferAttribute( new Uint16Array( array ), itemSize );
  5501. };
  5502. THREE.Int32Attribute = function ( array, itemSize ) {
  5503. return new THREE.BufferAttribute( new Int32Array( array ), itemSize );
  5504. };
  5505. THREE.Uint32Attribute = function ( array, itemSize ) {
  5506. return new THREE.BufferAttribute( new Uint32Array( array ), itemSize );
  5507. };
  5508. THREE.Float32Attribute = function ( array, itemSize ) {
  5509. return new THREE.BufferAttribute( new Float32Array( array ), itemSize );
  5510. };
  5511. THREE.Float64Attribute = function ( array, itemSize ) {
  5512. return new THREE.BufferAttribute( new Float64Array( array ), itemSize );
  5513. };
  5514. // Deprecated
  5515. THREE.DynamicBufferAttribute = function ( array, itemSize ) {
  5516. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  5517. return new THREE.BufferAttribute( array, itemSize ).setDynamic( true );
  5518. };
  5519. // File:src/core/InstancedBufferAttribute.js
  5520. /**
  5521. * @author benaadams / https://twitter.com/ben_a_adams
  5522. */
  5523. THREE.InstancedBufferAttribute = function ( array, itemSize, meshPerAttribute ) {
  5524. THREE.BufferAttribute.call( this, array, itemSize );
  5525. this.meshPerAttribute = meshPerAttribute || 1;
  5526. };
  5527. THREE.InstancedBufferAttribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5528. THREE.InstancedBufferAttribute.prototype.constructor = THREE.InstancedBufferAttribute;
  5529. THREE.InstancedBufferAttribute.prototype.copy = function ( source ) {
  5530. THREE.BufferAttribute.prototype.copy.call( this, source );
  5531. this.meshPerAttribute = source.meshPerAttribute;
  5532. return this;
  5533. };
  5534. // File:src/core/InterleavedBuffer.js
  5535. /**
  5536. * @author benaadams / https://twitter.com/ben_a_adams
  5537. */
  5538. THREE.InterleavedBuffer = function ( array, stride ) {
  5539. this.uuid = THREE.Math.generateUUID();
  5540. this.array = array;
  5541. this.stride = stride;
  5542. this.dynamic = false;
  5543. this.updateRange = { offset: 0, count: - 1 };
  5544. this.version = 0;
  5545. };
  5546. THREE.InterleavedBuffer.prototype = {
  5547. constructor: THREE.InterleavedBuffer,
  5548. get length () {
  5549. return this.array.length;
  5550. },
  5551. get count () {
  5552. return this.array.length / this.stride;
  5553. },
  5554. set needsUpdate( value ) {
  5555. if ( value === true ) this.version ++;
  5556. },
  5557. setDynamic: function ( value ) {
  5558. this.dynamic = value;
  5559. return this;
  5560. },
  5561. copy: function ( source ) {
  5562. this.array = new source.array.constructor( source.array );
  5563. this.stride = source.stride;
  5564. this.dynamic = source.dynamic;
  5565. },
  5566. copyAt: function ( index1, attribute, index2 ) {
  5567. index1 *= this.stride;
  5568. index2 *= attribute.stride;
  5569. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  5570. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5571. }
  5572. return this;
  5573. },
  5574. set: function ( value, offset ) {
  5575. if ( offset === undefined ) offset = 0;
  5576. this.array.set( value, offset );
  5577. return this;
  5578. },
  5579. clone: function () {
  5580. return new this.constructor().copy( this );
  5581. }
  5582. };
  5583. // File:src/core/InstancedInterleavedBuffer.js
  5584. /**
  5585. * @author benaadams / https://twitter.com/ben_a_adams
  5586. */
  5587. THREE.InstancedInterleavedBuffer = function ( array, stride, meshPerAttribute ) {
  5588. THREE.InterleavedBuffer.call( this, array, stride );
  5589. this.meshPerAttribute = meshPerAttribute || 1;
  5590. };
  5591. THREE.InstancedInterleavedBuffer.prototype = Object.create( THREE.InterleavedBuffer.prototype );
  5592. THREE.InstancedInterleavedBuffer.prototype.constructor = THREE.InstancedInterleavedBuffer;
  5593. THREE.InstancedInterleavedBuffer.prototype.copy = function ( source ) {
  5594. THREE.InterleavedBuffer.prototype.copy.call( this, source );
  5595. this.meshPerAttribute = source.meshPerAttribute;
  5596. return this;
  5597. };
  5598. // File:src/core/InterleavedBufferAttribute.js
  5599. /**
  5600. * @author benaadams / https://twitter.com/ben_a_adams
  5601. */
  5602. THREE.InterleavedBufferAttribute = function ( interleavedBuffer, itemSize, offset ) {
  5603. this.uuid = THREE.Math.generateUUID();
  5604. this.data = interleavedBuffer;
  5605. this.itemSize = itemSize;
  5606. this.offset = offset;
  5607. };
  5608. THREE.InterleavedBufferAttribute.prototype = {
  5609. constructor: THREE.InterleavedBufferAttribute,
  5610. get length() {
  5611. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' );
  5612. return this.array.length;
  5613. },
  5614. get count() {
  5615. return this.data.array.length / this.data.stride;
  5616. },
  5617. setX: function ( index, x ) {
  5618. this.data.array[ index * this.data.stride + this.offset ] = x;
  5619. return this;
  5620. },
  5621. setY: function ( index, y ) {
  5622. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  5623. return this;
  5624. },
  5625. setZ: function ( index, z ) {
  5626. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  5627. return this;
  5628. },
  5629. setW: function ( index, w ) {
  5630. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  5631. return this;
  5632. },
  5633. getX: function ( index ) {
  5634. return this.data.array[ index * this.data.stride + this.offset ];
  5635. },
  5636. getY: function ( index ) {
  5637. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  5638. },
  5639. getZ: function ( index ) {
  5640. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  5641. },
  5642. getW: function ( index ) {
  5643. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  5644. },
  5645. setXY: function ( index, x, y ) {
  5646. index = index * this.data.stride + this.offset;
  5647. this.data.array[ index + 0 ] = x;
  5648. this.data.array[ index + 1 ] = y;
  5649. return this;
  5650. },
  5651. setXYZ: function ( index, x, y, z ) {
  5652. index = index * this.data.stride + this.offset;
  5653. this.data.array[ index + 0 ] = x;
  5654. this.data.array[ index + 1 ] = y;
  5655. this.data.array[ index + 2 ] = z;
  5656. return this;
  5657. },
  5658. setXYZW: function ( index, x, y, z, w ) {
  5659. index = index * this.data.stride + this.offset;
  5660. this.data.array[ index + 0 ] = x;
  5661. this.data.array[ index + 1 ] = y;
  5662. this.data.array[ index + 2 ] = z;
  5663. this.data.array[ index + 3 ] = w;
  5664. return this;
  5665. }
  5666. };
  5667. // File:src/core/Geometry.js
  5668. /**
  5669. * @author mrdoob / http://mrdoob.com/
  5670. * @author kile / http://kile.stravaganza.org/
  5671. * @author alteredq / http://alteredqualia.com/
  5672. * @author mikael emtinger / http://gomo.se/
  5673. * @author zz85 / http://www.lab4games.net/zz85/blog
  5674. * @author bhouston / http://clara.io
  5675. */
  5676. THREE.Geometry = function () {
  5677. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  5678. this.uuid = THREE.Math.generateUUID();
  5679. this.name = '';
  5680. this.type = 'Geometry';
  5681. this.vertices = [];
  5682. this.colors = [];
  5683. this.faces = [];
  5684. this.faceVertexUvs = [ [] ];
  5685. this.morphTargets = [];
  5686. this.morphNormals = [];
  5687. this.skinWeights = [];
  5688. this.skinIndices = [];
  5689. this.lineDistances = [];
  5690. this.boundingBox = null;
  5691. this.boundingSphere = null;
  5692. // update flags
  5693. this.verticesNeedUpdate = false;
  5694. this.elementsNeedUpdate = false;
  5695. this.uvsNeedUpdate = false;
  5696. this.normalsNeedUpdate = false;
  5697. this.colorsNeedUpdate = false;
  5698. this.lineDistancesNeedUpdate = false;
  5699. this.groupsNeedUpdate = false;
  5700. };
  5701. THREE.Geometry.prototype = {
  5702. constructor: THREE.Geometry,
  5703. applyMatrix: function ( matrix ) {
  5704. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5705. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5706. var vertex = this.vertices[ i ];
  5707. vertex.applyMatrix4( matrix );
  5708. }
  5709. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5710. var face = this.faces[ i ];
  5711. face.normal.applyMatrix3( normalMatrix ).normalize();
  5712. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5713. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5714. }
  5715. }
  5716. if ( this.boundingBox !== null ) {
  5717. this.computeBoundingBox();
  5718. }
  5719. if ( this.boundingSphere !== null ) {
  5720. this.computeBoundingSphere();
  5721. }
  5722. this.verticesNeedUpdate = true;
  5723. this.normalsNeedUpdate = true;
  5724. },
  5725. rotateX: function () {
  5726. // rotate geometry around world x-axis
  5727. var m1;
  5728. return function rotateX( angle ) {
  5729. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5730. m1.makeRotationX( angle );
  5731. this.applyMatrix( m1 );
  5732. return this;
  5733. };
  5734. }(),
  5735. rotateY: function () {
  5736. // rotate geometry around world y-axis
  5737. var m1;
  5738. return function rotateY( angle ) {
  5739. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5740. m1.makeRotationY( angle );
  5741. this.applyMatrix( m1 );
  5742. return this;
  5743. };
  5744. }(),
  5745. rotateZ: function () {
  5746. // rotate geometry around world z-axis
  5747. var m1;
  5748. return function rotateZ( angle ) {
  5749. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5750. m1.makeRotationZ( angle );
  5751. this.applyMatrix( m1 );
  5752. return this;
  5753. };
  5754. }(),
  5755. translate: function () {
  5756. // translate geometry
  5757. var m1;
  5758. return function translate( x, y, z ) {
  5759. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5760. m1.makeTranslation( x, y, z );
  5761. this.applyMatrix( m1 );
  5762. return this;
  5763. };
  5764. }(),
  5765. scale: function () {
  5766. // scale geometry
  5767. var m1;
  5768. return function scale( x, y, z ) {
  5769. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5770. m1.makeScale( x, y, z );
  5771. this.applyMatrix( m1 );
  5772. return this;
  5773. };
  5774. }(),
  5775. lookAt: function () {
  5776. var obj;
  5777. return function lookAt( vector ) {
  5778. if ( obj === undefined ) obj = new THREE.Object3D();
  5779. obj.lookAt( vector );
  5780. obj.updateMatrix();
  5781. this.applyMatrix( obj.matrix );
  5782. };
  5783. }(),
  5784. fromBufferGeometry: function ( geometry ) {
  5785. var scope = this;
  5786. var indices = geometry.index !== null ? geometry.index.array : undefined;
  5787. var attributes = geometry.attributes;
  5788. var vertices = attributes.position.array;
  5789. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  5790. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  5791. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  5792. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  5793. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  5794. var tempNormals = [];
  5795. var tempUVs = [];
  5796. var tempUVs2 = [];
  5797. for ( var i = 0, j = 0, k = 0; i < vertices.length; i += 3, j += 2, k += 4 ) {
  5798. scope.vertices.push( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  5799. if ( normals !== undefined ) {
  5800. tempNormals.push( new THREE.Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  5801. }
  5802. if ( colors !== undefined ) {
  5803. scope.colors.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  5804. }
  5805. if ( uvs !== undefined ) {
  5806. tempUVs.push( new THREE.Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  5807. }
  5808. if ( uvs2 !== undefined ) {
  5809. tempUVs2.push( new THREE.Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  5810. }
  5811. }
  5812. function addFace( a, b, c ) {
  5813. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  5814. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  5815. var face = new THREE.Face3( a, b, c, vertexNormals, vertexColors );
  5816. scope.faces.push( face );
  5817. if ( uvs !== undefined ) {
  5818. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  5819. }
  5820. if ( uvs2 !== undefined ) {
  5821. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  5822. }
  5823. };
  5824. if ( indices !== undefined ) {
  5825. var groups = geometry.groups;
  5826. if ( groups.length > 0 ) {
  5827. for ( var i = 0; i < groups.length; i ++ ) {
  5828. var group = groups[ i ];
  5829. var start = group.start;
  5830. var count = group.count;
  5831. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  5832. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ] );
  5833. }
  5834. }
  5835. } else {
  5836. for ( var i = 0; i < indices.length; i += 3 ) {
  5837. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  5838. }
  5839. }
  5840. } else {
  5841. for ( var i = 0; i < vertices.length / 3; i += 3 ) {
  5842. addFace( i, i + 1, i + 2 );
  5843. }
  5844. }
  5845. this.computeFaceNormals();
  5846. if ( geometry.boundingBox !== null ) {
  5847. this.boundingBox = geometry.boundingBox.clone();
  5848. }
  5849. if ( geometry.boundingSphere !== null ) {
  5850. this.boundingSphere = geometry.boundingSphere.clone();
  5851. }
  5852. return this;
  5853. },
  5854. center: function () {
  5855. this.computeBoundingBox();
  5856. var offset = this.boundingBox.center().negate();
  5857. this.translate( offset.x, offset.y, offset.z );
  5858. return offset;
  5859. },
  5860. normalize: function () {
  5861. this.computeBoundingSphere();
  5862. var center = this.boundingSphere.center;
  5863. var radius = this.boundingSphere.radius;
  5864. var s = radius === 0 ? 1 : 1.0 / radius;
  5865. var matrix = new THREE.Matrix4();
  5866. matrix.set(
  5867. s, 0, 0, - s * center.x,
  5868. 0, s, 0, - s * center.y,
  5869. 0, 0, s, - s * center.z,
  5870. 0, 0, 0, 1
  5871. );
  5872. this.applyMatrix( matrix );
  5873. return this;
  5874. },
  5875. computeFaceNormals: function () {
  5876. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5877. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5878. var face = this.faces[ f ];
  5879. var vA = this.vertices[ face.a ];
  5880. var vB = this.vertices[ face.b ];
  5881. var vC = this.vertices[ face.c ];
  5882. cb.subVectors( vC, vB );
  5883. ab.subVectors( vA, vB );
  5884. cb.cross( ab );
  5885. cb.normalize();
  5886. face.normal.copy( cb );
  5887. }
  5888. },
  5889. computeVertexNormals: function ( areaWeighted ) {
  5890. var v, vl, f, fl, face, vertices;
  5891. vertices = new Array( this.vertices.length );
  5892. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5893. vertices[ v ] = new THREE.Vector3();
  5894. }
  5895. if ( areaWeighted ) {
  5896. // vertex normals weighted by triangle areas
  5897. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5898. var vA, vB, vC;
  5899. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5900. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5901. face = this.faces[ f ];
  5902. vA = this.vertices[ face.a ];
  5903. vB = this.vertices[ face.b ];
  5904. vC = this.vertices[ face.c ];
  5905. cb.subVectors( vC, vB );
  5906. ab.subVectors( vA, vB );
  5907. cb.cross( ab );
  5908. vertices[ face.a ].add( cb );
  5909. vertices[ face.b ].add( cb );
  5910. vertices[ face.c ].add( cb );
  5911. }
  5912. } else {
  5913. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5914. face = this.faces[ f ];
  5915. vertices[ face.a ].add( face.normal );
  5916. vertices[ face.b ].add( face.normal );
  5917. vertices[ face.c ].add( face.normal );
  5918. }
  5919. }
  5920. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5921. vertices[ v ].normalize();
  5922. }
  5923. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5924. face = this.faces[ f ];
  5925. var vertexNormals = face.vertexNormals;
  5926. if ( vertexNormals.length === 3 ) {
  5927. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  5928. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  5929. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  5930. } else {
  5931. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  5932. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  5933. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  5934. }
  5935. }
  5936. },
  5937. computeMorphNormals: function () {
  5938. var i, il, f, fl, face;
  5939. // save original normals
  5940. // - create temp variables on first access
  5941. // otherwise just copy (for faster repeated calls)
  5942. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5943. face = this.faces[ f ];
  5944. if ( ! face.__originalFaceNormal ) {
  5945. face.__originalFaceNormal = face.normal.clone();
  5946. } else {
  5947. face.__originalFaceNormal.copy( face.normal );
  5948. }
  5949. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5950. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5951. if ( ! face.__originalVertexNormals[ i ] ) {
  5952. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5953. } else {
  5954. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  5955. }
  5956. }
  5957. }
  5958. // use temp geometry to compute face and vertex normals for each morph
  5959. var tmpGeo = new THREE.Geometry();
  5960. tmpGeo.faces = this.faces;
  5961. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  5962. // create on first access
  5963. if ( ! this.morphNormals[ i ] ) {
  5964. this.morphNormals[ i ] = {};
  5965. this.morphNormals[ i ].faceNormals = [];
  5966. this.morphNormals[ i ].vertexNormals = [];
  5967. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  5968. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  5969. var faceNormal, vertexNormals;
  5970. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5971. faceNormal = new THREE.Vector3();
  5972. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5973. dstNormalsFace.push( faceNormal );
  5974. dstNormalsVertex.push( vertexNormals );
  5975. }
  5976. }
  5977. var morphNormals = this.morphNormals[ i ];
  5978. // set vertices to morph target
  5979. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5980. // compute morph normals
  5981. tmpGeo.computeFaceNormals();
  5982. tmpGeo.computeVertexNormals();
  5983. // store morph normals
  5984. var faceNormal, vertexNormals;
  5985. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5986. face = this.faces[ f ];
  5987. faceNormal = morphNormals.faceNormals[ f ];
  5988. vertexNormals = morphNormals.vertexNormals[ f ];
  5989. faceNormal.copy( face.normal );
  5990. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5991. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5992. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5993. }
  5994. }
  5995. // restore original normals
  5996. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5997. face = this.faces[ f ];
  5998. face.normal = face.__originalFaceNormal;
  5999. face.vertexNormals = face.__originalVertexNormals;
  6000. }
  6001. },
  6002. computeTangents: function () {
  6003. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  6004. },
  6005. computeLineDistances: function () {
  6006. var d = 0;
  6007. var vertices = this.vertices;
  6008. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6009. if ( i > 0 ) {
  6010. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  6011. }
  6012. this.lineDistances[ i ] = d;
  6013. }
  6014. },
  6015. computeBoundingBox: function () {
  6016. if ( this.boundingBox === null ) {
  6017. this.boundingBox = new THREE.Box3();
  6018. }
  6019. this.boundingBox.setFromPoints( this.vertices );
  6020. },
  6021. computeBoundingSphere: function () {
  6022. if ( this.boundingSphere === null ) {
  6023. this.boundingSphere = new THREE.Sphere();
  6024. }
  6025. this.boundingSphere.setFromPoints( this.vertices );
  6026. },
  6027. merge: function ( geometry, matrix, materialIndexOffset ) {
  6028. if ( geometry instanceof THREE.Geometry === false ) {
  6029. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  6030. return;
  6031. }
  6032. var normalMatrix,
  6033. vertexOffset = this.vertices.length,
  6034. vertices1 = this.vertices,
  6035. vertices2 = geometry.vertices,
  6036. faces1 = this.faces,
  6037. faces2 = geometry.faces,
  6038. uvs1 = this.faceVertexUvs[ 0 ],
  6039. uvs2 = geometry.faceVertexUvs[ 0 ];
  6040. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  6041. if ( matrix !== undefined ) {
  6042. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  6043. }
  6044. // vertices
  6045. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  6046. var vertex = vertices2[ i ];
  6047. var vertexCopy = vertex.clone();
  6048. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  6049. vertices1.push( vertexCopy );
  6050. }
  6051. // faces
  6052. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  6053. var face = faces2[ i ], faceCopy, normal, color,
  6054. faceVertexNormals = face.vertexNormals,
  6055. faceVertexColors = face.vertexColors;
  6056. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  6057. faceCopy.normal.copy( face.normal );
  6058. if ( normalMatrix !== undefined ) {
  6059. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  6060. }
  6061. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  6062. normal = faceVertexNormals[ j ].clone();
  6063. if ( normalMatrix !== undefined ) {
  6064. normal.applyMatrix3( normalMatrix ).normalize();
  6065. }
  6066. faceCopy.vertexNormals.push( normal );
  6067. }
  6068. faceCopy.color.copy( face.color );
  6069. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  6070. color = faceVertexColors[ j ];
  6071. faceCopy.vertexColors.push( color.clone() );
  6072. }
  6073. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  6074. faces1.push( faceCopy );
  6075. }
  6076. // uvs
  6077. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  6078. var uv = uvs2[ i ], uvCopy = [];
  6079. if ( uv === undefined ) {
  6080. continue;
  6081. }
  6082. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  6083. uvCopy.push( uv[ j ].clone() );
  6084. }
  6085. uvs1.push( uvCopy );
  6086. }
  6087. },
  6088. mergeMesh: function ( mesh ) {
  6089. if ( mesh instanceof THREE.Mesh === false ) {
  6090. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  6091. return;
  6092. }
  6093. mesh.matrixAutoUpdate && mesh.updateMatrix();
  6094. this.merge( mesh.geometry, mesh.matrix );
  6095. },
  6096. /*
  6097. * Checks for duplicate vertices with hashmap.
  6098. * Duplicated vertices are removed
  6099. * and faces' vertices are updated.
  6100. */
  6101. mergeVertices: function () {
  6102. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  6103. var unique = [], changes = [];
  6104. var v, key;
  6105. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  6106. var precision = Math.pow( 10, precisionPoints );
  6107. var i, il, face;
  6108. var indices, j, jl;
  6109. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  6110. v = this.vertices[ i ];
  6111. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  6112. if ( verticesMap[ key ] === undefined ) {
  6113. verticesMap[ key ] = i;
  6114. unique.push( this.vertices[ i ] );
  6115. changes[ i ] = unique.length - 1;
  6116. } else {
  6117. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  6118. changes[ i ] = changes[ verticesMap[ key ] ];
  6119. }
  6120. }
  6121. // if faces are completely degenerate after merging vertices, we
  6122. // have to remove them from the geometry.
  6123. var faceIndicesToRemove = [];
  6124. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  6125. face = this.faces[ i ];
  6126. face.a = changes[ face.a ];
  6127. face.b = changes[ face.b ];
  6128. face.c = changes[ face.c ];
  6129. indices = [ face.a, face.b, face.c ];
  6130. var dupIndex = - 1;
  6131. // if any duplicate vertices are found in a Face3
  6132. // we have to remove the face as nothing can be saved
  6133. for ( var n = 0; n < 3; n ++ ) {
  6134. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  6135. dupIndex = n;
  6136. faceIndicesToRemove.push( i );
  6137. break;
  6138. }
  6139. }
  6140. }
  6141. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  6142. var idx = faceIndicesToRemove[ i ];
  6143. this.faces.splice( idx, 1 );
  6144. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  6145. this.faceVertexUvs[ j ].splice( idx, 1 );
  6146. }
  6147. }
  6148. // Use unique set of vertices
  6149. var diff = this.vertices.length - unique.length;
  6150. this.vertices = unique;
  6151. return diff;
  6152. },
  6153. sortFacesByMaterialIndex: function () {
  6154. var faces = this.faces;
  6155. var length = faces.length;
  6156. // tag faces
  6157. for ( var i = 0; i < length; i ++ ) {
  6158. faces[ i ]._id = i;
  6159. }
  6160. // sort faces
  6161. function materialIndexSort( a, b ) {
  6162. return a.materialIndex - b.materialIndex;
  6163. }
  6164. faces.sort( materialIndexSort );
  6165. // sort uvs
  6166. var uvs1 = this.faceVertexUvs[ 0 ];
  6167. var uvs2 = this.faceVertexUvs[ 1 ];
  6168. var newUvs1, newUvs2;
  6169. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  6170. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  6171. for ( var i = 0; i < length; i ++ ) {
  6172. var id = faces[ i ]._id;
  6173. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  6174. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  6175. }
  6176. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  6177. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  6178. },
  6179. toJSON: function () {
  6180. var data = {
  6181. metadata: {
  6182. version: 4.4,
  6183. type: 'Geometry',
  6184. generator: 'Geometry.toJSON'
  6185. }
  6186. };
  6187. // standard Geometry serialization
  6188. data.uuid = this.uuid;
  6189. data.type = this.type;
  6190. if ( this.name !== '' ) data.name = this.name;
  6191. if ( this.parameters !== undefined ) {
  6192. var parameters = this.parameters;
  6193. for ( var key in parameters ) {
  6194. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6195. }
  6196. return data;
  6197. }
  6198. var vertices = [];
  6199. for ( var i = 0; i < this.vertices.length; i ++ ) {
  6200. var vertex = this.vertices[ i ];
  6201. vertices.push( vertex.x, vertex.y, vertex.z );
  6202. }
  6203. var faces = [];
  6204. var normals = [];
  6205. var normalsHash = {};
  6206. var colors = [];
  6207. var colorsHash = {};
  6208. var uvs = [];
  6209. var uvsHash = {};
  6210. for ( var i = 0; i < this.faces.length; i ++ ) {
  6211. var face = this.faces[ i ];
  6212. var hasMaterial = true;
  6213. var hasFaceUv = false; // deprecated
  6214. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  6215. var hasFaceNormal = face.normal.length() > 0;
  6216. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  6217. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  6218. var hasFaceVertexColor = face.vertexColors.length > 0;
  6219. var faceType = 0;
  6220. faceType = setBit( faceType, 0, 0 ); // isQuad
  6221. faceType = setBit( faceType, 1, hasMaterial );
  6222. faceType = setBit( faceType, 2, hasFaceUv );
  6223. faceType = setBit( faceType, 3, hasFaceVertexUv );
  6224. faceType = setBit( faceType, 4, hasFaceNormal );
  6225. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  6226. faceType = setBit( faceType, 6, hasFaceColor );
  6227. faceType = setBit( faceType, 7, hasFaceVertexColor );
  6228. faces.push( faceType );
  6229. faces.push( face.a, face.b, face.c );
  6230. faces.push( face.materialIndex );
  6231. if ( hasFaceVertexUv ) {
  6232. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  6233. faces.push(
  6234. getUvIndex( faceVertexUvs[ 0 ] ),
  6235. getUvIndex( faceVertexUvs[ 1 ] ),
  6236. getUvIndex( faceVertexUvs[ 2 ] )
  6237. );
  6238. }
  6239. if ( hasFaceNormal ) {
  6240. faces.push( getNormalIndex( face.normal ) );
  6241. }
  6242. if ( hasFaceVertexNormal ) {
  6243. var vertexNormals = face.vertexNormals;
  6244. faces.push(
  6245. getNormalIndex( vertexNormals[ 0 ] ),
  6246. getNormalIndex( vertexNormals[ 1 ] ),
  6247. getNormalIndex( vertexNormals[ 2 ] )
  6248. );
  6249. }
  6250. if ( hasFaceColor ) {
  6251. faces.push( getColorIndex( face.color ) );
  6252. }
  6253. if ( hasFaceVertexColor ) {
  6254. var vertexColors = face.vertexColors;
  6255. faces.push(
  6256. getColorIndex( vertexColors[ 0 ] ),
  6257. getColorIndex( vertexColors[ 1 ] ),
  6258. getColorIndex( vertexColors[ 2 ] )
  6259. );
  6260. }
  6261. }
  6262. function setBit( value, position, enabled ) {
  6263. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  6264. }
  6265. function getNormalIndex( normal ) {
  6266. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  6267. if ( normalsHash[ hash ] !== undefined ) {
  6268. return normalsHash[ hash ];
  6269. }
  6270. normalsHash[ hash ] = normals.length / 3;
  6271. normals.push( normal.x, normal.y, normal.z );
  6272. return normalsHash[ hash ];
  6273. }
  6274. function getColorIndex( color ) {
  6275. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  6276. if ( colorsHash[ hash ] !== undefined ) {
  6277. return colorsHash[ hash ];
  6278. }
  6279. colorsHash[ hash ] = colors.length;
  6280. colors.push( color.getHex() );
  6281. return colorsHash[ hash ];
  6282. }
  6283. function getUvIndex( uv ) {
  6284. var hash = uv.x.toString() + uv.y.toString();
  6285. if ( uvsHash[ hash ] !== undefined ) {
  6286. return uvsHash[ hash ];
  6287. }
  6288. uvsHash[ hash ] = uvs.length / 2;
  6289. uvs.push( uv.x, uv.y );
  6290. return uvsHash[ hash ];
  6291. }
  6292. data.data = {};
  6293. data.data.vertices = vertices;
  6294. data.data.normals = normals;
  6295. if ( colors.length > 0 ) data.data.colors = colors;
  6296. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  6297. data.data.faces = faces;
  6298. return data;
  6299. },
  6300. clone: function () {
  6301. // Handle primitives
  6302. var parameters = this.parameters;
  6303. if ( parameters !== undefined ) {
  6304. var values = [];
  6305. for ( var key in parameters ) {
  6306. values.push( parameters[ key ] );
  6307. }
  6308. var geometry = Object.create( this.constructor.prototype );
  6309. this.constructor.apply( geometry, values );
  6310. return geometry;
  6311. }
  6312. return new this.constructor().copy( this );
  6313. },
  6314. copy: function ( source ) {
  6315. this.vertices = [];
  6316. this.faces = [];
  6317. this.faceVertexUvs = [ [] ];
  6318. var vertices = source.vertices;
  6319. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6320. this.vertices.push( vertices[ i ].clone() );
  6321. }
  6322. var faces = source.faces;
  6323. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  6324. this.faces.push( faces[ i ].clone() );
  6325. }
  6326. for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  6327. var faceVertexUvs = source.faceVertexUvs[ i ];
  6328. if ( this.faceVertexUvs[ i ] === undefined ) {
  6329. this.faceVertexUvs[ i ] = [];
  6330. }
  6331. for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  6332. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  6333. for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
  6334. var uv = uvs[ k ];
  6335. uvsCopy.push( uv.clone() );
  6336. }
  6337. this.faceVertexUvs[ i ].push( uvsCopy );
  6338. }
  6339. }
  6340. return this;
  6341. },
  6342. dispose: function () {
  6343. this.dispatchEvent( { type: 'dispose' } );
  6344. }
  6345. };
  6346. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  6347. THREE.GeometryIdCount = 0;
  6348. // File:src/core/DirectGeometry.js
  6349. /**
  6350. * @author mrdoob / http://mrdoob.com/
  6351. */
  6352. THREE.DirectGeometry = function () {
  6353. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  6354. this.uuid = THREE.Math.generateUUID();
  6355. this.name = '';
  6356. this.type = 'DirectGeometry';
  6357. this.indices = [];
  6358. this.vertices = [];
  6359. this.normals = [];
  6360. this.colors = [];
  6361. this.uvs = [];
  6362. this.uvs2 = [];
  6363. this.groups = [];
  6364. this.morphTargets = {};
  6365. this.skinWeights = [];
  6366. this.skinIndices = [];
  6367. // this.lineDistances = [];
  6368. this.boundingBox = null;
  6369. this.boundingSphere = null;
  6370. // update flags
  6371. this.verticesNeedUpdate = false;
  6372. this.normalsNeedUpdate = false;
  6373. this.colorsNeedUpdate = false;
  6374. this.uvsNeedUpdate = false;
  6375. this.groupsNeedUpdate = false;
  6376. };
  6377. THREE.DirectGeometry.prototype = {
  6378. constructor: THREE.DirectGeometry,
  6379. computeBoundingBox: THREE.Geometry.prototype.computeBoundingBox,
  6380. computeBoundingSphere: THREE.Geometry.prototype.computeBoundingSphere,
  6381. computeFaceNormals: function () {
  6382. console.warn( 'THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.' );
  6383. },
  6384. computeVertexNormals: function () {
  6385. console.warn( 'THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.' );
  6386. },
  6387. computeGroups: function ( geometry ) {
  6388. var group;
  6389. var groups = [];
  6390. var materialIndex;
  6391. var faces = geometry.faces;
  6392. for ( var i = 0; i < faces.length; i ++ ) {
  6393. var face = faces[ i ];
  6394. // materials
  6395. if ( face.materialIndex !== materialIndex ) {
  6396. materialIndex = face.materialIndex;
  6397. if ( group !== undefined ) {
  6398. group.count = ( i * 3 ) - group.start;
  6399. groups.push( group );
  6400. }
  6401. group = {
  6402. start: i * 3,
  6403. materialIndex: materialIndex
  6404. };
  6405. }
  6406. }
  6407. if ( group !== undefined ) {
  6408. group.count = ( i * 3 ) - group.start;
  6409. groups.push( group );
  6410. }
  6411. this.groups = groups;
  6412. },
  6413. fromGeometry: function ( geometry ) {
  6414. var faces = geometry.faces;
  6415. var vertices = geometry.vertices;
  6416. var faceVertexUvs = geometry.faceVertexUvs;
  6417. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  6418. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  6419. // morphs
  6420. var morphTargets = geometry.morphTargets;
  6421. var morphTargetsLength = morphTargets.length;
  6422. if ( morphTargetsLength > 0 ) {
  6423. var morphTargetsPosition = [];
  6424. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  6425. morphTargetsPosition[ i ] = [];
  6426. }
  6427. this.morphTargets.position = morphTargetsPosition;
  6428. }
  6429. var morphNormals = geometry.morphNormals;
  6430. var morphNormalsLength = morphNormals.length;
  6431. if ( morphNormalsLength > 0 ) {
  6432. var morphTargetsNormal = [];
  6433. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  6434. morphTargetsNormal[ i ] = [];
  6435. }
  6436. this.morphTargets.normal = morphTargetsNormal;
  6437. }
  6438. // skins
  6439. var skinIndices = geometry.skinIndices;
  6440. var skinWeights = geometry.skinWeights;
  6441. var hasSkinIndices = skinIndices.length === vertices.length;
  6442. var hasSkinWeights = skinWeights.length === vertices.length;
  6443. //
  6444. for ( var i = 0; i < faces.length; i ++ ) {
  6445. var face = faces[ i ];
  6446. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  6447. var vertexNormals = face.vertexNormals;
  6448. if ( vertexNormals.length === 3 ) {
  6449. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  6450. } else {
  6451. var normal = face.normal;
  6452. this.normals.push( normal, normal, normal );
  6453. }
  6454. var vertexColors = face.vertexColors;
  6455. if ( vertexColors.length === 3 ) {
  6456. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  6457. } else {
  6458. var color = face.color;
  6459. this.colors.push( color, color, color );
  6460. }
  6461. if ( hasFaceVertexUv === true ) {
  6462. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  6463. if ( vertexUvs !== undefined ) {
  6464. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  6465. } else {
  6466. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  6467. this.uvs.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() );
  6468. }
  6469. }
  6470. if ( hasFaceVertexUv2 === true ) {
  6471. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  6472. if ( vertexUvs !== undefined ) {
  6473. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  6474. } else {
  6475. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  6476. this.uvs2.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() );
  6477. }
  6478. }
  6479. // morphs
  6480. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  6481. var morphTarget = morphTargets[ j ].vertices;
  6482. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  6483. }
  6484. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  6485. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  6486. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  6487. }
  6488. // skins
  6489. if ( hasSkinIndices ) {
  6490. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  6491. }
  6492. if ( hasSkinWeights ) {
  6493. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  6494. }
  6495. }
  6496. this.computeGroups( geometry );
  6497. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6498. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6499. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6500. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6501. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6502. return this;
  6503. },
  6504. dispose: function () {
  6505. this.dispatchEvent( { type: 'dispose' } );
  6506. }
  6507. };
  6508. THREE.EventDispatcher.prototype.apply( THREE.DirectGeometry.prototype );
  6509. // File:src/core/BufferGeometry.js
  6510. /**
  6511. * @author alteredq / http://alteredqualia.com/
  6512. * @author mrdoob / http://mrdoob.com/
  6513. */
  6514. THREE.BufferGeometry = function () {
  6515. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  6516. this.uuid = THREE.Math.generateUUID();
  6517. this.name = '';
  6518. this.type = 'BufferGeometry';
  6519. this.index = null;
  6520. this.attributes = {};
  6521. this.morphAttributes = {};
  6522. this.groups = [];
  6523. this.boundingBox = null;
  6524. this.boundingSphere = null;
  6525. this.drawRange = { start: 0, count: Infinity };
  6526. };
  6527. THREE.BufferGeometry.prototype = {
  6528. constructor: THREE.BufferGeometry,
  6529. addIndex: function ( index ) {
  6530. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  6531. this.setIndex( index );
  6532. },
  6533. getIndex: function () {
  6534. return this.index;
  6535. },
  6536. setIndex: function ( index ) {
  6537. this.index = index;
  6538. },
  6539. addAttribute: function ( name, attribute ) {
  6540. if ( attribute instanceof THREE.BufferAttribute === false && attribute instanceof THREE.InterleavedBufferAttribute === false ) {
  6541. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  6542. this.addAttribute( name, new THREE.BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  6543. return;
  6544. }
  6545. if ( name === 'index' ) {
  6546. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  6547. this.setIndex( attribute );
  6548. return;
  6549. }
  6550. this.attributes[ name ] = attribute;
  6551. },
  6552. getAttribute: function ( name ) {
  6553. return this.attributes[ name ];
  6554. },
  6555. removeAttribute: function ( name ) {
  6556. delete this.attributes[ name ];
  6557. },
  6558. get drawcalls() {
  6559. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  6560. return this.groups;
  6561. },
  6562. get offsets() {
  6563. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  6564. return this.groups;
  6565. },
  6566. addDrawCall: function ( start, count, indexOffset ) {
  6567. if ( indexOffset !== undefined ) {
  6568. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  6569. }
  6570. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  6571. this.addGroup( start, count );
  6572. },
  6573. clearDrawCalls: function () {
  6574. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  6575. this.clearGroups();
  6576. },
  6577. addGroup: function ( start, count, materialIndex ) {
  6578. this.groups.push( {
  6579. start: start,
  6580. count: count,
  6581. materialIndex: materialIndex !== undefined ? materialIndex : 0
  6582. } );
  6583. },
  6584. clearGroups: function () {
  6585. this.groups = [];
  6586. },
  6587. setDrawRange: function ( start, count ) {
  6588. this.drawRange.start = start;
  6589. this.drawRange.count = count;
  6590. },
  6591. applyMatrix: function ( matrix ) {
  6592. var position = this.attributes.position;
  6593. if ( position !== undefined ) {
  6594. matrix.applyToVector3Array( position.array );
  6595. position.needsUpdate = true;
  6596. }
  6597. var normal = this.attributes.normal;
  6598. if ( normal !== undefined ) {
  6599. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  6600. normalMatrix.applyToVector3Array( normal.array );
  6601. normal.needsUpdate = true;
  6602. }
  6603. if ( this.boundingBox !== null ) {
  6604. this.computeBoundingBox();
  6605. }
  6606. if ( this.boundingSphere !== null ) {
  6607. this.computeBoundingSphere();
  6608. }
  6609. },
  6610. rotateX: function () {
  6611. // rotate geometry around world x-axis
  6612. var m1;
  6613. return function rotateX( angle ) {
  6614. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6615. m1.makeRotationX( angle );
  6616. this.applyMatrix( m1 );
  6617. return this;
  6618. };
  6619. }(),
  6620. rotateY: function () {
  6621. // rotate geometry around world y-axis
  6622. var m1;
  6623. return function rotateY( angle ) {
  6624. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6625. m1.makeRotationY( angle );
  6626. this.applyMatrix( m1 );
  6627. return this;
  6628. };
  6629. }(),
  6630. rotateZ: function () {
  6631. // rotate geometry around world z-axis
  6632. var m1;
  6633. return function rotateZ( angle ) {
  6634. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6635. m1.makeRotationZ( angle );
  6636. this.applyMatrix( m1 );
  6637. return this;
  6638. };
  6639. }(),
  6640. translate: function () {
  6641. // translate geometry
  6642. var m1;
  6643. return function translate( x, y, z ) {
  6644. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6645. m1.makeTranslation( x, y, z );
  6646. this.applyMatrix( m1 );
  6647. return this;
  6648. };
  6649. }(),
  6650. scale: function () {
  6651. // scale geometry
  6652. var m1;
  6653. return function scale( x, y, z ) {
  6654. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6655. m1.makeScale( x, y, z );
  6656. this.applyMatrix( m1 );
  6657. return this;
  6658. };
  6659. }(),
  6660. lookAt: function () {
  6661. var obj;
  6662. return function lookAt( vector ) {
  6663. if ( obj === undefined ) obj = new THREE.Object3D();
  6664. obj.lookAt( vector );
  6665. obj.updateMatrix();
  6666. this.applyMatrix( obj.matrix );
  6667. };
  6668. }(),
  6669. center: function () {
  6670. this.computeBoundingBox();
  6671. var offset = this.boundingBox.center().negate();
  6672. this.translate( offset.x, offset.y, offset.z );
  6673. return offset;
  6674. },
  6675. setFromObject: function ( object ) {
  6676. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  6677. var geometry = object.geometry;
  6678. if ( object instanceof THREE.Points || object instanceof THREE.Line ) {
  6679. var positions = new THREE.Float32Attribute( geometry.vertices.length * 3, 3 );
  6680. var colors = new THREE.Float32Attribute( geometry.colors.length * 3, 3 );
  6681. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  6682. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  6683. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  6684. var lineDistances = new THREE.Float32Attribute( geometry.lineDistances.length, 1 );
  6685. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  6686. }
  6687. if ( geometry.boundingSphere !== null ) {
  6688. this.boundingSphere = geometry.boundingSphere.clone();
  6689. }
  6690. if ( geometry.boundingBox !== null ) {
  6691. this.boundingBox = geometry.boundingBox.clone();
  6692. }
  6693. } else if ( object instanceof THREE.Mesh ) {
  6694. if ( geometry instanceof THREE.Geometry ) {
  6695. this.fromGeometry( geometry );
  6696. }
  6697. }
  6698. return this;
  6699. },
  6700. updateFromObject: function ( object ) {
  6701. var geometry = object.geometry;
  6702. if ( object instanceof THREE.Mesh ) {
  6703. var direct = geometry.__directGeometry;
  6704. if ( direct === undefined ) {
  6705. return this.fromGeometry( geometry );
  6706. }
  6707. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6708. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6709. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6710. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6711. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6712. geometry.verticesNeedUpdate = false;
  6713. geometry.normalsNeedUpdate = false;
  6714. geometry.colorsNeedUpdate = false;
  6715. geometry.uvsNeedUpdate = false;
  6716. geometry.groupsNeedUpdate = false;
  6717. geometry = direct;
  6718. }
  6719. if ( geometry.verticesNeedUpdate === true ) {
  6720. var attribute = this.attributes.position;
  6721. if ( attribute !== undefined ) {
  6722. attribute.copyVector3sArray( geometry.vertices );
  6723. attribute.needsUpdate = true;
  6724. }
  6725. geometry.verticesNeedUpdate = false;
  6726. }
  6727. if ( geometry.normalsNeedUpdate === true ) {
  6728. var attribute = this.attributes.normal;
  6729. if ( attribute !== undefined ) {
  6730. attribute.copyVector3sArray( geometry.normals );
  6731. attribute.needsUpdate = true;
  6732. }
  6733. geometry.normalsNeedUpdate = false;
  6734. }
  6735. if ( geometry.colorsNeedUpdate === true ) {
  6736. var attribute = this.attributes.color;
  6737. if ( attribute !== undefined ) {
  6738. attribute.copyColorsArray( geometry.colors );
  6739. attribute.needsUpdate = true;
  6740. }
  6741. geometry.colorsNeedUpdate = false;
  6742. }
  6743. if ( geometry.uvsNeedUpdate ) {
  6744. var attribute = this.attributes.uv;
  6745. if ( attribute !== undefined ) {
  6746. attribute.copyVector2sArray( geometry.uvs );
  6747. attribute.needsUpdate = true;
  6748. }
  6749. geometry.uvsNeedUpdate = false;
  6750. }
  6751. if ( geometry.lineDistancesNeedUpdate ) {
  6752. var attribute = this.attributes.lineDistance;
  6753. if ( attribute !== undefined ) {
  6754. attribute.copyArray( geometry.lineDistances );
  6755. attribute.needsUpdate = true;
  6756. }
  6757. geometry.lineDistancesNeedUpdate = false;
  6758. }
  6759. if ( geometry.groupsNeedUpdate ) {
  6760. geometry.computeGroups( object.geometry );
  6761. this.groups = geometry.groups;
  6762. geometry.groupsNeedUpdate = false;
  6763. }
  6764. return this;
  6765. },
  6766. fromGeometry: function ( geometry ) {
  6767. geometry.__directGeometry = new THREE.DirectGeometry().fromGeometry( geometry );
  6768. return this.fromDirectGeometry( geometry.__directGeometry );
  6769. },
  6770. fromDirectGeometry: function ( geometry ) {
  6771. var positions = new Float32Array( geometry.vertices.length * 3 );
  6772. this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  6773. if ( geometry.normals.length > 0 ) {
  6774. var normals = new Float32Array( geometry.normals.length * 3 );
  6775. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  6776. }
  6777. if ( geometry.colors.length > 0 ) {
  6778. var colors = new Float32Array( geometry.colors.length * 3 );
  6779. this.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  6780. }
  6781. if ( geometry.uvs.length > 0 ) {
  6782. var uvs = new Float32Array( geometry.uvs.length * 2 );
  6783. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  6784. }
  6785. if ( geometry.uvs2.length > 0 ) {
  6786. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  6787. this.addAttribute( 'uv2', new THREE.BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  6788. }
  6789. if ( geometry.indices.length > 0 ) {
  6790. var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array;
  6791. var indices = new TypeArray( geometry.indices.length * 3 );
  6792. this.setIndex( new THREE.BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  6793. }
  6794. // groups
  6795. this.groups = geometry.groups;
  6796. // morphs
  6797. for ( var name in geometry.morphTargets ) {
  6798. var array = [];
  6799. var morphTargets = geometry.morphTargets[ name ];
  6800. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  6801. var morphTarget = morphTargets[ i ];
  6802. var attribute = new THREE.Float32Attribute( morphTarget.length * 3, 3 );
  6803. array.push( attribute.copyVector3sArray( morphTarget ) );
  6804. }
  6805. this.morphAttributes[ name ] = array;
  6806. }
  6807. // skinning
  6808. if ( geometry.skinIndices.length > 0 ) {
  6809. var skinIndices = new THREE.Float32Attribute( geometry.skinIndices.length * 4, 4 );
  6810. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  6811. }
  6812. if ( geometry.skinWeights.length > 0 ) {
  6813. var skinWeights = new THREE.Float32Attribute( geometry.skinWeights.length * 4, 4 );
  6814. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  6815. }
  6816. //
  6817. if ( geometry.boundingSphere !== null ) {
  6818. this.boundingSphere = geometry.boundingSphere.clone();
  6819. }
  6820. if ( geometry.boundingBox !== null ) {
  6821. this.boundingBox = geometry.boundingBox.clone();
  6822. }
  6823. return this;
  6824. },
  6825. computeBoundingBox: function () {
  6826. var vector = new THREE.Vector3();
  6827. return function () {
  6828. if ( this.boundingBox === null ) {
  6829. this.boundingBox = new THREE.Box3();
  6830. }
  6831. var positions = this.attributes.position.array;
  6832. if ( positions ) {
  6833. var bb = this.boundingBox;
  6834. bb.makeEmpty();
  6835. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  6836. vector.fromArray( positions, i );
  6837. bb.expandByPoint( vector );
  6838. }
  6839. }
  6840. if ( positions === undefined || positions.length === 0 ) {
  6841. this.boundingBox.min.set( 0, 0, 0 );
  6842. this.boundingBox.max.set( 0, 0, 0 );
  6843. }
  6844. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6845. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6846. }
  6847. };
  6848. }(),
  6849. computeBoundingSphere: function () {
  6850. var box = new THREE.Box3();
  6851. var vector = new THREE.Vector3();
  6852. return function () {
  6853. if ( this.boundingSphere === null ) {
  6854. this.boundingSphere = new THREE.Sphere();
  6855. }
  6856. var positions = this.attributes.position.array;
  6857. if ( positions ) {
  6858. box.makeEmpty();
  6859. var center = this.boundingSphere.center;
  6860. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  6861. vector.fromArray( positions, i );
  6862. box.expandByPoint( vector );
  6863. }
  6864. box.center( center );
  6865. // hoping to find a boundingSphere with a radius smaller than the
  6866. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6867. var maxRadiusSq = 0;
  6868. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  6869. vector.fromArray( positions, i );
  6870. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  6871. }
  6872. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6873. if ( isNaN( this.boundingSphere.radius ) ) {
  6874. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6875. }
  6876. }
  6877. };
  6878. }(),
  6879. computeFaceNormals: function () {
  6880. // backwards compatibility
  6881. },
  6882. computeVertexNormals: function () {
  6883. var index = this.index;
  6884. var attributes = this.attributes;
  6885. var groups = this.groups;
  6886. if ( attributes.position ) {
  6887. var positions = attributes.position.array;
  6888. if ( attributes.normal === undefined ) {
  6889. this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( positions.length ), 3 ) );
  6890. } else {
  6891. // reset existing normals to zero
  6892. var normals = attributes.normal.array;
  6893. for ( var i = 0, il = normals.length; i < il; i ++ ) {
  6894. normals[ i ] = 0;
  6895. }
  6896. }
  6897. var normals = attributes.normal.array;
  6898. var vA, vB, vC,
  6899. pA = new THREE.Vector3(),
  6900. pB = new THREE.Vector3(),
  6901. pC = new THREE.Vector3(),
  6902. cb = new THREE.Vector3(),
  6903. ab = new THREE.Vector3();
  6904. // indexed elements
  6905. if ( index ) {
  6906. var indices = index.array;
  6907. if ( groups.length === 0 ) {
  6908. this.addGroup( 0, indices.length );
  6909. }
  6910. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  6911. var group = groups[ j ];
  6912. var start = group.start;
  6913. var count = group.count;
  6914. for ( var i = start, il = start + count; i < il; i += 3 ) {
  6915. vA = indices[ i + 0 ] * 3;
  6916. vB = indices[ i + 1 ] * 3;
  6917. vC = indices[ i + 2 ] * 3;
  6918. pA.fromArray( positions, vA );
  6919. pB.fromArray( positions, vB );
  6920. pC.fromArray( positions, vC );
  6921. cb.subVectors( pC, pB );
  6922. ab.subVectors( pA, pB );
  6923. cb.cross( ab );
  6924. normals[ vA ] += cb.x;
  6925. normals[ vA + 1 ] += cb.y;
  6926. normals[ vA + 2 ] += cb.z;
  6927. normals[ vB ] += cb.x;
  6928. normals[ vB + 1 ] += cb.y;
  6929. normals[ vB + 2 ] += cb.z;
  6930. normals[ vC ] += cb.x;
  6931. normals[ vC + 1 ] += cb.y;
  6932. normals[ vC + 2 ] += cb.z;
  6933. }
  6934. }
  6935. } else {
  6936. // non-indexed elements (unconnected triangle soup)
  6937. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  6938. pA.fromArray( positions, i );
  6939. pB.fromArray( positions, i + 3 );
  6940. pC.fromArray( positions, i + 6 );
  6941. cb.subVectors( pC, pB );
  6942. ab.subVectors( pA, pB );
  6943. cb.cross( ab );
  6944. normals[ i ] = cb.x;
  6945. normals[ i + 1 ] = cb.y;
  6946. normals[ i + 2 ] = cb.z;
  6947. normals[ i + 3 ] = cb.x;
  6948. normals[ i + 4 ] = cb.y;
  6949. normals[ i + 5 ] = cb.z;
  6950. normals[ i + 6 ] = cb.x;
  6951. normals[ i + 7 ] = cb.y;
  6952. normals[ i + 8 ] = cb.z;
  6953. }
  6954. }
  6955. this.normalizeNormals();
  6956. attributes.normal.needsUpdate = true;
  6957. }
  6958. },
  6959. computeTangents: function () {
  6960. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  6961. },
  6962. computeOffsets: function ( size ) {
  6963. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.');
  6964. },
  6965. merge: function ( geometry, offset ) {
  6966. if ( geometry instanceof THREE.BufferGeometry === false ) {
  6967. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  6968. return;
  6969. }
  6970. if ( offset === undefined ) offset = 0;
  6971. var attributes = this.attributes;
  6972. for ( var key in attributes ) {
  6973. if ( geometry.attributes[ key ] === undefined ) continue;
  6974. var attribute1 = attributes[ key ];
  6975. var attributeArray1 = attribute1.array;
  6976. var attribute2 = geometry.attributes[ key ];
  6977. var attributeArray2 = attribute2.array;
  6978. var attributeSize = attribute2.itemSize;
  6979. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  6980. attributeArray1[ j ] = attributeArray2[ i ];
  6981. }
  6982. }
  6983. return this;
  6984. },
  6985. normalizeNormals: function () {
  6986. var normals = this.attributes.normal.array;
  6987. var x, y, z, n;
  6988. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  6989. x = normals[ i ];
  6990. y = normals[ i + 1 ];
  6991. z = normals[ i + 2 ];
  6992. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  6993. normals[ i ] *= n;
  6994. normals[ i + 1 ] *= n;
  6995. normals[ i + 2 ] *= n;
  6996. }
  6997. },
  6998. toJSON: function () {
  6999. var data = {
  7000. metadata: {
  7001. version: 4.4,
  7002. type: 'BufferGeometry',
  7003. generator: 'BufferGeometry.toJSON'
  7004. }
  7005. };
  7006. // standard BufferGeometry serialization
  7007. data.uuid = this.uuid;
  7008. data.type = this.type;
  7009. if ( this.name !== '' ) data.name = this.name;
  7010. if ( this.parameters !== undefined ) {
  7011. var parameters = this.parameters;
  7012. for ( var key in parameters ) {
  7013. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  7014. }
  7015. return data;
  7016. }
  7017. data.data = { attributes: {} };
  7018. var index = this.index;
  7019. if ( index !== null ) {
  7020. var array = Array.prototype.slice.call( index.array );
  7021. data.data.index = {
  7022. type: index.array.constructor.name,
  7023. array: array
  7024. };
  7025. }
  7026. var attributes = this.attributes;
  7027. for ( var key in attributes ) {
  7028. var attribute = attributes[ key ];
  7029. var array = Array.prototype.slice.call( attribute.array );
  7030. data.data.attributes[ key ] = {
  7031. itemSize: attribute.itemSize,
  7032. type: attribute.array.constructor.name,
  7033. array: array
  7034. };
  7035. }
  7036. var groups = this.groups;
  7037. if ( groups.length > 0 ) {
  7038. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  7039. }
  7040. var boundingSphere = this.boundingSphere;
  7041. if ( boundingSphere !== null ) {
  7042. data.data.boundingSphere = {
  7043. center: boundingSphere.center.toArray(),
  7044. radius: boundingSphere.radius
  7045. };
  7046. }
  7047. return data;
  7048. },
  7049. clone: function () {
  7050. // Handle primitives
  7051. var parameters = this.parameters;
  7052. if ( parameters !== undefined ) {
  7053. var values = [];
  7054. for ( var key in parameters ) {
  7055. values.push( parameters[ key ] );
  7056. }
  7057. var geometry = Object.create( this.constructor.prototype );
  7058. this.constructor.apply( geometry, values );
  7059. return geometry;
  7060. }
  7061. return new this.constructor().copy( this );
  7062. },
  7063. copy: function ( source ) {
  7064. var index = source.index;
  7065. if ( index !== null ) {
  7066. this.setIndex( index.clone() );
  7067. }
  7068. var attributes = source.attributes;
  7069. for ( var name in attributes ) {
  7070. var attribute = attributes[ name ];
  7071. this.addAttribute( name, attribute.clone() );
  7072. }
  7073. var groups = source.groups;
  7074. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  7075. var group = groups[ i ];
  7076. this.addGroup( group.start, group.count );
  7077. }
  7078. return this;
  7079. },
  7080. dispose: function () {
  7081. this.dispatchEvent( { type: 'dispose' } );
  7082. }
  7083. };
  7084. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  7085. THREE.BufferGeometry.MaxIndex = 65535;
  7086. // File:src/core/InstancedBufferGeometry.js
  7087. /**
  7088. * @author benaadams / https://twitter.com/ben_a_adams
  7089. */
  7090. THREE.InstancedBufferGeometry = function () {
  7091. THREE.BufferGeometry.call( this );
  7092. this.type = 'InstancedBufferGeometry';
  7093. this.maxInstancedCount = undefined;
  7094. };
  7095. THREE.InstancedBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  7096. THREE.InstancedBufferGeometry.prototype.constructor = THREE.InstancedBufferGeometry;
  7097. THREE.InstancedBufferGeometry.prototype.addGroup = function ( start, count, instances ) {
  7098. this.groups.push( {
  7099. start: start,
  7100. count: count,
  7101. instances: instances
  7102. } );
  7103. };
  7104. THREE.InstancedBufferGeometry.prototype.copy = function ( source ) {
  7105. var index = source.index;
  7106. if ( index !== null ) {
  7107. this.setIndex( index.clone() );
  7108. }
  7109. var attributes = source.attributes;
  7110. for ( var name in attributes ) {
  7111. var attribute = attributes[ name ];
  7112. this.addAttribute( name, attribute.clone() );
  7113. }
  7114. var groups = source.groups;
  7115. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  7116. var group = groups[ i ];
  7117. this.addGroup( group.start, group.count, group.instances );
  7118. }
  7119. return this;
  7120. };
  7121. THREE.EventDispatcher.prototype.apply( THREE.InstancedBufferGeometry.prototype );
  7122. // File:src/animation/AnimationClip.js
  7123. /**
  7124. *
  7125. * Reusable set of Tracks that represent an animation.
  7126. *
  7127. * @author Ben Houston / http://clara.io/
  7128. * @author David Sarno / http://lighthaus.us/
  7129. */
  7130. THREE.AnimationClip = function ( name, duration, tracks ) {
  7131. this.name = name || THREE.Math.generateUUID();
  7132. this.tracks = tracks;
  7133. this.duration = ( duration !== undefined ) ? duration : -1;
  7134. // this means it should figure out its duration by scanning the tracks
  7135. if ( this.duration < 0 ) {
  7136. this.resetDuration();
  7137. }
  7138. // maybe only do these on demand, as doing them here could potentially slow down loading
  7139. // but leaving these here during development as this ensures a lot of testing of these functions
  7140. this.trim();
  7141. this.optimize();
  7142. };
  7143. THREE.AnimationClip.prototype = {
  7144. constructor: THREE.AnimationClip,
  7145. resetDuration: function() {
  7146. var tracks = this.tracks,
  7147. duration = 0;
  7148. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  7149. var track = this.tracks[ i ];
  7150. duration = Math.max(
  7151. duration, track.times[ track.times.length - 1 ] );
  7152. }
  7153. this.duration = duration;
  7154. },
  7155. trim: function() {
  7156. for ( var i = 0; i < this.tracks.length; i ++ ) {
  7157. this.tracks[ i ].trim( 0, this.duration );
  7158. }
  7159. return this;
  7160. },
  7161. optimize: function() {
  7162. for ( var i = 0; i < this.tracks.length; i ++ ) {
  7163. this.tracks[ i ].optimize();
  7164. }
  7165. return this;
  7166. }
  7167. };
  7168. // Static methods:
  7169. Object.assign( THREE.AnimationClip, {
  7170. parse: function( json ) {
  7171. var tracks = [],
  7172. jsonTracks = json.tracks,
  7173. frameTime = 1.0 / ( json.fps || 1.0 );
  7174. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  7175. tracks.push( THREE.KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  7176. }
  7177. return new THREE.AnimationClip( json.name, json.duration, tracks );
  7178. },
  7179. toJSON: function( clip ) {
  7180. var tracks = [],
  7181. clipTracks = clip.tracks;
  7182. var json = {
  7183. 'name': clip.name,
  7184. 'duration': clip.duration,
  7185. 'tracks': tracks
  7186. };
  7187. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  7188. tracks.push( THREE.KeyframeTrack.toJSON( clipTracks[ i ] ) );
  7189. }
  7190. return json;
  7191. },
  7192. CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps ) {
  7193. var numMorphTargets = morphTargetSequence.length;
  7194. var tracks = [];
  7195. for ( var i = 0; i < numMorphTargets; i ++ ) {
  7196. var times = [];
  7197. var values = [];
  7198. times.push(
  7199. ( i + numMorphTargets - 1 ) % numMorphTargets,
  7200. i,
  7201. ( i + 1 ) % numMorphTargets );
  7202. values.push( 0, 1, 0 );
  7203. var order = THREE.AnimationUtils.getKeyframeOrder( times );
  7204. times = THREE.AnimationUtils.sortedArray( times, 1, order );
  7205. values = THREE.AnimationUtils.sortedArray( values, 1, order );
  7206. // if there is a key at the first frame, duplicate it as the
  7207. // last frame as well for perfect loop.
  7208. if ( times[ 0 ] === 0 ) {
  7209. times.push( numMorphTargets );
  7210. values.push( values[ 0 ] );
  7211. }
  7212. tracks.push(
  7213. new THREE.NumberKeyframeTrack(
  7214. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  7215. times, values
  7216. ).scale( 1.0 / fps ) );
  7217. }
  7218. return new THREE.AnimationClip( name, -1, tracks );
  7219. },
  7220. findByName: function( clipArray, name ) {
  7221. for ( var i = 0; i < clipArray.length; i ++ ) {
  7222. if ( clipArray[ i ].name === name ) {
  7223. return clipArray[ i ];
  7224. }
  7225. }
  7226. return null;
  7227. },
  7228. CreateClipsFromMorphTargetSequences: function( morphTargets, fps ) {
  7229. var animationToMorphTargets = {};
  7230. // tested with https://regex101.com/ on trick sequences
  7231. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  7232. var pattern = /^([\w-]*?)([\d]+)$/;
  7233. // sort morph target names into animation groups based
  7234. // patterns like Walk_001, Walk_002, Run_001, Run_002
  7235. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  7236. var morphTarget = morphTargets[ i ];
  7237. var parts = morphTarget.name.match( pattern );
  7238. if ( parts && parts.length > 1 ) {
  7239. var name = parts[ 1 ];
  7240. var animationMorphTargets = animationToMorphTargets[ name ];
  7241. if ( ! animationMorphTargets ) {
  7242. animationToMorphTargets[ name ] = animationMorphTargets = [];
  7243. }
  7244. animationMorphTargets.push( morphTarget );
  7245. }
  7246. }
  7247. var clips = [];
  7248. for ( var name in animationToMorphTargets ) {
  7249. clips.push( THREE.AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps ) );
  7250. }
  7251. return clips;
  7252. },
  7253. // parse the animation.hierarchy format
  7254. parseAnimation: function( animation, bones, nodeName ) {
  7255. if ( ! animation ) {
  7256. console.error( " no animation in JSONLoader data" );
  7257. return null;
  7258. }
  7259. var addNonemptyTrack = function(
  7260. trackType, trackName, animationKeys, propertyName, destTracks ) {
  7261. // only return track if there are actually keys.
  7262. if ( animationKeys.length !== 0 ) {
  7263. var times = [];
  7264. var values = [];
  7265. THREE.AnimationUtils.flattenJSON(
  7266. animationKeys, times, values, propertyName );
  7267. // empty keys are filtered out, so check again
  7268. if ( times.length !== 0 ) {
  7269. destTracks.push( new trackType( trackName, times, values ) );
  7270. }
  7271. }
  7272. };
  7273. var tracks = [];
  7274. var clipName = animation.name || 'default';
  7275. // automatic length determination in AnimationClip.
  7276. var duration = animation.length || -1;
  7277. var fps = animation.fps || 30;
  7278. var hierarchyTracks = animation.hierarchy || [];
  7279. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  7280. var animationKeys = hierarchyTracks[ h ].keys;
  7281. // skip empty tracks
  7282. if ( ! animationKeys || animationKeys.length == 0 ) continue;
  7283. // process morph targets in a way exactly compatible
  7284. // with AnimationHandler.init( animation )
  7285. if ( animationKeys[0].morphTargets ) {
  7286. // figure out all morph targets used in this track
  7287. var morphTargetNames = {};
  7288. for ( var k = 0; k < animationKeys.length; k ++ ) {
  7289. if ( animationKeys[k].morphTargets ) {
  7290. for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) {
  7291. morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1;
  7292. }
  7293. }
  7294. }
  7295. // create a track for each morph target with all zero
  7296. // morphTargetInfluences except for the keys in which
  7297. // the morphTarget is named.
  7298. for ( var morphTargetName in morphTargetNames ) {
  7299. var times = [];
  7300. var values = [];
  7301. for ( var m = 0;
  7302. m !== animationKeys[k].morphTargets.length; ++ m ) {
  7303. var animationKey = animationKeys[k];
  7304. times.push( animationKey.time );
  7305. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 )
  7306. }
  7307. tracks.push( new THREE.NumberKeyframeTrack(
  7308. '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  7309. }
  7310. duration = morphTargetNames.length * ( fps || 1.0 );
  7311. } else {
  7312. // ...assume skeletal animation
  7313. var boneName = '.bones[' + bones[ h ].name + ']';
  7314. addNonemptyTrack(
  7315. THREE.VectorKeyframeTrack, boneName + '.position',
  7316. animationKeys, 'pos', tracks );
  7317. addNonemptyTrack(
  7318. THREE.QuaternionKeyframeTrack, boneName + '.quaternion',
  7319. animationKeys, 'rot', tracks );
  7320. addNonemptyTrack(
  7321. THREE.VectorKeyframeTrack, boneName + '.scale',
  7322. animationKeys, 'scl', tracks );
  7323. }
  7324. }
  7325. if ( tracks.length === 0 ) {
  7326. return null;
  7327. }
  7328. var clip = new THREE.AnimationClip( clipName, duration, tracks );
  7329. return clip;
  7330. }
  7331. } );
  7332. // File:src/animation/AnimationMixer.js
  7333. /**
  7334. *
  7335. * Player for AnimationClips.
  7336. *
  7337. *
  7338. * @author Ben Houston / http://clara.io/
  7339. * @author David Sarno / http://lighthaus.us/
  7340. * @author tschw
  7341. */
  7342. THREE.AnimationMixer = function( root ) {
  7343. this._root = root;
  7344. this._initMemoryManager();
  7345. this._accuIndex = 0;
  7346. this.time = 0;
  7347. this.timeScale = 1.0;
  7348. };
  7349. THREE.AnimationMixer.prototype = {
  7350. constructor: THREE.AnimationMixer,
  7351. // return an action for a clip optionally using a custom root target
  7352. // object (this method allocates a lot of dynamic memory in case a
  7353. // previously unknown clip/root combination is specified)
  7354. clipAction: function( clip, optionalRoot ) {
  7355. var root = optionalRoot || this._root,
  7356. rootUuid = root.uuid,
  7357. clipName = ( typeof clip === 'string' ) ? clip : clip.name,
  7358. clipObject = ( clip !== clipName ) ? clip : null,
  7359. actionsForClip = this._actionsByClip[ clipName ],
  7360. prototypeAction;
  7361. if ( actionsForClip !== undefined ) {
  7362. var existingAction =
  7363. actionsForClip.actionByRoot[ rootUuid ];
  7364. if ( existingAction !== undefined ) {
  7365. return existingAction;
  7366. }
  7367. // we know the clip, so we don't have to parse all
  7368. // the bindings again but can just copy
  7369. prototypeAction = actionsForClip.knownActions[ 0 ];
  7370. // also, take the clip from the prototype action
  7371. clipObject = prototypeAction._clip;
  7372. if ( clip !== clipName && clip !== clipObject ) {
  7373. throw new Error(
  7374. "Different clips with the same name detected!" );
  7375. }
  7376. }
  7377. // clip must be known when specified via string
  7378. if ( clipObject === null ) return null;
  7379. // allocate all resources required to run it
  7380. var newAction = new THREE.
  7381. AnimationMixer._Action( this, clipObject, optionalRoot );
  7382. this._bindAction( newAction, prototypeAction );
  7383. // and make the action known to the memory manager
  7384. this._addInactiveAction( newAction, clipName, rootUuid );
  7385. return newAction;
  7386. },
  7387. // get an existing action
  7388. existingAction: function( clip, optionalRoot ) {
  7389. var root = optionalRoot || this._root,
  7390. rootUuid = root.uuid,
  7391. clipName = ( typeof clip === 'string' ) ? clip : clip.name,
  7392. actionsForClip = this._actionsByClip[ clipName ];
  7393. if ( actionsForClip !== undefined ) {
  7394. return actionsForClip.actionByRoot[ rootUuid ] || null;
  7395. }
  7396. return null;
  7397. },
  7398. // deactivates all previously scheduled actions
  7399. stopAllAction: function() {
  7400. var actions = this._actions,
  7401. nActions = this._nActiveActions,
  7402. bindings = this._bindings,
  7403. nBindings = this._nActiveBindings;
  7404. this._nActiveActions = 0;
  7405. this._nActiveBindings = 0;
  7406. for ( var i = 0; i !== nActions; ++ i ) {
  7407. actions[ i ].reset();
  7408. }
  7409. for ( var i = 0; i !== nBindings; ++ i ) {
  7410. bindings[ i ].useCount = 0;
  7411. }
  7412. return this;
  7413. },
  7414. // advance the time and update apply the animation
  7415. update: function( deltaTime ) {
  7416. deltaTime *= this.timeScale;
  7417. var actions = this._actions,
  7418. nActions = this._nActiveActions,
  7419. time = this.time += deltaTime,
  7420. timeDirection = Math.sign( deltaTime ),
  7421. accuIndex = this._accuIndex ^= 1;
  7422. // run active actions
  7423. for ( var i = 0; i !== nActions; ++ i ) {
  7424. var action = actions[ i ];
  7425. if ( action.enabled ) {
  7426. action._update( time, deltaTime, timeDirection, accuIndex );
  7427. }
  7428. }
  7429. // update scene graph
  7430. var bindings = this._bindings,
  7431. nBindings = this._nActiveBindings;
  7432. for ( var i = 0; i !== nBindings; ++ i ) {
  7433. bindings[ i ].apply( accuIndex );
  7434. }
  7435. return this;
  7436. },
  7437. // return this mixer's root target object
  7438. getRoot: function() {
  7439. return this._root;
  7440. },
  7441. // free all resources specific to a particular clip
  7442. uncacheClip: function( clip ) {
  7443. var actions = this._actions,
  7444. clipName = clip.name,
  7445. actionsByClip = this._actionsByClip,
  7446. actionsForClip = actionsByClip[ clipName ];
  7447. if ( actionsForClip !== undefined ) {
  7448. // note: just calling _removeInactiveAction would mess up the
  7449. // iteration state and also require updating the state we can
  7450. // just throw away
  7451. var actionsToRemove = actionsForClip.knownActions;
  7452. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  7453. var action = actionsToRemove[ i ];
  7454. this._deactivateAction( action );
  7455. var cacheIndex = action._cacheIndex,
  7456. lastInactiveAction = actions[ actions.length - 1 ];
  7457. action._cacheIndex = null;
  7458. action._byClipCacheIndex = null;
  7459. lastInactiveAction._cacheIndex = cacheIndex;
  7460. actions[ cacheIndex ] = lastInactiveAction;
  7461. actions.pop();
  7462. this._removeInactiveBindingsForAction( action );
  7463. }
  7464. delete actionsByClip[ clipName ];
  7465. }
  7466. },
  7467. // free all resources specific to a particular root target object
  7468. uncacheRoot: function( root ) {
  7469. var rootUuid = root.uuid,
  7470. actionsByClip = this._actionsByClip;
  7471. for ( var clipName in actionsByClip ) {
  7472. var actionByRoot = actionsByClip[ clipName ].actionByRoot,
  7473. action = actionByRoot[ rootUuid ];
  7474. if ( action !== undefined ) {
  7475. this._deactivateAction( action );
  7476. this._removeInactiveAction( action );
  7477. }
  7478. }
  7479. var bindingsByRoot = this._bindingsByRootAndName,
  7480. bindingByName = bindingsByRoot[ rootUuid ];
  7481. if ( bindingByName !== undefined ) {
  7482. for ( var trackName in bindingByName ) {
  7483. var binding = bindingByName[ trackName ];
  7484. binding.restoreOriginalState();
  7485. this._removeInactiveBinding( binding );
  7486. }
  7487. }
  7488. },
  7489. // remove a targeted clip from the cache
  7490. uncacheAction: function( clip, optionalRoot ) {
  7491. var action = this.existingAction( clip, optionalRoot );
  7492. if ( action !== null ) {
  7493. this._deactivateAction( action );
  7494. this._removeInactiveAction( action );
  7495. }
  7496. }
  7497. };
  7498. THREE.EventDispatcher.prototype.apply( THREE.AnimationMixer.prototype );
  7499. THREE.AnimationMixer._Action =
  7500. function( mixer, clip, localRoot ) {
  7501. this._mixer = mixer;
  7502. this._clip = clip;
  7503. this._localRoot = localRoot || null;
  7504. var tracks = clip.tracks,
  7505. nTracks = tracks.length,
  7506. interpolants = new Array( nTracks );
  7507. var interpolantSettings = {
  7508. endingStart: THREE.ZeroCurvatureEnding,
  7509. endingEnd: THREE.ZeroCurvatureEnding
  7510. };
  7511. for ( var i = 0; i !== nTracks; ++ i ) {
  7512. var interpolant = tracks[ i ].createInterpolant( null );
  7513. interpolants[ i ] = interpolant;
  7514. interpolant.settings = interpolantSettings
  7515. }
  7516. this._interpolantSettings = interpolantSettings;
  7517. this._interpolants = interpolants; // bound by the mixer
  7518. // inside: PropertyMixer (managed by the mixer)
  7519. this._propertyBindings = new Array( nTracks );
  7520. this._cacheIndex = null; // for the memory manager
  7521. this._byClipCacheIndex = null; // for the memory manager
  7522. this._timeScaleInterpolant = null;
  7523. this._weightInterpolant = null;
  7524. this.loop = THREE.LoopRepeat;
  7525. this._loopCount = -1;
  7526. // global mixer time when the action is to be started
  7527. // it's set back to 'null' upon start of the action
  7528. this._startTime = null;
  7529. // scaled local time of the action
  7530. // gets clamped or wrapped to 0..clip.duration according to loop
  7531. this.time = 0;
  7532. this.timeScale = 1;
  7533. this._effectiveTimeScale = 1;
  7534. this.weight = 1;
  7535. this._effectiveWeight = 1;
  7536. this.repetitions = Infinity; // no. of repetitions when looping
  7537. this.paused = false; // false -> zero effective time scale
  7538. this.enabled = true; // true -> zero effective weight
  7539. this.clampWhenFinished = false; // keep feeding the last frame?
  7540. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  7541. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  7542. };
  7543. THREE.AnimationMixer._Action.prototype = {
  7544. constructor: THREE.AnimationMixer._Action,
  7545. // State & Scheduling
  7546. play: function() {
  7547. this._mixer._activateAction( this );
  7548. return this;
  7549. },
  7550. stop: function() {
  7551. this._mixer._deactivateAction( this );
  7552. return this.reset();
  7553. },
  7554. reset: function() {
  7555. this.paused = false;
  7556. this.enabled = true;
  7557. this.time = 0; // restart clip
  7558. this._loopCount = -1; // forget previous loops
  7559. this._startTime = null; // forget scheduling
  7560. return this.stopFading().stopWarping();
  7561. },
  7562. isRunning: function() {
  7563. var start = this._startTime;
  7564. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  7565. this._startTime === null && this._mixer._isActiveAction( this )
  7566. },
  7567. // return true when play has been called
  7568. isScheduled: function() {
  7569. return this._mixer._isActiveAction( this );
  7570. },
  7571. startAt: function( time ) {
  7572. this._startTime = time;
  7573. return this;
  7574. },
  7575. setLoop: function( mode, repetitions ) {
  7576. this.loop = mode;
  7577. this.repetitions = repetitions;
  7578. return this;
  7579. },
  7580. // Weight
  7581. // set the weight stopping any scheduled fading
  7582. // although .enabled = false yields an effective weight of zero, this
  7583. // method does *not* change .enabled, because it would be confusing
  7584. setEffectiveWeight: function( weight ) {
  7585. this.weight = weight;
  7586. // note: same logic as when updated at runtime
  7587. this._effectiveWeight = this.enabled ? weight : 0;
  7588. return this.stopFading();
  7589. },
  7590. // return the weight considering fading and .enabled
  7591. getEffectiveWeight: function() {
  7592. return this._effectiveWeight;
  7593. },
  7594. fadeIn: function( duration ) {
  7595. return this._scheduleFading( duration, 0, 1 );
  7596. },
  7597. fadeOut: function( duration ) {
  7598. return this._scheduleFading( duration, 1, 0 );
  7599. },
  7600. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  7601. var mixer = this._mixer;
  7602. fadeOutAction.fadeOut( duration );
  7603. this.fadeIn( duration );
  7604. if( warp ) {
  7605. var fadeInDuration = this._clip.duration,
  7606. fadeOutDuration = fadeOutAction._clip.duration,
  7607. startEndRatio = fadeOutDuration / fadeInDuration,
  7608. endStartRatio = fadeInDuration / fadeOutDuration;
  7609. fadeOutAction.warp( 1.0, startEndRatio, duration );
  7610. this.warp( endStartRatio, 1.0, duration );
  7611. }
  7612. return this;
  7613. },
  7614. crossFadeTo: function( fadeInAction, duration, warp ) {
  7615. return fadeInAction.crossFadeFrom( this, duration, warp );
  7616. },
  7617. stopFading: function() {
  7618. var weightInterpolant = this._weightInterpolant;
  7619. if ( weightInterpolant !== null ) {
  7620. this._weightInterpolant = null;
  7621. this._mixer._takeBackControlInterpolant( weightInterpolant );
  7622. }
  7623. return this;
  7624. },
  7625. // Time Scale Control
  7626. // set the weight stopping any scheduled warping
  7627. // although .paused = true yields an effective time scale of zero, this
  7628. // method does *not* change .paused, because it would be confusing
  7629. setEffectiveTimeScale: function( timeScale ) {
  7630. this.timeScale = timeScale;
  7631. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  7632. return this.stopWarping();
  7633. },
  7634. // return the time scale considering warping and .paused
  7635. getEffectiveTimeScale: function() {
  7636. return this._effectiveTimeScale;
  7637. },
  7638. setDuration: function( duration ) {
  7639. this.timeScale = this._clip.duration / duration;
  7640. return this.stopWarping();
  7641. },
  7642. syncWith: function( action ) {
  7643. this.time = action.time;
  7644. this.timeScale = action.timeScale;
  7645. return this.stopWarping();
  7646. },
  7647. halt: function( duration ) {
  7648. return this.warp( this._currentTimeScale, 0, duration );
  7649. },
  7650. warp: function( startTimeScale, endTimeScale, duration ) {
  7651. var mixer = this._mixer, now = mixer.time,
  7652. interpolant = this._timeScaleInterpolant,
  7653. timeScale = this.timeScale;
  7654. if ( interpolant === null ) {
  7655. interpolant = mixer._lendControlInterpolant(),
  7656. this._timeScaleInterpolant = interpolant;
  7657. }
  7658. var times = interpolant.parameterPositions,
  7659. values = interpolant.sampleValues;
  7660. times[ 0 ] = now;
  7661. times[ 1 ] = now + duration;
  7662. values[ 0 ] = startTimeScale / timeScale;
  7663. values[ 1 ] = endTimeScale / timeScale;
  7664. return this;
  7665. },
  7666. stopWarping: function() {
  7667. var timeScaleInterpolant = this._timeScaleInterpolant;
  7668. if ( timeScaleInterpolant !== null ) {
  7669. this._timeScaleInterpolant = null;
  7670. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  7671. }
  7672. return this;
  7673. },
  7674. // Object Accessors
  7675. getMixer: function() {
  7676. return this._mixer;
  7677. },
  7678. getClip: function() {
  7679. return this._clip;
  7680. },
  7681. getRoot: function() {
  7682. return this._localRoot || this._mixer._root;
  7683. },
  7684. // Interna
  7685. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  7686. // called by the mixer
  7687. var startTime = this._startTime;
  7688. if ( startTime !== null ) {
  7689. // check for scheduled start of action
  7690. var timeRunning = ( time - startTime ) * timeDirection;
  7691. if ( timeRunning < 0 || timeDirection === 0 ) {
  7692. return; // yet to come / don't decide when delta = 0
  7693. }
  7694. // start
  7695. this._startTime = null; // unschedule
  7696. deltaTime = timeDirection * timeRunning;
  7697. }
  7698. // apply time scale and advance time
  7699. deltaTime *= this._updateTimeScale( time );
  7700. var clipTime = this._updateTime( deltaTime );
  7701. // note: _updateTime may disable the action resulting in
  7702. // an effective weight of 0
  7703. var weight = this._updateWeight( time );
  7704. if ( weight > 0 ) {
  7705. var interpolants = this._interpolants;
  7706. var propertyMixers = this._propertyBindings;
  7707. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  7708. interpolants[ j ].evaluate( clipTime );
  7709. propertyMixers[ j ].accumulate( accuIndex, weight );
  7710. }
  7711. }
  7712. },
  7713. _updateWeight: function( time ) {
  7714. var weight = 0;
  7715. if ( this.enabled ) {
  7716. weight = this.weight;
  7717. var interpolant = this._weightInterpolant;
  7718. if ( interpolant !== null ) {
  7719. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  7720. weight *= interpolantValue;
  7721. if ( time > interpolant.parameterPositions[ 1 ] ) {
  7722. this.stopFading();
  7723. if ( interpolantValue === 0 ) {
  7724. // faded out, disable
  7725. this.enabled = false;
  7726. }
  7727. }
  7728. }
  7729. }
  7730. this._effectiveWeight = weight;
  7731. return weight;
  7732. },
  7733. _updateTimeScale: function( time ) {
  7734. var timeScale = 0;
  7735. if ( ! this.paused ) {
  7736. timeScale = this.timeScale;
  7737. var interpolant = this._timeScaleInterpolant;
  7738. if ( interpolant !== null ) {
  7739. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  7740. timeScale *= interpolantValue;
  7741. if ( time > interpolant.parameterPositions[ 1 ] ) {
  7742. this.stopWarping();
  7743. if ( timeScale === 0 ) {
  7744. // motion has halted, pause
  7745. this.pause = true;
  7746. } else {
  7747. // warp done - apply final time scale
  7748. this.timeScale = timeScale;
  7749. }
  7750. }
  7751. }
  7752. }
  7753. this._effectiveTimeScale = timeScale;
  7754. return timeScale;
  7755. },
  7756. _updateTime: function( deltaTime ) {
  7757. var time = this.time + deltaTime;
  7758. if ( deltaTime === 0 ) return time;
  7759. var duration = this._clip.duration,
  7760. loop = this.loop,
  7761. loopCount = this._loopCount,
  7762. pingPong = false;
  7763. switch ( loop ) {
  7764. case THREE.LoopOnce:
  7765. case THREE.LoopOnceClamp:
  7766. if ( loopCount === -1 ) {
  7767. // just started
  7768. this.loopCount = 0;
  7769. this._setEndings( true, true, false );
  7770. }
  7771. if ( time >= duration ) {
  7772. time = duration;
  7773. } else if ( time < 0 ) {
  7774. time = 0;
  7775. } else break;
  7776. // reached the end
  7777. if ( this.clampWhenFinished ) this.pause = true;
  7778. else this.enabled = false;
  7779. this._mixer.dispatchEvent( {
  7780. type: 'finished', action: this,
  7781. direction: deltaTime < 0 ? -1 : 1
  7782. } );
  7783. break;
  7784. case THREE.LoopPingPong:
  7785. pingPong = true;
  7786. case THREE.LoopRepeat:
  7787. if ( loopCount === -1 ) {
  7788. // just started
  7789. if ( deltaTime > 0 ) {
  7790. loopCount = 0;
  7791. this._setEndings(
  7792. true, this.repetitions === 0, pingPong );
  7793. } else {
  7794. // when looping in reverse direction, the initial
  7795. // transition through zero counts as a repetition,
  7796. // so leave loopCount at -1
  7797. this._setEndings(
  7798. this.repetitions === 0, true, pingPong );
  7799. }
  7800. }
  7801. if ( time >= duration || time < 0 ) {
  7802. // wrap around
  7803. var loopDelta = Math.floor( time / duration ); // signed
  7804. time -= duration * loopDelta;
  7805. loopCount += Math.abs( loopDelta );
  7806. var pending = this.repetitions - loopCount;
  7807. if ( pending < 0 ) {
  7808. // stop (switch state, clamp time, fire event)
  7809. if ( this.clampWhenFinished ) this.paused = true;
  7810. else this.enabled = false;
  7811. time = deltaTime > 0 ? duration : 0;
  7812. this._mixer.dispatchEvent( {
  7813. type: 'finished', action: this,
  7814. direction: deltaTime > 0 ? 1 : -1
  7815. } );
  7816. break;
  7817. } else if ( pending === 0 ) {
  7818. // transition to last round
  7819. var atStart = deltaTime < 0;
  7820. this._setEndings( atStart, ! atStart, pingPong );
  7821. } else {
  7822. this._setEndings( false, false, pingPong );
  7823. }
  7824. this._loopCount = loopCount;
  7825. this._mixer.dispatchEvent( {
  7826. type: 'loop', action: this, loopDelta: loopDelta
  7827. } );
  7828. }
  7829. if ( loop === THREE.LoopPingPong && ( loopCount & 1 ) === 1 ) {
  7830. // invert time for the "pong round"
  7831. this.time = time;
  7832. return duration - time;
  7833. }
  7834. break;
  7835. }
  7836. this.time = time;
  7837. return time;
  7838. },
  7839. _setEndings: function( atStart, atEnd, pingPong ) {
  7840. var settings = this._interpolantSettings;
  7841. if ( pingPong ) {
  7842. settings.endingStart = THREE.ZeroSlopeEnding;
  7843. settings.endingEnd = THREE.ZeroSlopeEnding;
  7844. } else {
  7845. // assuming for LoopOnce atStart == atEnd == true
  7846. if ( atStart ) {
  7847. settings.endingStart = this.zeroSlopeAtStart ?
  7848. THREE.ZeroSlopeEnding : THREE.ZeroCurvatureEnding;
  7849. } else {
  7850. settings.endingStart = THREE.WrapAroundEnding;
  7851. }
  7852. if ( atEnd ) {
  7853. settings.endingEnd = this.zeroSlopeAtEnd ?
  7854. THREE.ZeroSlopeEnding : THREE.ZeroCurvatureEnding;
  7855. } else {
  7856. settings.endingEnd = THREE.WrapAroundEnding;
  7857. }
  7858. }
  7859. },
  7860. _scheduleFading: function( duration, weightNow, weightThen ) {
  7861. var mixer = this._mixer, now = mixer.time,
  7862. interpolant = this._weightInterpolant;
  7863. if ( interpolant === null ) {
  7864. interpolant = mixer._lendControlInterpolant(),
  7865. this._weightInterpolant = interpolant;
  7866. }
  7867. var times = interpolant.parameterPositions,
  7868. values = interpolant.sampleValues;
  7869. times[ 0 ] = now; values[ 0 ] = weightNow;
  7870. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  7871. return this;
  7872. }
  7873. };
  7874. // Implementation details:
  7875. Object.assign( THREE.AnimationMixer.prototype, {
  7876. _bindAction: function( action, prototypeAction ) {
  7877. var root = action._localRoot || this._root,
  7878. tracks = action._clip.tracks,
  7879. nTracks = tracks.length,
  7880. bindings = action._propertyBindings,
  7881. interpolants = action._interpolants,
  7882. rootUuid = root.uuid,
  7883. bindingsByRoot = this._bindingsByRootAndName,
  7884. bindingsByName = bindingsByRoot[ rootUuid ];
  7885. if ( bindingsByName === undefined ) {
  7886. bindingsByName = {};
  7887. bindingsByRoot[ rootUuid ] = bindingsByName;
  7888. }
  7889. for ( var i = 0; i !== nTracks; ++ i ) {
  7890. var track = tracks[ i ],
  7891. trackName = track.name,
  7892. binding = bindingsByName[ trackName ];
  7893. if ( binding !== undefined ) {
  7894. bindings[ i ] = binding;
  7895. } else {
  7896. binding = bindings[ i ];
  7897. if ( binding !== undefined ) {
  7898. // existing binding, make sure the cache knows
  7899. if ( binding._cacheIndex === null ) {
  7900. ++ binding.referenceCount;
  7901. this._addInactiveBinding( binding, rootUuid, trackName );
  7902. }
  7903. continue;
  7904. }
  7905. var path = prototypeAction && prototypeAction.
  7906. _propertyBindings[ i ].binding.parsedPath;
  7907. binding = new THREE.PropertyMixer(
  7908. THREE.PropertyBinding.create( root, trackName, path ),
  7909. track.ValueTypeName, track.getValueSize() );
  7910. ++ binding.referenceCount;
  7911. this._addInactiveBinding( binding, rootUuid, trackName );
  7912. bindings[ i ] = binding;
  7913. }
  7914. interpolants[ i ].resultBuffer = binding.buffer;
  7915. }
  7916. },
  7917. _activateAction: function( action ) {
  7918. if ( ! this._isActiveAction( action ) ) {
  7919. if ( action._cacheIndex === null ) {
  7920. // this action has been forgotten by the cache, but the user
  7921. // appears to be still using it -> rebind
  7922. var rootUuid = ( action._localRoot || this._root ).uuid,
  7923. clipName = action._clip.name,
  7924. actionsForClip = this._actionsByClip[ clipName ];
  7925. this._bindAction( action,
  7926. actionsForClip && actionsForClip.knownActions[ 0 ] );
  7927. this._addInactiveAction( action, clipName, rootUuid );
  7928. }
  7929. var bindings = action._propertyBindings;
  7930. // increment reference counts / sort out state
  7931. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  7932. var binding = bindings[ i ];
  7933. if ( binding.useCount ++ === 0 ) {
  7934. this._lendBinding( binding );
  7935. binding.saveOriginalState();
  7936. }
  7937. }
  7938. this._lendAction( action );
  7939. }
  7940. },
  7941. _deactivateAction: function( action ) {
  7942. if ( this._isActiveAction( action ) ) {
  7943. var bindings = action._propertyBindings;
  7944. // decrement reference counts / sort out state
  7945. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  7946. var binding = bindings[ i ];
  7947. if ( -- binding.useCount === 0 ) {
  7948. binding.restoreOriginalState();
  7949. this._takeBackBinding( binding );
  7950. }
  7951. }
  7952. this._takeBackAction( action );
  7953. }
  7954. },
  7955. // Memory manager
  7956. _initMemoryManager: function() {
  7957. this._actions = []; // 'nActiveActions' followed by inactive ones
  7958. this._nActiveActions = 0;
  7959. this._actionsByClip = {};
  7960. // inside:
  7961. // {
  7962. // knownActions: Array< _Action > - used as prototypes
  7963. // actionByRoot: _Action - lookup
  7964. // }
  7965. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  7966. this._nActiveBindings = 0;
  7967. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  7968. this._controlInterpolants = []; // same game as above
  7969. this._nActiveControlInterpolants = 0;
  7970. var scope = this;
  7971. this.stats = {
  7972. actions: {
  7973. get total() { return scope._actions.length; },
  7974. get inUse() { return scope._nActiveActions; }
  7975. },
  7976. bindings: {
  7977. get total() { return scope._bindings.length; },
  7978. get inUse() { return scope._nActiveBindings; }
  7979. },
  7980. controlInterpolants: {
  7981. get total() { return scope._controlInterpolants.length; },
  7982. get inUse() { return scope._nActiveControlInterpolants; }
  7983. }
  7984. };
  7985. },
  7986. // Memory management for _Action objects
  7987. _isActiveAction: function( action ) {
  7988. var index = action._cacheIndex;
  7989. return index !== null && index < this._nActiveActions;
  7990. },
  7991. _addInactiveAction: function( action, clipName, rootUuid ) {
  7992. var actions = this._actions,
  7993. actionsByClip = this._actionsByClip,
  7994. actionsForClip = actionsByClip[ clipName ];
  7995. if ( actionsForClip === undefined ) {
  7996. actionsForClip = {
  7997. knownActions: [ action ],
  7998. actionByRoot: {}
  7999. };
  8000. action._byClipCacheIndex = 0;
  8001. actionsByClip[ clipName ] = actionsForClip;
  8002. } else {
  8003. var knownActions = actionsForClip.knownActions;
  8004. action._byClipCacheIndex = knownActions.length;
  8005. knownActions.push( action );
  8006. }
  8007. action._cacheIndex = actions.length;
  8008. actions.push( action );
  8009. actionsForClip.actionByRoot[ rootUuid ] = action;
  8010. },
  8011. _removeInactiveAction: function( action ) {
  8012. var actions = this._actions,
  8013. lastInactiveAction = actions[ actions.length - 1 ],
  8014. cacheIndex = action._cacheIndex;
  8015. lastInactiveAction._cacheIndex = cacheIndex;
  8016. actions[ cacheIndex ] = lastInactiveAction;
  8017. actions.pop();
  8018. action._cacheIndex = null;
  8019. var clipName = action._clip.name,
  8020. actionsByClip = this._actionsByClip,
  8021. actionsForClip = actionsByClip[ clipName ],
  8022. knownActionsForClip = actionsForClip.knownActions,
  8023. lastKnownAction =
  8024. knownActionsForClip[ knownActionsForClip.length - 1 ],
  8025. byClipCacheIndex = action._byClipCacheIndex;
  8026. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  8027. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  8028. knownActionsForClip.pop();
  8029. action._byClipCacheIndex = null;
  8030. var actionByRoot = actionsForClip.actionByRoot,
  8031. rootUuid = ( actions._localRoot || this._root ).uuid;
  8032. delete actionByRoot[ rootUuid ];
  8033. if ( knownActionsForClip.length === 0 ) {
  8034. delete actionsByClip[ clipName ];
  8035. }
  8036. this._removeInactiveBindingsForAction( action );
  8037. },
  8038. _removeInactiveBindingsForAction: function( action ) {
  8039. var bindings = action._propertyBindings;
  8040. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  8041. var binding = bindings[ i ];
  8042. if ( -- binding.referenceCount === 0 ) {
  8043. this._removeInactiveBinding( binding );
  8044. }
  8045. }
  8046. },
  8047. _lendAction: function( action ) {
  8048. // [ active actions | inactive actions ]
  8049. // [ active actions >| inactive actions ]
  8050. // s a
  8051. // <-swap->
  8052. // a s
  8053. var actions = this._actions,
  8054. prevIndex = action._cacheIndex,
  8055. lastActiveIndex = this._nActiveActions ++,
  8056. firstInactiveAction = actions[ lastActiveIndex ];
  8057. action._cacheIndex = lastActiveIndex;
  8058. actions[ lastActiveIndex ] = action;
  8059. firstInactiveAction._cacheIndex = prevIndex;
  8060. actions[ prevIndex ] = firstInactiveAction;
  8061. },
  8062. _takeBackAction: function( action ) {
  8063. // [ active actions | inactive actions ]
  8064. // [ active actions |< inactive actions ]
  8065. // a s
  8066. // <-swap->
  8067. // s a
  8068. var actions = this._actions,
  8069. prevIndex = action._cacheIndex,
  8070. firstInactiveIndex = -- this._nActiveActions,
  8071. lastActiveAction = actions[ firstInactiveIndex ];
  8072. action._cacheIndex = firstInactiveIndex;
  8073. actions[ firstInactiveIndex ] = action;
  8074. lastActiveAction._cacheIndex = prevIndex;
  8075. actions[ prevIndex ] = lastActiveAction;
  8076. },
  8077. // Memory management for PropertyMixer objects
  8078. _addInactiveBinding: function( binding, rootUuid, trackName ) {
  8079. var bindingsByRoot = this._bindingsByRootAndName,
  8080. bindingByName = bindingsByRoot[ rootUuid ],
  8081. bindings = this._bindings;
  8082. if ( bindingByName === undefined ) {
  8083. bindingByName = {};
  8084. bindingsByRoot[ rootUuid ] = bindingByName;
  8085. }
  8086. bindingByName[ trackName ] = binding;
  8087. binding._cacheIndex = bindings.length;
  8088. bindings.push( binding );
  8089. },
  8090. _removeInactiveBinding: function( binding ) {
  8091. var bindings = this._bindings,
  8092. propBinding = binding.binding,
  8093. rootUuid = propBinding.rootNode.uuid,
  8094. trackName = propBinding.path,
  8095. bindingsByRoot = this._bindingsByRootAndName,
  8096. bindingByName = bindingsByRoot[ rootUuid ],
  8097. lastInactiveBinding = bindings[ bindings.length - 1 ],
  8098. cacheIndex = binding._cacheIndex;
  8099. lastInactiveBinding._cacheIndex = cacheIndex;
  8100. bindings[ cacheIndex ] = lastInactiveBinding;
  8101. bindings.pop();
  8102. delete bindingByName[ trackName ];
  8103. remove_empty_map: {
  8104. for ( var _ in bindingByName ) break remove_empty_map;
  8105. delete bindingsByRoot[ rootUuid ];
  8106. }
  8107. },
  8108. _lendBinding: function( binding ) {
  8109. var bindings = this._bindings,
  8110. prevIndex = binding._cacheIndex,
  8111. lastActiveIndex = this._nActiveBindings ++,
  8112. firstInactiveBinding = bindings[ lastActiveIndex ];
  8113. binding._cacheIndex = lastActiveIndex;
  8114. bindings[ lastActiveIndex ] = binding;
  8115. firstInactiveBinding._cacheIndex = prevIndex;
  8116. bindings[ prevIndex ] = firstInactiveBinding;
  8117. },
  8118. _takeBackBinding: function( binding ) {
  8119. var bindings = this._bindings,
  8120. prevIndex = binding._cacheIndex,
  8121. firstInactiveIndex = -- this._nActiveBindings,
  8122. lastActiveBinding = bindings[ firstInactiveIndex ];
  8123. binding._cacheIndex = firstInactiveIndex;
  8124. bindings[ firstInactiveIndex ] = binding;
  8125. lastActiveBinding._cacheIndex = prevIndex;
  8126. bindings[ prevIndex ] = lastActiveBinding;
  8127. },
  8128. // Memory management of Interpolants for weight and time scale
  8129. _lendControlInterpolant: function() {
  8130. var interpolants = this._controlInterpolants,
  8131. lastActiveIndex = this._nActiveControlInterpolants ++,
  8132. interpolant = interpolants[ lastActiveIndex ];
  8133. if ( interpolant === undefined ) {
  8134. interpolant = new THREE.LinearInterpolant(
  8135. new Float32Array( 2 ), new Float32Array( 2 ),
  8136. 1, this._controlInterpolantsResultBuffer );
  8137. interpolant.__cacheIndex = lastActiveIndex;
  8138. interpolants[ lastActiveIndex ] = interpolant;
  8139. }
  8140. return interpolant;
  8141. },
  8142. _takeBackControlInterpolant: function( interpolant ) {
  8143. var interpolants = this._controlInterpolants,
  8144. prevIndex = interpolant.__cacheIndex,
  8145. firstInactiveIndex = -- this._nActiveControlInterpolants,
  8146. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  8147. interpolant.__cacheIndex = firstInactiveIndex;
  8148. interpolants[ firstInactiveIndex ] = interpolant;
  8149. lastActiveInterpolant.__cacheIndex = prevIndex;
  8150. interpolants[ prevIndex ] = lastActiveInterpolant;
  8151. },
  8152. _controlInterpolantsResultBuffer: new Float32Array( 1 )
  8153. } );
  8154. // File:src/animation/AnimationObjectGroup.js
  8155. /**
  8156. *
  8157. * A group of objects that receives a shared animation state.
  8158. *
  8159. * Usage:
  8160. *
  8161. * - Add objects you would otherwise pass as 'root' to the
  8162. * constructor or the .clipAction method of AnimationMixer.
  8163. *
  8164. * - Instead pass this object as 'root'.
  8165. *
  8166. * - You can also add and remove objects later when the mixer
  8167. * is running.
  8168. *
  8169. * Note:
  8170. *
  8171. * Objects of this class appear as one object to the mixer,
  8172. * so cache control of the individual objects must be done
  8173. * on the group.
  8174. *
  8175. * Limitation:
  8176. *
  8177. * - The animated properties must be compatible among the
  8178. * all objects in the group.
  8179. *
  8180. * - A single property can either be controlled through a
  8181. * target group or directly, but not both.
  8182. *
  8183. * @author tschw
  8184. */
  8185. THREE.AnimationObjectGroup = function( var_args ) {
  8186. this.uuid = THREE.Math.generateUUID();
  8187. // cached objects followed by the active ones
  8188. this._objects = Array.prototype.slice.call( arguments );
  8189. this.nCachedObjects_ = 0; // threshold
  8190. // note: read by PropertyBinding.Composite
  8191. var indices = {};
  8192. this._indicesByUUID = indices; // for bookkeeping
  8193. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8194. indices[ arguments[ i ].uuid ] = i;
  8195. }
  8196. this._paths = []; // inside: string
  8197. this._parsedPaths = []; // inside: { we don't care, here }
  8198. this._bindings = []; // inside: Array< PropertyBinding >
  8199. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  8200. var scope = this;
  8201. this.stats = {
  8202. objects: {
  8203. get total() { return scope._objects.length; },
  8204. get inUse() { return this.total - scope.nCachedObjects_; }
  8205. },
  8206. get bindingsPerObject() { return scope._bindings.length; }
  8207. };
  8208. };
  8209. THREE.AnimationObjectGroup.prototype = {
  8210. constructor: THREE.AnimationObjectGroup,
  8211. add: function( var_args ) {
  8212. var objects = this._objects,
  8213. nObjects = objects.length,
  8214. nCachedObjects = this.nCachedObjects_,
  8215. indicesByUUID = this._indicesByUUID,
  8216. paths = this._paths,
  8217. parsedPaths = this._parsedPaths,
  8218. bindings = this._bindings,
  8219. nBindings = bindings.length;
  8220. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8221. var object = arguments[ i ],
  8222. uuid = object.uuid,
  8223. index = indicesByUUID[ uuid ];
  8224. if ( index === undefined ) {
  8225. // unknown object -> add it to the ACTIVE region
  8226. index = nObjects ++;
  8227. indicesByUUID[ uuid ] = index;
  8228. objects.push( object );
  8229. // accounting is done, now do the same for all bindings
  8230. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8231. bindings[ j ].push(
  8232. new THREE.PropertyBinding(
  8233. object, paths[ j ], parsedPaths[ j ] ) );
  8234. }
  8235. } else if ( index < nCachedObjects ) {
  8236. var knownObject = objects[ index ];
  8237. // move existing object to the ACTIVE region
  8238. var firstActiveIndex = -- nCachedObjects,
  8239. lastCachedObject = objects[ firstActiveIndex ];
  8240. indicesByUUID[ lastCachedObject.uuid ] = index;
  8241. objects[ index ] = lastCachedObject;
  8242. indicesByUUID[ uuid ] = firstActiveIndex;
  8243. objects[ firstActiveIndex ] = object;
  8244. // accounting is done, now do the same for all bindings
  8245. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8246. var bindingsForPath = bindings[ j ],
  8247. lastCached = bindingsForPath[ firstActiveIndex ],
  8248. binding = bindingsForPath[ index ];
  8249. bindingsForPath[ index ] = lastCached;
  8250. if ( binding === undefined ) {
  8251. // since we do not bother to create new bindings
  8252. // for objects that are cached, the binding may
  8253. // or may not exist
  8254. binding = new THREE.PropertyBinding(
  8255. object, paths[ j ], parsedPaths[ j ] );
  8256. }
  8257. bindingsForPath[ firstActiveIndex ] = binding;
  8258. }
  8259. } else if ( objects[ index ] !== knownObject) {
  8260. console.error( "Different objects with the same UUID " +
  8261. "detected. Clean the caches or recreate your " +
  8262. "infrastructure when reloading scenes..." );
  8263. } // else the object is already where we want it to be
  8264. } // for arguments
  8265. this.nCachedObjects_ = nCachedObjects;
  8266. },
  8267. remove: function( var_args ) {
  8268. var objects = this._objects,
  8269. nObjects = objects.length,
  8270. nCachedObjects = this.nCachedObjects_,
  8271. indicesByUUID = this._indicesByUUID,
  8272. bindings = this._bindings,
  8273. nBindings = bindings.length;
  8274. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8275. var object = arguments[ i ],
  8276. uuid = object.uuid,
  8277. index = indicesByUUID[ uuid ];
  8278. if ( index !== undefined && index >= nCachedObjects ) {
  8279. // move existing object into the CACHED region
  8280. var lastCachedIndex = nCachedObjects ++,
  8281. firstActiveObject = objects[ lastCachedIndex ];
  8282. indicesByUUID[ firstActiveObject.uuid ] = index;
  8283. objects[ index ] = firstActiveObject;
  8284. indicesByUUID[ uuid ] = lastCachedIndex;
  8285. objects[ lastCachedIndex ] = object;
  8286. // accounting is done, now do the same for all bindings
  8287. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8288. var bindingsForPath = bindings[ j ],
  8289. firstActive = bindingsForPath[ lastCachedIndex ],
  8290. binding = bindingsForPath[ index ];
  8291. bindingsForPath[ index ] = firstActive;
  8292. bindingsForPath[ lastCachedIndex ] = binding;
  8293. }
  8294. }
  8295. } // for arguments
  8296. this.nCachedObjects_ = nCachedObjects;
  8297. },
  8298. // remove & forget
  8299. uncache: function( var_args ) {
  8300. var objects = this._objects,
  8301. nObjects = objects.length,
  8302. nCachedObjects = this.nCachedObjects_,
  8303. indicesByUUID = this._indicesByUUID,
  8304. bindings = this._bindings,
  8305. nBindings = bindings.length;
  8306. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8307. var object = arguments[ i ],
  8308. uuid = object.uuid,
  8309. index = indicesByUUID[ uuid ];
  8310. if ( index !== undefined ) {
  8311. delete indicesByUUID[ uuid ];
  8312. if ( index < nCachedObjects ) {
  8313. // object is cached, shrink the CACHED region
  8314. var firstActiveIndex = -- nCachedObjects,
  8315. lastCachedObject = objects[ firstActiveIndex ],
  8316. lastIndex = -- nObjects,
  8317. lastObject = objects[ lastIndex ];
  8318. // last cached object takes this object's place
  8319. indicesByUUID[ lastCachedObject.uuid ] = index;
  8320. objects[ index ] = lastCachedObject;
  8321. // last object goes to the activated slot and pop
  8322. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  8323. objects[ firstActiveIndex ] = lastObject;
  8324. objects.pop();
  8325. // accounting is done, now do the same for all bindings
  8326. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8327. var bindingsForPath = bindings[ j ],
  8328. lastCached = bindingsForPath[ firstActiveIndex ],
  8329. last = bindingsForPath[ lastIndex ];
  8330. bindingsForPath[ index ] = lastCached;
  8331. bindingsForPath[ firstActiveIndex ] = last;
  8332. bindingsForPath.pop();
  8333. }
  8334. } else {
  8335. // object is active, just swap with the last and pop
  8336. var lastIndex = -- nObjects,
  8337. lastObject = objects[ lastIndex ];
  8338. indicesByUUID[ lastObject.uuid ] = index;
  8339. objects[ index ] = lastObject;
  8340. objects.pop();
  8341. // accounting is done, now do the same for all bindings
  8342. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8343. var bindingsForPath = bindings[ j ];
  8344. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  8345. bindingsForPath.pop();
  8346. }
  8347. } // cached or active
  8348. } // if object is known
  8349. } // for arguments
  8350. this.nCachedObjects_ = nCachedObjects;
  8351. },
  8352. // Internal interface used by befriended PropertyBinding.Composite:
  8353. subscribe_: function( path, parsedPath ) {
  8354. // returns an array of bindings for the given path that is changed
  8355. // according to the contained objects in the group
  8356. var indicesByPath = this._bindingsIndicesByPath,
  8357. index = indicesByPath[ path ],
  8358. bindings = this._bindings;
  8359. if ( index !== undefined ) return bindings[ index ];
  8360. var paths = this._paths,
  8361. parsedPaths = this._parsedPaths,
  8362. objects = this._objects,
  8363. nObjects = objects.length,
  8364. nCachedObjects = this.nCachedObjects_,
  8365. bindingsForPath = new Array( nObjects );
  8366. index = bindings.length;
  8367. indicesByPath[ path ] = index;
  8368. paths.push( path );
  8369. parsedPaths.push( parsedPath );
  8370. bindings.push( bindingsForPath );
  8371. for ( var i = nCachedObjects,
  8372. n = objects.length; i !== n; ++ i ) {
  8373. var object = objects[ i ];
  8374. bindingsForPath[ i ] =
  8375. new THREE.PropertyBinding( object, path, parsedPath );
  8376. }
  8377. return bindingsForPath;
  8378. },
  8379. unsubscribe_: function( path ) {
  8380. // tells the group to forget about a property path and no longer
  8381. // update the array previously obtained with 'subscribe_'
  8382. var indicesByPath = this._bindingsIndicesByPath,
  8383. index = indicesByPath[ path ];
  8384. if ( index !== undefined ) {
  8385. var paths = this._paths,
  8386. parsedPaths = this._parsedPaths,
  8387. bindings = this._bindings,
  8388. lastBindingsIndex = bindings.length - 1,
  8389. lastBindings = bindings[ lastBindingsIndex ],
  8390. lastBindingsPath = path[ lastBindingsIndex ];
  8391. indicesByPath[ lastBindingsPath ] = index;
  8392. bindings[ index ] = lastBindings;
  8393. bindings.pop();
  8394. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  8395. parsedPaths.pop();
  8396. paths[ index ] = paths[ lastBindingsIndex ];
  8397. paths.pop();
  8398. }
  8399. }
  8400. };
  8401. // File:src/animation/AnimationUtils.js
  8402. /**
  8403. * @author tschw
  8404. * @author Ben Houston / http://clara.io/
  8405. * @author David Sarno / http://lighthaus.us/
  8406. */
  8407. THREE.AnimationUtils = {
  8408. // same as Array.prototype.slice, but also works on typed arrays
  8409. arraySlice: function( array, from, to ) {
  8410. if ( THREE.AnimationUtils.isTypedArray( array ) ) {
  8411. return new array.constructor( array.subarray( from, to ) );
  8412. }
  8413. return array.slice( from, to );
  8414. },
  8415. // converts an array to a specific type
  8416. convertArray: function( array, type, forceClone ) {
  8417. if ( ! array || // let 'undefined' and 'null' pass
  8418. ! forceClone && array.constructor === type ) return array;
  8419. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  8420. return new type( array ); // create typed array
  8421. }
  8422. return Array.prototype.slice.call( array ); // create Array
  8423. },
  8424. isTypedArray: function( object ) {
  8425. return ArrayBuffer.isView( object ) &&
  8426. ! ( object instanceof DataView );
  8427. },
  8428. // returns an array by which times and values can be sorted
  8429. getKeyframeOrder: function( times ) {
  8430. function compareTime( i, j ) {
  8431. return times[ i ] - times[ j ];
  8432. }
  8433. var n = times.length;
  8434. var result = new Array( n );
  8435. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  8436. result.sort( compareTime );
  8437. return result;
  8438. },
  8439. // uses the array previously returned by 'getKeyframeOrder' to sort data
  8440. sortedArray: function( values, stride, order ) {
  8441. var nValues = values.length;
  8442. var result = new values.constructor( nValues );
  8443. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  8444. var srcOffset = order[ i ] * stride;
  8445. for ( var j = 0; j !== stride; ++ j ) {
  8446. result[ dstOffset ++ ] = values[ srcOffset + j ];
  8447. }
  8448. }
  8449. return result;
  8450. },
  8451. // function for parsing AOS keyframe formats
  8452. flattenJSON: function( jsonKeys, times, values, valuePropertyName ) {
  8453. var i = 1, key = jsonKeys[ 0 ];
  8454. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  8455. key = jsonKeys[ i ++ ];
  8456. }
  8457. if ( key === undefined ) return; // no data
  8458. var value = key[ valuePropertyName ];
  8459. if ( value === undefined ) return; // no data
  8460. if ( Array.isArray( value ) ) {
  8461. do {
  8462. value = key[ valuePropertyName ];
  8463. if ( value !== undefined ) {
  8464. times.push( key.time );
  8465. values.push.apply( values, value ); // push all elements
  8466. }
  8467. key = jsonKeys[ i ++ ];
  8468. } while ( key !== undefined );
  8469. } else if ( value.toArray !== undefined ) {
  8470. // ...assume THREE.Math-ish
  8471. do {
  8472. value = key[ valuePropertyName ];
  8473. if ( value !== undefined ) {
  8474. times.push( key.time );
  8475. value.toArray( values, values.length );
  8476. }
  8477. key = jsonKeys[ i ++ ];
  8478. } while ( key !== undefined );
  8479. } else {
  8480. // otherwise push as-is
  8481. do {
  8482. value = key[ valuePropertyName ];
  8483. if ( value !== undefined ) {
  8484. times.push( key.time );
  8485. values.push( value );
  8486. }
  8487. key = jsonKeys[ i ++ ];
  8488. } while ( key !== undefined );
  8489. }
  8490. }
  8491. };
  8492. // File:src/animation/KeyframeTrack.js
  8493. /**
  8494. *
  8495. * A timed sequence of keyframes for a specific property.
  8496. *
  8497. *
  8498. * @author Ben Houston / http://clara.io/
  8499. * @author David Sarno / http://lighthaus.us/
  8500. * @author tschw
  8501. */
  8502. THREE.KeyframeTrack = function ( name, times, values, interpolation ) {
  8503. if( name === undefined ) throw new Error( "track name is undefined" );
  8504. if( times === undefined || times.length === 0 ) {
  8505. throw new Error( "no keyframes in track named " + name );
  8506. }
  8507. this.name = name;
  8508. this.times = THREE.AnimationUtils.convertArray( times, this.TimeBufferType );
  8509. this.values = THREE.AnimationUtils.convertArray( values, this.ValueBufferType );
  8510. this.setInterpolation( interpolation || this.DefaultInterpolation );
  8511. this.validate();
  8512. this.optimize();
  8513. };
  8514. THREE.KeyframeTrack.prototype = {
  8515. constructor: THREE.KeyframeTrack,
  8516. TimeBufferType: Float32Array,
  8517. ValueBufferType: Float32Array,
  8518. DefaultInterpolation: THREE.InterpolateLinear,
  8519. InterpolantFactoryMethodDiscrete: function( result ) {
  8520. return new THREE.DiscreteInterpolant(
  8521. this.times, this.values, this.getValueSize(), result );
  8522. },
  8523. InterpolantFactoryMethodLinear: function( result ) {
  8524. return new THREE.LinearInterpolant(
  8525. this.times, this.values, this.getValueSize(), result );
  8526. },
  8527. InterpolantFactoryMethodSmooth: function( result ) {
  8528. return new THREE.CubicInterpolant(
  8529. this.times, this.values, this.getValueSize(), result );
  8530. },
  8531. setInterpolation: function( interpolation ) {
  8532. var factoryMethod = undefined;
  8533. switch ( interpolation ) {
  8534. case THREE.InterpolateDiscrete:
  8535. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  8536. break;
  8537. case THREE.InterpolateLinear:
  8538. factoryMethod = this.InterpolantFactoryMethodLinear;
  8539. break;
  8540. case THREE.InterpolateSmooth:
  8541. factoryMethod = this.InterpolantFactoryMethodSmooth;
  8542. break;
  8543. }
  8544. if ( factoryMethod === undefined ) {
  8545. var message = "unsupported interpolation for " +
  8546. this.ValueTypeName + " keyframe track named " + this.name;
  8547. if ( this.createInterpolant === undefined ) {
  8548. // fall back to default, unless the default itself is messed up
  8549. if ( interpolation !== this.DefaultInterpolation ) {
  8550. this.setInterpolation( this.DefaultInterpolation );
  8551. } else {
  8552. throw new Error( message ); // fatal, in this case
  8553. }
  8554. }
  8555. console.warn( message );
  8556. return;
  8557. }
  8558. this.createInterpolant = factoryMethod;
  8559. },
  8560. getInterpolation: function() {
  8561. switch ( this.createInterpolant ) {
  8562. case this.InterpolantFactoryMethodDiscrete:
  8563. return THREE.InterpolateDiscrete;
  8564. case this.InterpolantFactoryMethodLinear:
  8565. return THREE.InterpolateLinear;
  8566. case this.InterpolantFactoryMethodSmooth:
  8567. return THREE.InterpolateSmooth;
  8568. }
  8569. },
  8570. getValueSize: function() {
  8571. return this.values.length / this.times.length;
  8572. },
  8573. // move all keyframes either forwards or backwards in time
  8574. shift: function( timeOffset ) {
  8575. if( timeOffset !== 0.0 ) {
  8576. var times = this.times;
  8577. for( var i = 0, n = times.length; i !== n; ++ i ) {
  8578. times[ i ] += timeOffset;
  8579. }
  8580. }
  8581. return this;
  8582. },
  8583. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  8584. scale: function( timeScale ) {
  8585. if( timeScale !== 1.0 ) {
  8586. var times = this.times;
  8587. for( var i = 0, n = times.length; i !== n; ++ i ) {
  8588. times[ i ] *= timeScale;
  8589. }
  8590. }
  8591. return this;
  8592. },
  8593. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  8594. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  8595. trim: function( startTime, endTime ) {
  8596. var times = this.times;
  8597. var nKeys = times.length;
  8598. var firstKeysToRemove = 0;
  8599. for ( var i = 1; i !== nKeys; ++ i ) {
  8600. if ( times[i] <= startTime ) ++ firstKeysToRemove;
  8601. }
  8602. var lastKeysToRemove = 0;
  8603. for ( var i = nKeys - 2; i !== 0; -- i ) {
  8604. if ( times[i] >= endTime ) ++ lastKeysToRemove;
  8605. else break;
  8606. }
  8607. // remove last keys first because it doesn't affect the position of the first keys (the otherway around doesn't work as easily)
  8608. if( ( firstKeysToRemove + lastKeysToRemove ) !== 0 ) {
  8609. var from = firstKeysToRemove;
  8610. var to = nKeys - lastKeysToRemove - firstKeysToRemove;
  8611. this.times = THREE.AnimationUtils.arraySlice( times, from, to );
  8612. var values = this.values;
  8613. var stride = this.getValueSize();
  8614. this.values = THREE.AnimationUtils.arraySlice( values, from * stride, to * stride );
  8615. }
  8616. return this;
  8617. },
  8618. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  8619. validate: function() {
  8620. var valid = true;
  8621. var valueSize = this.getValueSize();
  8622. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  8623. console.error( "invalid value size in track", this );
  8624. valid = false;
  8625. }
  8626. var times = this.times,
  8627. values = this.values,
  8628. nKeys = times.length;
  8629. if( nKeys === 0 ) {
  8630. console.error( "track is empty", this );
  8631. valid = false;
  8632. }
  8633. var prevTime = null;
  8634. for( var i = 0; i !== nKeys; i ++ ) {
  8635. var currTime = times[ i ];
  8636. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  8637. console.error( "time is not a valid number", this, i, currTime );
  8638. valid = false;
  8639. break;
  8640. }
  8641. if( prevTime !== null && prevTime > currTime ) {
  8642. console.error( "out of order keys", this, i, currTime, prevTime );
  8643. valid = false;
  8644. break;
  8645. }
  8646. prevTime = currTime;
  8647. }
  8648. if ( values !== undefined ) {
  8649. if ( THREE.AnimationUtils.isTypedArray( values ) ) {
  8650. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  8651. var value = values[ i ];
  8652. if ( isNaN( value ) ) {
  8653. console.error( "value is not a valid number", this, i, value );
  8654. valid = false;
  8655. break;
  8656. }
  8657. }
  8658. }
  8659. }
  8660. return valid;
  8661. },
  8662. // removes equivalent sequential keys as common in morph target sequences
  8663. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  8664. optimize: function() {
  8665. var times = this.times,
  8666. values = this.values,
  8667. stride = this.getValueSize(),
  8668. writeIndex = 1;
  8669. for( var i = 1, n = times.length - 1; i <= n; ++ i ) {
  8670. var keep = false;
  8671. var time = times[ i ];
  8672. var timeNext = times[ i + 1 ];
  8673. // remove adjacent keyframes scheduled at the same time
  8674. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  8675. // remove unnecessary keyframes same as their neighbors
  8676. var offset = i * stride,
  8677. offsetP = offset - stride,
  8678. offsetN = offset + stride;
  8679. for ( var j = 0; j !== stride; ++ j ) {
  8680. var value = values[ offset + j ];
  8681. if ( value !== values[ offsetP + j ] ||
  8682. value !== values[ offsetN + j ] ) {
  8683. keep = true;
  8684. break;
  8685. }
  8686. }
  8687. }
  8688. // in-place compaction
  8689. if ( keep ) {
  8690. if ( i !== writeIndex ) {
  8691. times[ writeIndex ] = times[ i ];
  8692. var readOffset = i * stride,
  8693. writeOffset = writeIndex * stride;
  8694. for ( var j = 0; j !== stride; ++ j ) {
  8695. values[ writeOffset + j ] = values[ readOffset + j ];
  8696. }
  8697. }
  8698. ++ writeIndex;
  8699. }
  8700. }
  8701. if ( writeIndex !== times.length ) {
  8702. this.times = THREE.AnimationUtils.arraySlice( times, 0, writeIndex );
  8703. this.values = THREE.AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  8704. }
  8705. return this;
  8706. }
  8707. };
  8708. // Static methods:
  8709. Object.assign( THREE.KeyframeTrack, {
  8710. // Serialization (in static context, because of constructor invocation
  8711. // and automatic invocation of .toJSON):
  8712. parse: function( json ) {
  8713. if( json.type === undefined ) {
  8714. throw new Error( "track type undefined, can not parse" );
  8715. }
  8716. var trackType = THREE.KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  8717. if ( json.times === undefined ) {
  8718. console.warn( "legacy JSON format detected, converting" );
  8719. var times = [], values = [];
  8720. THREE.AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  8721. json.times = times;
  8722. json.values = values;
  8723. }
  8724. // derived classes can define a static parse method
  8725. if ( trackType.parse !== undefined ) {
  8726. return trackType.parse( json );
  8727. } else {
  8728. // by default, we asssume a constructor compatible with the base
  8729. return new trackType(
  8730. json.name, json.times, json.values, json.interpolation );
  8731. }
  8732. },
  8733. toJSON: function( track ) {
  8734. var trackType = track.constructor;
  8735. var json;
  8736. // derived classes can define a static toJSON method
  8737. if ( trackType.toJSON !== undefined ) {
  8738. json = trackType.toJSON( track );
  8739. } else {
  8740. // by default, we assume the data can be serialized as-is
  8741. json = {
  8742. 'name': track.name,
  8743. 'times': THREE.AnimationUtils.convertArray( track.times, Array ),
  8744. 'values': THREE.AnimationUtils.convertArray( track.values, Array )
  8745. };
  8746. var interpolation = track.getInterpolation();
  8747. if ( interpolation !== track.DefaultInterpolation ) {
  8748. json.interpolation = interpolation;
  8749. }
  8750. }
  8751. json.type = track.ValueTypeName; // mandatory
  8752. return json;
  8753. },
  8754. _getTrackTypeForValueTypeName: function( typeName ) {
  8755. switch( typeName.toLowerCase() ) {
  8756. case "scalar":
  8757. case "double":
  8758. case "float":
  8759. case "number":
  8760. case "integer":
  8761. return THREE.NumberKeyframeTrack;
  8762. case "vector":
  8763. case "vector2":
  8764. case "vector3":
  8765. case "vector4":
  8766. return THREE.VectorKeyframeTrack;
  8767. case "color":
  8768. return THREE.ColorKeyframeTrack;
  8769. case "quaternion":
  8770. return THREE.QuaternionKeyframeTrack;
  8771. case "bool":
  8772. case "boolean":
  8773. return THREE.BooleanKeyframeTrack;
  8774. case "string":
  8775. return THREE.StringKeyframeTrack;
  8776. };
  8777. throw new Error( "Unsupported typeName: " + typeName );
  8778. }
  8779. } );
  8780. // File:src/animation/PropertyBinding.js
  8781. /**
  8782. *
  8783. * A reference to a real property in the scene graph.
  8784. *
  8785. *
  8786. * @author Ben Houston / http://clara.io/
  8787. * @author David Sarno / http://lighthaus.us/
  8788. * @author tschw
  8789. */
  8790. THREE.PropertyBinding = function ( rootNode, path, parsedPath ) {
  8791. this.path = path;
  8792. this.parsedPath = parsedPath ||
  8793. THREE.PropertyBinding.parseTrackName( path );
  8794. this.node = THREE.PropertyBinding.findNode(
  8795. rootNode, this.parsedPath.nodeName ) || rootNode;
  8796. this.rootNode = rootNode;
  8797. };
  8798. THREE.PropertyBinding.prototype = {
  8799. constructor: THREE.PropertyBinding,
  8800. getValue: function getValue_unbound( targetArray, offset ) {
  8801. this.bind();
  8802. this.getValue( targetArray, offset );
  8803. // Note: This class uses a State pattern on a per-method basis:
  8804. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  8805. // prototype version of these methods with one that represents
  8806. // the bound state. When the property is not found, the methods
  8807. // become no-ops.
  8808. },
  8809. setValue: function getValue_unbound( sourceArray, offset ) {
  8810. this.bind();
  8811. this.setValue( sourceArray, offset );
  8812. },
  8813. // create getter / setter pair for a property in the scene graph
  8814. bind: function() {
  8815. var targetObject = this.node,
  8816. parsedPath = this.parsedPath,
  8817. objectName = parsedPath.objectName,
  8818. propertyName = parsedPath.propertyName,
  8819. propertyIndex = parsedPath.propertyIndex;
  8820. if ( ! targetObject ) {
  8821. targetObject = THREE.PropertyBinding.findNode(
  8822. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  8823. this.node = targetObject;
  8824. }
  8825. // set fail state so we can just 'return' on error
  8826. this.getValue = this._getValue_unavailable;
  8827. this.setValue = this._setValue_unavailable;
  8828. // ensure there is a value node
  8829. if ( ! targetObject ) {
  8830. console.error( " trying to update node for track: " + this.path + " but it wasn't found." );
  8831. return;
  8832. }
  8833. if( objectName ) {
  8834. var objectIndex = parsedPath.objectIndex;
  8835. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  8836. switch ( objectName ) {
  8837. case 'materials':
  8838. if( ! targetObject.material ) {
  8839. console.error( ' can not bind to material as node does not have a material', this );
  8840. return;
  8841. }
  8842. if( ! targetObject.material.materials ) {
  8843. console.error( ' can not bind to material.materials as node.material does not have a materials array', this );
  8844. return;
  8845. }
  8846. targetObject = targetObject.material.materials;
  8847. break;
  8848. case 'bones':
  8849. if( ! targetObject.skeleton ) {
  8850. console.error( ' can not bind to bones as node does not have a skeleton', this );
  8851. return;
  8852. }
  8853. // potential future optimization: skip this if propertyIndex is already an integer
  8854. // and convert the integer string to a true integer.
  8855. targetObject = targetObject.skeleton.bones;
  8856. // support resolving morphTarget names into indices.
  8857. for ( var i = 0; i < targetObject.length; i ++ ) {
  8858. if ( targetObject[i].name === objectIndex ) {
  8859. objectIndex = i;
  8860. break;
  8861. }
  8862. }
  8863. break;
  8864. default:
  8865. if ( targetObject[ objectName ] === undefined ) {
  8866. console.error( ' can not bind to objectName of node, undefined', this );
  8867. return;
  8868. }
  8869. targetObject = targetObject[ objectName ];
  8870. }
  8871. if ( objectIndex !== undefined ) {
  8872. if( targetObject[ objectIndex ] === undefined ) {
  8873. console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject );
  8874. return;
  8875. }
  8876. targetObject = targetObject[ objectIndex ];
  8877. }
  8878. }
  8879. // resolve property
  8880. var nodeProperty = targetObject[ propertyName ];
  8881. if ( ! nodeProperty ) {
  8882. var nodeName = parsedPath.nodeName;
  8883. console.error( " trying to update property for track: " + nodeName +
  8884. '.' + propertyName + " but it wasn't found.", targetObject );
  8885. return;
  8886. }
  8887. // determine versioning scheme
  8888. var versioning = this.Versioning.None;
  8889. if ( targetObject.needsUpdate !== undefined ) { // material
  8890. versioning = this.Versioning.NeedsUpdate;
  8891. this.targetObject = targetObject;
  8892. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  8893. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  8894. this.targetObject = targetObject;
  8895. }
  8896. // determine how the property gets bound
  8897. var bindingType = this.BindingType.Direct;
  8898. if ( propertyIndex !== undefined ) {
  8899. // access a sub element of the property array (only primitives are supported right now)
  8900. if ( propertyName === "morphTargetInfluences" ) {
  8901. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  8902. // support resolving morphTarget names into indices.
  8903. if ( ! targetObject.geometry ) {
  8904. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this );
  8905. return;
  8906. }
  8907. if ( ! targetObject.geometry.morphTargets ) {
  8908. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this );
  8909. return;
  8910. }
  8911. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  8912. if ( targetObject.geometry.morphTargets[i].name === propertyIndex ) {
  8913. propertyIndex = i;
  8914. break;
  8915. }
  8916. }
  8917. }
  8918. bindingType = this.BindingType.ArrayElement;
  8919. this.resolvedProperty = nodeProperty;
  8920. this.propertyIndex = propertyIndex;
  8921. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  8922. // must use copy for Object3D.Euler/Quaternion
  8923. bindingType = this.BindingType.HasFromToArray;
  8924. this.resolvedProperty = nodeProperty;
  8925. } else if ( Array.isArray( nodeProperty ) ) {
  8926. bindingType = this.BindingType.EntireArray;
  8927. this.resolvedProperty = nodeProperty;
  8928. } else {
  8929. this.propertyName = propertyName;
  8930. }
  8931. // select getter / setter
  8932. this.getValue = this.GetterByBindingType[ bindingType ];
  8933. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  8934. },
  8935. unbind: function() {
  8936. this.node = null;
  8937. // back to the prototype version of getValue / setValue
  8938. // note: avoiding to mutate the shape of 'this' via 'delete'
  8939. this.getValue = this._getValue_unbound;
  8940. this.setValue = this._setValue_unbound;
  8941. }
  8942. };
  8943. Object.assign( THREE.PropertyBinding.prototype, { // prototype, continued
  8944. // these are used to "bind" a nonexistent property
  8945. _getValue_unavailable: function() {},
  8946. _setValue_unavailable: function() {},
  8947. // initial state of these methods that calls 'bind'
  8948. _getValue_unbound: THREE.PropertyBinding.prototype.getValue,
  8949. _setValue_unbound: THREE.PropertyBinding.prototype.setValue,
  8950. BindingType: {
  8951. Direct: 0,
  8952. EntireArray: 1,
  8953. ArrayElement: 2,
  8954. HasFromToArray: 3
  8955. },
  8956. Versioning: {
  8957. None: 0,
  8958. NeedsUpdate: 1,
  8959. MatrixWorldNeedsUpdate: 2
  8960. },
  8961. GetterByBindingType: [
  8962. function getValue_direct( buffer, offset ) {
  8963. buffer[ offset ] = this.node[ this.propertyName ];
  8964. },
  8965. function getValue_array( buffer, offset ) {
  8966. var source = this.node[ this.propertyName ];
  8967. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  8968. buffer[ offset ++ ] = source[ i ];
  8969. }
  8970. },
  8971. function getValue_arrayElement( buffer, offset ) {
  8972. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  8973. },
  8974. function getValue_toArray( buffer, offset ) {
  8975. this.resolvedProperty.toArray( buffer, offset );
  8976. }
  8977. ],
  8978. SetterByBindingTypeAndVersioning: [
  8979. [
  8980. // Direct
  8981. function setValue_direct( buffer, offset ) {
  8982. this.node[ this.propertyName ] = buffer[ offset ];
  8983. },
  8984. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  8985. this.node[ this.propertyName ] = buffer[ offset ];
  8986. this.targetObject.needsUpdate = true;
  8987. },
  8988. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  8989. this.node[ this.propertyName ] = buffer[ offset ];
  8990. this.targetObject.matrixWorldNeedsUpdate = true;
  8991. }
  8992. ], [
  8993. // EntireArray
  8994. function setValue_array( buffer, offset ) {
  8995. var dest = this.resolvedProperty;
  8996. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  8997. dest[ i ] = buffer[ offset ++ ];
  8998. }
  8999. },
  9000. function setValue_array_setNeedsUpdate( buffer, offset ) {
  9001. var dest = this.resolvedProperty;
  9002. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  9003. dest[ i ] = buffer[ offset ++ ];
  9004. }
  9005. this.targetObject.needsUpdate = true;
  9006. },
  9007. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  9008. var dest = this.resolvedProperty;
  9009. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  9010. dest[ i ] = buffer[ offset ++ ];
  9011. }
  9012. this.targetObject.matrixWorldNeedsUpdate = true;
  9013. }
  9014. ], [
  9015. // ArrayElement
  9016. function setValue_arrayElement( buffer, offset ) {
  9017. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  9018. },
  9019. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  9020. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  9021. this.targetObject.needsUpdate = true;
  9022. },
  9023. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  9024. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  9025. this.targetObject.matrixWorldNeedsUpdate = true;
  9026. }
  9027. ], [
  9028. // HasToFromArray
  9029. function setValue_fromArray( buffer, offset ) {
  9030. this.resolvedProperty.fromArray( buffer, offset );
  9031. },
  9032. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  9033. this.resolvedProperty.fromArray( buffer, offset );
  9034. this.targetObject.needsUpdate = true;
  9035. },
  9036. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  9037. this.resolvedProperty.fromArray( buffer, offset );
  9038. this.targetObject.matrixWorldNeedsUpdate = true;
  9039. }
  9040. ]
  9041. ]
  9042. } );
  9043. THREE.PropertyBinding.Composite =
  9044. function( targetGroup, path, optionalParsedPath ) {
  9045. var parsedPath = optionalParsedPath ||
  9046. THREE.PropertyBinding.parseTrackName( path );
  9047. this._targetGroup = targetGroup;
  9048. this._bindings = targetGroup.subscribe_( path, parsedPath );
  9049. };
  9050. THREE.PropertyBinding.Composite.prototype = {
  9051. constructor: THREE.PropertyBinding.Composite,
  9052. getValue: function( array, offset ) {
  9053. this.bind(); // bind all binding
  9054. var firstValidIndex = this._targetGroup.nCachedObjects_,
  9055. binding = this._bindings[ firstValidIndex ];
  9056. // and only call .getValue on the first
  9057. if ( binding !== undefined ) binding.getValue( array, offset );
  9058. },
  9059. setValue: function( array, offset ) {
  9060. var bindings = this._bindings;
  9061. for ( var i = this._targetGroup.nCachedObjects_,
  9062. n = bindings.length; i !== n; ++ i ) {
  9063. bindings[ i ].setValue( array, offset );
  9064. }
  9065. },
  9066. bind: function() {
  9067. var bindings = this._bindings;
  9068. for ( var i = this._targetGroup.nCachedObjects_,
  9069. n = bindings.length; i !== n; ++ i ) {
  9070. bindings[ i ].bind();
  9071. }
  9072. },
  9073. unbind: function() {
  9074. var bindings = this._bindings;
  9075. for ( var i = this._targetGroup.nCachedObjects_,
  9076. n = bindings.length; i !== n; ++ i ) {
  9077. bindings[ i ].unbind();
  9078. }
  9079. }
  9080. };
  9081. THREE.PropertyBinding.create = function( root, path, parsedPath ) {
  9082. if ( ! ( root instanceof THREE.AnimationObjectGroup ) ) {
  9083. return new THREE.PropertyBinding( root, path, parsedPath );
  9084. } else {
  9085. return new THREE.PropertyBinding.Composite( root, path, parsedPath );
  9086. }
  9087. };
  9088. THREE.PropertyBinding.parseTrackName = function( trackName ) {
  9089. // matches strings in the form of:
  9090. // nodeName.property
  9091. // nodeName.property[accessor]
  9092. // nodeName.material.property[accessor]
  9093. // uuid.property[accessor]
  9094. // uuid.objectName[objectIndex].propertyName[propertyIndex]
  9095. // parentName/nodeName.property
  9096. // parentName/parentName/nodeName.property[index]
  9097. // .bone[Armature.DEF_cog].position
  9098. // created and tested via https://regex101.com/#javascript
  9099. var re = /^(([\w]+\/)*)([\w-\d]+)?(\.([\w]+)(\[([\w\d\[\]\_. ]+)\])?)?(\.([\w.]+)(\[([\w\d\[\]\_. ]+)\])?)$/;
  9100. var matches = re.exec(trackName);
  9101. if( ! matches ) {
  9102. throw new Error( "cannot parse trackName at all: " + trackName );
  9103. }
  9104. if (matches.index === re.lastIndex) {
  9105. re.lastIndex++;
  9106. }
  9107. var results = {
  9108. // directoryName: matches[1], // (tschw) currently unused
  9109. nodeName: matches[3], // allowed to be null, specified root node.
  9110. objectName: matches[5],
  9111. objectIndex: matches[7],
  9112. propertyName: matches[9],
  9113. propertyIndex: matches[11] // allowed to be null, specifies that the whole property is set.
  9114. };
  9115. if( results.propertyName === null || results.propertyName.length === 0 ) {
  9116. throw new Error( "can not parse propertyName from trackName: " + trackName );
  9117. }
  9118. return results;
  9119. };
  9120. THREE.PropertyBinding.findNode = function( root, nodeName ) {
  9121. if( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  9122. return root;
  9123. }
  9124. // search into skeleton bones.
  9125. if( root.skeleton ) {
  9126. var searchSkeleton = function( skeleton ) {
  9127. for( var i = 0; i < skeleton.bones.length; i ++ ) {
  9128. var bone = skeleton.bones[i];
  9129. if( bone.name === nodeName ) {
  9130. return bone;
  9131. }
  9132. }
  9133. return null;
  9134. };
  9135. var bone = searchSkeleton( root.skeleton );
  9136. if( bone ) {
  9137. return bone;
  9138. }
  9139. }
  9140. // search into node subtree.
  9141. if( root.children ) {
  9142. var searchNodeSubtree = function( children ) {
  9143. for( var i = 0; i < children.length; i ++ ) {
  9144. var childNode = children[i];
  9145. if( childNode.name === nodeName || childNode.uuid === nodeName ) {
  9146. return childNode;
  9147. }
  9148. var result = searchNodeSubtree( childNode.children );
  9149. if( result ) return result;
  9150. }
  9151. return null;
  9152. };
  9153. var subTreeNode = searchNodeSubtree( root.children );
  9154. if( subTreeNode ) {
  9155. return subTreeNode;
  9156. }
  9157. }
  9158. return null;
  9159. }
  9160. // File:src/animation/PropertyMixer.js
  9161. /**
  9162. *
  9163. * Buffered scene graph property that allows weighted accumulation.
  9164. *
  9165. *
  9166. * @author Ben Houston / http://clara.io/
  9167. * @author David Sarno / http://lighthaus.us/
  9168. * @author tschw
  9169. */
  9170. THREE.PropertyMixer = function ( binding, typeName, valueSize ) {
  9171. this.binding = binding;
  9172. this.valueSize = valueSize;
  9173. var bufferType = Float64Array,
  9174. mixFunction;
  9175. switch ( typeName ) {
  9176. case 'quaternion': mixFunction = this._slerp; break;
  9177. case 'string':
  9178. case 'bool':
  9179. bufferType = Array, mixFunction = this._select; break;
  9180. default: mixFunction = this._lerp;
  9181. }
  9182. this.buffer = new bufferType( valueSize * 4 );
  9183. // layout: [ incoming | accu0 | accu1 | orig ]
  9184. //
  9185. // interpolators can use .buffer as their .result
  9186. // the data then goes to 'incoming'
  9187. //
  9188. // 'accu0' and 'accu1' are used frame-interleaved for
  9189. // the cumulative result and are compared to detect
  9190. // changes
  9191. //
  9192. // 'orig' stores the original state of the property
  9193. this._mixBufferRegion = mixFunction;
  9194. this.cumulativeWeight = 0;
  9195. this.useCount = 0;
  9196. this.referenceCount = 0;
  9197. };
  9198. THREE.PropertyMixer.prototype = {
  9199. constructor: THREE.PropertyMixer,
  9200. // accumulate data in the 'incoming' region into 'accu<i>'
  9201. accumulate: function( accuIndex, weight ) {
  9202. // note: happily accumulating nothing when weight = 0, the caller knows
  9203. // the weight and shouldn't have made the call in the first place
  9204. var buffer = this.buffer,
  9205. stride = this.valueSize,
  9206. offset = accuIndex * stride + stride,
  9207. currentWeight = this.cumulativeWeight;
  9208. if ( currentWeight === 0 ) {
  9209. // accuN := incoming * weight
  9210. for ( var i = 0; i !== stride; ++ i ) {
  9211. buffer[ offset + i ] = buffer[ i ];
  9212. }
  9213. currentWeight = weight;
  9214. } else {
  9215. // accuN := accuN + incoming * weight
  9216. currentWeight += weight;
  9217. var mix = weight / currentWeight;
  9218. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  9219. }
  9220. this.cumulativeWeight = currentWeight;
  9221. },
  9222. // apply the state of 'accu<i>' to the binding when accus differ
  9223. apply: function( accuIndex ) {
  9224. var stride = this.valueSize,
  9225. buffer = this.buffer,
  9226. offset = accuIndex * stride + stride,
  9227. weight = this.cumulativeWeight,
  9228. binding = this.binding;
  9229. this.cumulativeWeight = 0;
  9230. if ( weight < 1 ) {
  9231. // accuN := accuN + original * ( 1 - cumulativeWeight )
  9232. var originalValueOffset = stride * 3;
  9233. this._mixBufferRegion(
  9234. buffer, offset, originalValueOffset, 1 - weight, stride );
  9235. }
  9236. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  9237. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  9238. // value has changed -> update scene graph
  9239. binding.setValue( buffer, offset );
  9240. break;
  9241. }
  9242. }
  9243. },
  9244. // remember the state of the bound property and copy it to both accus
  9245. saveOriginalState: function() {
  9246. var binding = this.binding;
  9247. var buffer = this.buffer,
  9248. stride = this.valueSize,
  9249. originalValueOffset = stride * 3;
  9250. binding.getValue( buffer, originalValueOffset );
  9251. // accu[0..1] := orig -- initially detect changes against the original
  9252. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  9253. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  9254. }
  9255. this.cumulativeWeight = 0;
  9256. },
  9257. // apply the state previously taken via 'saveOriginalState' to the binding
  9258. restoreOriginalState: function() {
  9259. var originalValueOffset = this.valueSize * 3;
  9260. this.binding.setValue( this.buffer, originalValueOffset );
  9261. },
  9262. // mix functions
  9263. _select: function( buffer, dstOffset, srcOffset, t, stride ) {
  9264. if ( t >= 0.5 ) {
  9265. for ( var i = 0; i !== stride; ++ i ) {
  9266. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  9267. }
  9268. }
  9269. },
  9270. _slerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  9271. THREE.Quaternion.slerpFlat( buffer, dstOffset,
  9272. buffer, dstOffset, buffer, srcOffset, t );
  9273. },
  9274. _lerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  9275. var s = 1 - t;
  9276. for ( var i = 0; i !== stride; ++ i ) {
  9277. var j = dstOffset + i;
  9278. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  9279. }
  9280. }
  9281. };
  9282. // File:src/animation/tracks/BooleanKeyframeTrack.js
  9283. /**
  9284. *
  9285. * A Track of Boolean keyframe values.
  9286. *
  9287. *
  9288. * @author Ben Houston / http://clara.io/
  9289. * @author David Sarno / http://lighthaus.us/
  9290. * @author tschw
  9291. */
  9292. THREE.BooleanKeyframeTrack = function ( name, times, values ) {
  9293. THREE.KeyframeTrack.call( this, name, times, values );
  9294. };
  9295. THREE.BooleanKeyframeTrack.prototype =
  9296. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9297. constructor: THREE.BooleanKeyframeTrack,
  9298. ValueTypeName: 'bool',
  9299. ValueBufferType: Array,
  9300. DefaultInterpolation: THREE.IntepolateDiscrete,
  9301. InterpolantFactoryMethodLinear: undefined,
  9302. InterpolantFactoryMethodSmooth: undefined
  9303. // Note: Actually this track could have a optimized / compressed
  9304. // representation of a single value and a custom interpolant that
  9305. // computes "firstValue ^ isOdd( index )".
  9306. } );
  9307. // File:src/animation/tracks/NumberKeyframeTrack.js
  9308. /**
  9309. *
  9310. * A Track of numeric keyframe values.
  9311. *
  9312. * @author Ben Houston / http://clara.io/
  9313. * @author David Sarno / http://lighthaus.us/
  9314. * @author tschw
  9315. */
  9316. THREE.NumberKeyframeTrack = function ( name, times, values, interpolation ) {
  9317. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9318. };
  9319. THREE.NumberKeyframeTrack.prototype =
  9320. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9321. constructor: THREE.NumberKeyframeTrack,
  9322. ValueTypeName: 'number',
  9323. // ValueBufferType is inherited
  9324. // DefaultInterpolation is inherited
  9325. } );
  9326. // File:src/animation/tracks/QuaternionKeyframeTrack.js
  9327. /**
  9328. *
  9329. * A Track of quaternion keyframe values.
  9330. *
  9331. * @author Ben Houston / http://clara.io/
  9332. * @author David Sarno / http://lighthaus.us/
  9333. * @author tschw
  9334. */
  9335. THREE.QuaternionKeyframeTrack = function ( name, times, values, interpolation ) {
  9336. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9337. };
  9338. THREE.QuaternionKeyframeTrack.prototype =
  9339. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9340. constructor: THREE.QuaternionKeyframeTrack,
  9341. ValueTypeName: 'quaternion',
  9342. // ValueBufferType is inherited
  9343. DefaultInterpolation: THREE.InterpolateLinear,
  9344. InterpolantFactoryMethodLinear: function( result ) {
  9345. return new THREE.QuaternionLinearInterpolant(
  9346. this.times, this.values, this.getValueSize(), result );
  9347. },
  9348. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  9349. } );
  9350. // File:src/animation/tracks/StringKeyframeTrack.js
  9351. /**
  9352. *
  9353. * A Track that interpolates Strings
  9354. *
  9355. *
  9356. * @author Ben Houston / http://clara.io/
  9357. * @author David Sarno / http://lighthaus.us/
  9358. * @author tschw
  9359. */
  9360. THREE.StringKeyframeTrack = function ( name, times, values, interpolation ) {
  9361. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9362. };
  9363. THREE.StringKeyframeTrack.prototype =
  9364. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9365. constructor: THREE.StringKeyframeTrack,
  9366. ValueTypeName: 'string',
  9367. ValueBufferType: Array,
  9368. DefaultInterpolation: THREE.IntepolateDiscrete,
  9369. InterpolantFactoryMethodLinear: undefined,
  9370. InterpolantFactoryMethodSmooth: undefined
  9371. } );
  9372. // File:src/animation/tracks/VectorKeyframeTrack.js
  9373. /**
  9374. *
  9375. * A Track of vectored keyframe values.
  9376. *
  9377. *
  9378. * @author Ben Houston / http://clara.io/
  9379. * @author David Sarno / http://lighthaus.us/
  9380. * @author tschw
  9381. */
  9382. THREE.VectorKeyframeTrack = function ( name, times, values, interpolation ) {
  9383. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9384. };
  9385. THREE.VectorKeyframeTrack.prototype =
  9386. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9387. constructor: THREE.VectorKeyframeTrack,
  9388. ValueTypeName: 'vector'
  9389. // ValueBufferType is inherited
  9390. // DefaultInterpolation is inherited
  9391. } );
  9392. // File:src/audio/Audio.js
  9393. /**
  9394. * @author mrdoob / http://mrdoob.com/
  9395. */
  9396. THREE.Audio = function ( listener ) {
  9397. THREE.Object3D.call( this );
  9398. this.type = 'Audio';
  9399. this.context = listener.context;
  9400. this.source = this.context.createBufferSource();
  9401. this.source.onended = this.onEnded.bind( this );
  9402. this.gain = this.context.createGain();
  9403. this.gain.connect( this.context.destination );
  9404. this.panner = this.context.createPanner();
  9405. this.panner.connect( this.gain );
  9406. this.autoplay = false;
  9407. this.startTime = 0;
  9408. this.playbackRate = 1;
  9409. this.isPlaying = false;
  9410. };
  9411. THREE.Audio.prototype = Object.create( THREE.Object3D.prototype );
  9412. THREE.Audio.prototype.constructor = THREE.Audio;
  9413. THREE.Audio.prototype.load = function ( file ) {
  9414. var scope = this;
  9415. var request = new XMLHttpRequest();
  9416. request.open( 'GET', file, true );
  9417. request.responseType = 'arraybuffer';
  9418. request.onload = function ( e ) {
  9419. scope.context.decodeAudioData( this.response, function ( buffer ) {
  9420. scope.source.buffer = buffer;
  9421. if ( scope.autoplay ) scope.play();
  9422. } );
  9423. };
  9424. request.send();
  9425. return this;
  9426. };
  9427. THREE.Audio.prototype.play = function () {
  9428. if ( this.isPlaying === true ) {
  9429. console.warn( 'THREE.Audio: Audio is already playing.' );
  9430. return;
  9431. }
  9432. var source = this.context.createBufferSource();
  9433. source.buffer = this.source.buffer;
  9434. source.loop = this.source.loop;
  9435. source.onended = this.source.onended;
  9436. source.start( 0, this.startTime );
  9437. source.playbackRate.value = this.playbackRate;
  9438. this.isPlaying = true;
  9439. this.source = source;
  9440. this.connect();
  9441. };
  9442. THREE.Audio.prototype.pause = function () {
  9443. this.source.stop();
  9444. this.startTime = this.context.currentTime;
  9445. };
  9446. THREE.Audio.prototype.stop = function () {
  9447. this.source.stop();
  9448. this.startTime = 0;
  9449. };
  9450. THREE.Audio.prototype.connect = function () {
  9451. if ( this.filter !== undefined ) {
  9452. this.source.connect( this.filter );
  9453. this.filter.connect( this.panner );
  9454. } else {
  9455. this.source.connect( this.panner );
  9456. }
  9457. };
  9458. THREE.Audio.prototype.disconnect = function () {
  9459. if ( this.filter !== undefined ) {
  9460. this.source.disconnect( this.filter );
  9461. this.filter.disconnect( this.panner );
  9462. } else {
  9463. this.source.disconnect( this.panner );
  9464. }
  9465. };
  9466. THREE.Audio.prototype.setFilter = function ( value ) {
  9467. if ( this.isPlaying === true ) {
  9468. this.disconnect();
  9469. this.filter = value;
  9470. this.connect();
  9471. } else {
  9472. this.filter = value;
  9473. }
  9474. };
  9475. THREE.Audio.prototype.getFilter = function () {
  9476. return this.filter;
  9477. };
  9478. THREE.Audio.prototype.setPlaybackRate = function ( value ) {
  9479. this.playbackRate = value;
  9480. if ( this.isPlaying === true ) {
  9481. this.source.playbackRate.value = this.playbackRate;
  9482. }
  9483. };
  9484. THREE.Audio.prototype.getPlaybackRate = function () {
  9485. return this.playbackRate;
  9486. };
  9487. THREE.Audio.prototype.onEnded = function() {
  9488. this.isPlaying = false;
  9489. };
  9490. THREE.Audio.prototype.setLoop = function ( value ) {
  9491. this.source.loop = value;
  9492. };
  9493. THREE.Audio.prototype.getLoop = function () {
  9494. return this.source.loop;
  9495. };
  9496. THREE.Audio.prototype.setRefDistance = function ( value ) {
  9497. this.panner.refDistance = value;
  9498. };
  9499. THREE.Audio.prototype.getRefDistance = function () {
  9500. return this.panner.refDistance;
  9501. };
  9502. THREE.Audio.prototype.setRolloffFactor = function ( value ) {
  9503. this.panner.rolloffFactor = value;
  9504. };
  9505. THREE.Audio.prototype.getRolloffFactor = function () {
  9506. return this.panner.rolloffFactor;
  9507. };
  9508. THREE.Audio.prototype.setVolume = function ( value ) {
  9509. this.gain.gain.value = value;
  9510. };
  9511. THREE.Audio.prototype.getVolume = function () {
  9512. return this.gain.gain.value;
  9513. };
  9514. THREE.Audio.prototype.updateMatrixWorld = ( function () {
  9515. var position = new THREE.Vector3();
  9516. return function updateMatrixWorld( force ) {
  9517. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  9518. position.setFromMatrixPosition( this.matrixWorld );
  9519. this.panner.setPosition( position.x, position.y, position.z );
  9520. };
  9521. } )();
  9522. // File:src/audio/AudioListener.js
  9523. /**
  9524. * @author mrdoob / http://mrdoob.com/
  9525. */
  9526. THREE.AudioListener = function () {
  9527. THREE.Object3D.call( this );
  9528. this.type = 'AudioListener';
  9529. this.context = new ( window.AudioContext || window.webkitAudioContext )();
  9530. };
  9531. THREE.AudioListener.prototype = Object.create( THREE.Object3D.prototype );
  9532. THREE.AudioListener.prototype.constructor = THREE.AudioListener;
  9533. THREE.AudioListener.prototype.updateMatrixWorld = ( function () {
  9534. var position = new THREE.Vector3();
  9535. var quaternion = new THREE.Quaternion();
  9536. var scale = new THREE.Vector3();
  9537. var orientation = new THREE.Vector3();
  9538. return function updateMatrixWorld( force ) {
  9539. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  9540. var listener = this.context.listener;
  9541. var up = this.up;
  9542. this.matrixWorld.decompose( position, quaternion, scale );
  9543. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  9544. listener.setPosition( position.x, position.y, position.z );
  9545. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  9546. };
  9547. } )();
  9548. // File:src/cameras/Camera.js
  9549. /**
  9550. * @author mrdoob / http://mrdoob.com/
  9551. * @author mikael emtinger / http://gomo.se/
  9552. * @author WestLangley / http://github.com/WestLangley
  9553. */
  9554. THREE.Camera = function () {
  9555. THREE.Object3D.call( this );
  9556. this.type = 'Camera';
  9557. this.matrixWorldInverse = new THREE.Matrix4();
  9558. this.projectionMatrix = new THREE.Matrix4();
  9559. };
  9560. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  9561. THREE.Camera.prototype.constructor = THREE.Camera;
  9562. THREE.Camera.prototype.getWorldDirection = function () {
  9563. var quaternion = new THREE.Quaternion();
  9564. return function ( optionalTarget ) {
  9565. var result = optionalTarget || new THREE.Vector3();
  9566. this.getWorldQuaternion( quaternion );
  9567. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  9568. };
  9569. }();
  9570. THREE.Camera.prototype.lookAt = function () {
  9571. // This routine does not support cameras with rotated and/or translated parent(s)
  9572. var m1 = new THREE.Matrix4();
  9573. return function ( vector ) {
  9574. m1.lookAt( this.position, vector, this.up );
  9575. this.quaternion.setFromRotationMatrix( m1 );
  9576. };
  9577. }();
  9578. THREE.Camera.prototype.clone = function () {
  9579. return new this.constructor().copy( this );
  9580. };
  9581. THREE.Camera.prototype.copy = function ( source ) {
  9582. THREE.Object3D.prototype.copy.call( this, source );
  9583. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  9584. this.projectionMatrix.copy( source.projectionMatrix );
  9585. return this;
  9586. };
  9587. // File:src/cameras/CubeCamera.js
  9588. /**
  9589. * Camera for rendering cube maps
  9590. * - renders scene into axis-aligned cube
  9591. *
  9592. * @author alteredq / http://alteredqualia.com/
  9593. */
  9594. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  9595. THREE.Object3D.call( this );
  9596. this.type = 'CubeCamera';
  9597. var fov = 90, aspect = 1;
  9598. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9599. cameraPX.up.set( 0, - 1, 0 );
  9600. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  9601. this.add( cameraPX );
  9602. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9603. cameraNX.up.set( 0, - 1, 0 );
  9604. cameraNX.lookAt( new THREE.Vector3( - 1, 0, 0 ) );
  9605. this.add( cameraNX );
  9606. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9607. cameraPY.up.set( 0, 0, 1 );
  9608. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  9609. this.add( cameraPY );
  9610. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9611. cameraNY.up.set( 0, 0, - 1 );
  9612. cameraNY.lookAt( new THREE.Vector3( 0, - 1, 0 ) );
  9613. this.add( cameraNY );
  9614. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9615. cameraPZ.up.set( 0, - 1, 0 );
  9616. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  9617. this.add( cameraPZ );
  9618. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9619. cameraNZ.up.set( 0, - 1, 0 );
  9620. cameraNZ.lookAt( new THREE.Vector3( 0, 0, - 1 ) );
  9621. this.add( cameraNZ );
  9622. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  9623. this.updateCubeMap = function ( renderer, scene ) {
  9624. if ( this.parent === null ) this.updateMatrixWorld();
  9625. var renderTarget = this.renderTarget;
  9626. var generateMipmaps = renderTarget.texture.generateMipmaps;
  9627. renderTarget.texture.generateMipmaps = false;
  9628. renderTarget.activeCubeFace = 0;
  9629. renderer.render( scene, cameraPX, renderTarget );
  9630. renderTarget.activeCubeFace = 1;
  9631. renderer.render( scene, cameraNX, renderTarget );
  9632. renderTarget.activeCubeFace = 2;
  9633. renderer.render( scene, cameraPY, renderTarget );
  9634. renderTarget.activeCubeFace = 3;
  9635. renderer.render( scene, cameraNY, renderTarget );
  9636. renderTarget.activeCubeFace = 4;
  9637. renderer.render( scene, cameraPZ, renderTarget );
  9638. renderTarget.texture.generateMipmaps = generateMipmaps;
  9639. renderTarget.activeCubeFace = 5;
  9640. renderer.render( scene, cameraNZ, renderTarget );
  9641. renderer.setRenderTarget( null );
  9642. };
  9643. };
  9644. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  9645. THREE.CubeCamera.prototype.constructor = THREE.CubeCamera;
  9646. // File:src/cameras/OrthographicCamera.js
  9647. /**
  9648. * @author alteredq / http://alteredqualia.com/
  9649. */
  9650. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  9651. THREE.Camera.call( this );
  9652. this.type = 'OrthographicCamera';
  9653. this.zoom = 1;
  9654. this.left = left;
  9655. this.right = right;
  9656. this.top = top;
  9657. this.bottom = bottom;
  9658. this.near = ( near !== undefined ) ? near : 0.1;
  9659. this.far = ( far !== undefined ) ? far : 2000;
  9660. this.updateProjectionMatrix();
  9661. };
  9662. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  9663. THREE.OrthographicCamera.prototype.constructor = THREE.OrthographicCamera;
  9664. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  9665. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9666. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9667. var cx = ( this.right + this.left ) / 2;
  9668. var cy = ( this.top + this.bottom ) / 2;
  9669. this.projectionMatrix.makeOrthographic( cx - dx, cx + dx, cy + dy, cy - dy, this.near, this.far );
  9670. };
  9671. THREE.OrthographicCamera.prototype.copy = function ( source ) {
  9672. THREE.Camera.prototype.copy.call( this, source );
  9673. this.left = source.left;
  9674. this.right = source.right;
  9675. this.top = source.top;
  9676. this.bottom = source.bottom;
  9677. this.near = source.near;
  9678. this.far = source.far;
  9679. this.zoom = source.zoom;
  9680. return this;
  9681. };
  9682. THREE.OrthographicCamera.prototype.toJSON = function ( meta ) {
  9683. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9684. data.object.zoom = this.zoom;
  9685. data.object.left = this.left;
  9686. data.object.right = this.right;
  9687. data.object.top = this.top;
  9688. data.object.bottom = this.bottom;
  9689. data.object.near = this.near;
  9690. data.object.far = this.far;
  9691. return data;
  9692. };
  9693. // File:src/cameras/PerspectiveCamera.js
  9694. /**
  9695. * @author mrdoob / http://mrdoob.com/
  9696. * @author greggman / http://games.greggman.com/
  9697. * @author zz85 / http://www.lab4games.net/zz85/blog
  9698. */
  9699. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  9700. THREE.Camera.call( this );
  9701. this.type = 'PerspectiveCamera';
  9702. this.zoom = 1;
  9703. this.fov = fov !== undefined ? fov : 50;
  9704. this.aspect = aspect !== undefined ? aspect : 1;
  9705. this.near = near !== undefined ? near : 0.1;
  9706. this.far = far !== undefined ? far : 2000;
  9707. this.updateProjectionMatrix();
  9708. };
  9709. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  9710. THREE.PerspectiveCamera.prototype.constructor = THREE.PerspectiveCamera;
  9711. /**
  9712. * Uses Focal Length (in mm) to estimate and set FOV
  9713. * 35mm (full-frame) camera is used if frame size is not specified;
  9714. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  9715. */
  9716. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  9717. if ( frameHeight === undefined ) frameHeight = 24;
  9718. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  9719. this.updateProjectionMatrix();
  9720. };
  9721. /**
  9722. * Sets an offset in a larger frustum. This is useful for multi-window or
  9723. * multi-monitor/multi-machine setups.
  9724. *
  9725. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  9726. * the monitors are in grid like this
  9727. *
  9728. * +---+---+---+
  9729. * | A | B | C |
  9730. * +---+---+---+
  9731. * | D | E | F |
  9732. * +---+---+---+
  9733. *
  9734. * then for each monitor you would call it like this
  9735. *
  9736. * var w = 1920;
  9737. * var h = 1080;
  9738. * var fullWidth = w * 3;
  9739. * var fullHeight = h * 2;
  9740. *
  9741. * --A--
  9742. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  9743. * --B--
  9744. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  9745. * --C--
  9746. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  9747. * --D--
  9748. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  9749. * --E--
  9750. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  9751. * --F--
  9752. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  9753. *
  9754. * Note there is no reason monitors have to be the same size or in a grid.
  9755. */
  9756. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  9757. this.fullWidth = fullWidth;
  9758. this.fullHeight = fullHeight;
  9759. this.x = x;
  9760. this.y = y;
  9761. this.width = width;
  9762. this.height = height;
  9763. this.updateProjectionMatrix();
  9764. };
  9765. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  9766. var fov = THREE.Math.radToDeg( 2 * Math.atan( Math.tan( THREE.Math.degToRad( this.fov ) * 0.5 ) / this.zoom ) );
  9767. if ( this.fullWidth ) {
  9768. var aspect = this.fullWidth / this.fullHeight;
  9769. var top = Math.tan( THREE.Math.degToRad( fov * 0.5 ) ) * this.near;
  9770. var bottom = - top;
  9771. var left = aspect * bottom;
  9772. var right = aspect * top;
  9773. var width = Math.abs( right - left );
  9774. var height = Math.abs( top - bottom );
  9775. this.projectionMatrix.makeFrustum(
  9776. left + this.x * width / this.fullWidth,
  9777. left + ( this.x + this.width ) * width / this.fullWidth,
  9778. top - ( this.y + this.height ) * height / this.fullHeight,
  9779. top - this.y * height / this.fullHeight,
  9780. this.near,
  9781. this.far
  9782. );
  9783. } else {
  9784. this.projectionMatrix.makePerspective( fov, this.aspect, this.near, this.far );
  9785. }
  9786. };
  9787. THREE.PerspectiveCamera.prototype.copy = function ( source ) {
  9788. THREE.Camera.prototype.copy.call( this, source );
  9789. this.fov = source.fov;
  9790. this.aspect = source.aspect;
  9791. this.near = source.near;
  9792. this.far = source.far;
  9793. this.zoom = source.zoom;
  9794. return this;
  9795. };
  9796. THREE.PerspectiveCamera.prototype.toJSON = function ( meta ) {
  9797. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9798. data.object.zoom = this.zoom;
  9799. data.object.fov = this.fov;
  9800. data.object.aspect = this.aspect;
  9801. data.object.near = this.near;
  9802. data.object.far = this.far;
  9803. return data;
  9804. };
  9805. // File:src/lights/Light.js
  9806. /**
  9807. * @author mrdoob / http://mrdoob.com/
  9808. * @author alteredq / http://alteredqualia.com/
  9809. */
  9810. THREE.Light = function ( color ) {
  9811. THREE.Object3D.call( this );
  9812. this.type = 'Light';
  9813. this.color = new THREE.Color( color );
  9814. this.receiveShadow = undefined;
  9815. };
  9816. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  9817. THREE.Light.prototype.constructor = THREE.Light;
  9818. THREE.Light.prototype.copy = function ( source ) {
  9819. THREE.Object3D.prototype.copy.call( this, source );
  9820. this.color.copy( source.color );
  9821. return this;
  9822. };
  9823. THREE.Light.prototype.toJSON = function ( meta ) {
  9824. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9825. data.object.color = this.color.getHex();
  9826. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  9827. if ( this.intensity !== undefined ) data.object.intensity = this.intensity;
  9828. if ( this.distance !== undefined ) data.object.distance = this.distance;
  9829. if ( this.angle !== undefined ) data.object.angle = this.angle;
  9830. if ( this.decay !== undefined ) data.object.decay = this.decay;
  9831. if ( this.exponent !== undefined ) data.object.exponent = this.exponent;
  9832. return data;
  9833. };
  9834. // File:src/lights/LightShadow.js
  9835. /**
  9836. * @author mrdoob / http://mrdoob.com/
  9837. */
  9838. THREE.LightShadow = function ( camera ) {
  9839. this.camera = camera;
  9840. this.bias = 0;
  9841. this.darkness = 1;
  9842. this.mapSize = new THREE.Vector2( 512, 512 );
  9843. this.map = null;
  9844. this.matrix = null;
  9845. };
  9846. THREE.LightShadow.prototype = {
  9847. constructor: THREE.LightShadow,
  9848. copy: function ( source ) {
  9849. this.camera = source.camera.clone();
  9850. this.bias = source.bias;
  9851. this.darkness = source.darkness;
  9852. this.mapSize.copy( source.mapSize );
  9853. return this;
  9854. },
  9855. clone: function () {
  9856. return new this.constructor().copy( this );
  9857. }
  9858. };
  9859. // File:src/lights/AmbientLight.js
  9860. /**
  9861. * @author mrdoob / http://mrdoob.com/
  9862. */
  9863. THREE.AmbientLight = function ( color ) {
  9864. THREE.Light.call( this, color );
  9865. this.type = 'AmbientLight';
  9866. this.castShadow = undefined;
  9867. };
  9868. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  9869. THREE.AmbientLight.prototype.constructor = THREE.AmbientLight;
  9870. // File:src/lights/DirectionalLight.js
  9871. /**
  9872. * @author mrdoob / http://mrdoob.com/
  9873. * @author alteredq / http://alteredqualia.com/
  9874. */
  9875. THREE.DirectionalLight = function ( color, intensity ) {
  9876. THREE.Light.call( this, color );
  9877. this.type = 'DirectionalLight';
  9878. this.position.set( 0, 1, 0 );
  9879. this.updateMatrix();
  9880. this.target = new THREE.Object3D();
  9881. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  9882. this.shadow = new THREE.LightShadow( new THREE.OrthographicCamera( - 500, 500, 500, - 500, 50, 5000 ) );
  9883. };
  9884. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  9885. THREE.DirectionalLight.prototype.constructor = THREE.DirectionalLight;
  9886. THREE.DirectionalLight.prototype.copy = function ( source ) {
  9887. THREE.Light.prototype.copy.call( this, source );
  9888. this.intensity = source.intensity;
  9889. this.target = source.target.clone();
  9890. this.shadow = source.shadow.clone();
  9891. return this;
  9892. };
  9893. // File:src/lights/HemisphereLight.js
  9894. /**
  9895. * @author alteredq / http://alteredqualia.com/
  9896. */
  9897. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  9898. THREE.Light.call( this, skyColor );
  9899. this.type = 'HemisphereLight';
  9900. this.castShadow = undefined;
  9901. this.position.set( 0, 1, 0 );
  9902. this.updateMatrix();
  9903. this.groundColor = new THREE.Color( groundColor );
  9904. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  9905. };
  9906. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  9907. THREE.HemisphereLight.prototype.constructor = THREE.HemisphereLight;
  9908. THREE.HemisphereLight.prototype.copy = function ( source ) {
  9909. THREE.Light.prototype.copy.call( this, source );
  9910. this.groundColor.copy( source.groundColor );
  9911. this.intensity = source.intensity;
  9912. return this;
  9913. };
  9914. // File:src/lights/PointLight.js
  9915. /**
  9916. * @author mrdoob / http://mrdoob.com/
  9917. */
  9918. THREE.PointLight = function ( color, intensity, distance, decay ) {
  9919. THREE.Light.call( this, color );
  9920. this.type = 'PointLight';
  9921. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  9922. this.distance = ( distance !== undefined ) ? distance : 0;
  9923. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  9924. this.shadow = new THREE.LightShadow( new THREE.PerspectiveCamera( 90, 1, 1, 500 ) );
  9925. };
  9926. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  9927. THREE.PointLight.prototype.constructor = THREE.PointLight;
  9928. THREE.PointLight.prototype.copy = function ( source ) {
  9929. THREE.Light.prototype.copy.call( this, source );
  9930. this.intensity = source.intensity;
  9931. this.distance = source.distance;
  9932. this.decay = source.decay;
  9933. this.shadow = source.shadow.clone();
  9934. return this;
  9935. };
  9936. // File:src/lights/SpotLight.js
  9937. /**
  9938. * @author alteredq / http://alteredqualia.com/
  9939. */
  9940. THREE.SpotLight = function ( color, intensity, distance, angle, exponent, decay ) {
  9941. THREE.Light.call( this, color );
  9942. this.type = 'SpotLight';
  9943. this.position.set( 0, 1, 0 );
  9944. this.updateMatrix();
  9945. this.target = new THREE.Object3D();
  9946. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  9947. this.distance = ( distance !== undefined ) ? distance : 0;
  9948. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  9949. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  9950. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  9951. this.shadow = new THREE.LightShadow( new THREE.PerspectiveCamera( 50, 1, 50, 5000 ) );
  9952. };
  9953. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  9954. THREE.SpotLight.prototype.constructor = THREE.SpotLight;
  9955. THREE.SpotLight.prototype.copy = function ( source ) {
  9956. THREE.Light.prototype.copy.call( this, source );
  9957. this.intensity = source.intensity;
  9958. this.distance = source.distance;
  9959. this.angle = source.angle;
  9960. this.exponent = source.exponent;
  9961. this.decay = source.decay;
  9962. this.target = source.target.clone();
  9963. this.shadow = source.shadow.clone();
  9964. return this;
  9965. };
  9966. // File:src/loaders/Cache.js
  9967. /**
  9968. * @author mrdoob / http://mrdoob.com/
  9969. */
  9970. THREE.Cache = {
  9971. enabled: false,
  9972. files: {},
  9973. add: function ( key, file ) {
  9974. if ( this.enabled === false ) return;
  9975. // console.log( 'THREE.Cache', 'Adding key:', key );
  9976. this.files[ key ] = file;
  9977. },
  9978. get: function ( key ) {
  9979. if ( this.enabled === false ) return;
  9980. // console.log( 'THREE.Cache', 'Checking key:', key );
  9981. return this.files[ key ];
  9982. },
  9983. remove: function ( key ) {
  9984. delete this.files[ key ];
  9985. },
  9986. clear: function () {
  9987. this.files = {};
  9988. }
  9989. };
  9990. // File:src/loaders/Loader.js
  9991. /**
  9992. * @author alteredq / http://alteredqualia.com/
  9993. */
  9994. THREE.Loader = function () {
  9995. this.onLoadStart = function () {};
  9996. this.onLoadProgress = function () {};
  9997. this.onLoadComplete = function () {};
  9998. };
  9999. THREE.Loader.prototype = {
  10000. constructor: THREE.Loader,
  10001. crossOrigin: undefined,
  10002. extractUrlBase: function ( url ) {
  10003. var parts = url.split( '/' );
  10004. if ( parts.length === 1 ) return './';
  10005. parts.pop();
  10006. return parts.join( '/' ) + '/';
  10007. },
  10008. initMaterials: function ( materials, texturePath, crossOrigin ) {
  10009. var array = [];
  10010. for ( var i = 0; i < materials.length; ++ i ) {
  10011. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  10012. }
  10013. return array;
  10014. },
  10015. createMaterial: ( function () {
  10016. var color, textureLoader, materialLoader;
  10017. return function ( m, texturePath, crossOrigin ) {
  10018. if ( color === undefined ) color = new THREE.Color();
  10019. if ( textureLoader === undefined ) textureLoader = new THREE.TextureLoader();
  10020. if ( materialLoader === undefined ) materialLoader = new THREE.MaterialLoader();
  10021. // convert from old material format
  10022. var textures = {};
  10023. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  10024. var fullPath = texturePath + path;
  10025. var loader = THREE.Loader.Handlers.get( fullPath );
  10026. var texture;
  10027. if ( loader !== null ) {
  10028. texture = loader.load( fullPath );
  10029. } else {
  10030. textureLoader.setCrossOrigin( crossOrigin );
  10031. texture = textureLoader.load( fullPath );
  10032. }
  10033. if ( repeat !== undefined ) {
  10034. texture.repeat.fromArray( repeat );
  10035. if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  10036. if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  10037. }
  10038. if ( offset !== undefined ) {
  10039. texture.offset.fromArray( offset );
  10040. }
  10041. if ( wrap !== undefined ) {
  10042. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = THREE.RepeatWrapping;
  10043. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = THREE.MirroredRepeatWrapping;
  10044. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = THREE.RepeatWrapping;
  10045. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = THREE.MirroredRepeatWrapping;
  10046. }
  10047. if ( anisotropy !== undefined ) {
  10048. texture.anisotropy = anisotropy;
  10049. }
  10050. var uuid = THREE.Math.generateUUID();
  10051. textures[ uuid ] = texture;
  10052. return uuid;
  10053. }
  10054. //
  10055. var json = {
  10056. uuid: THREE.Math.generateUUID(),
  10057. type: 'MeshLambertMaterial'
  10058. };
  10059. for ( var name in m ) {
  10060. var value = m[ name ];
  10061. switch ( name ) {
  10062. case 'DbgColor':
  10063. if ( json.color === undefined ) json.color = value;
  10064. break;
  10065. case 'DbgIndex':
  10066. case 'opticalDensity':
  10067. case 'illumination':
  10068. // These were never supported
  10069. break;
  10070. case 'DbgName':
  10071. json.name = value;
  10072. break;
  10073. case 'blending':
  10074. json.blending = THREE[ value ];
  10075. break;
  10076. case 'colorAmbient':
  10077. console.warn( 'THREE.Loader.createMaterial: colorAmbient is no longer supported' );
  10078. break;
  10079. case 'colorDiffuse':
  10080. json.color = color.fromArray( value ).getHex();
  10081. break;
  10082. case 'colorSpecular':
  10083. json.specular = color.fromArray( value ).getHex();
  10084. break;
  10085. case 'colorEmissive':
  10086. json.emissive = color.fromArray( value ).getHex();
  10087. break;
  10088. case 'specularCoef':
  10089. json.shininess = value;
  10090. break;
  10091. case 'shading':
  10092. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  10093. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  10094. break;
  10095. case 'mapDiffuse':
  10096. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  10097. break;
  10098. case 'mapDiffuseRepeat':
  10099. case 'mapDiffuseOffset':
  10100. case 'mapDiffuseWrap':
  10101. case 'mapDiffuseAnisotropy':
  10102. break;
  10103. case 'mapLight':
  10104. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  10105. break;
  10106. case 'mapLightRepeat':
  10107. case 'mapLightOffset':
  10108. case 'mapLightWrap':
  10109. case 'mapLightAnisotropy':
  10110. break;
  10111. case 'mapAO':
  10112. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  10113. break;
  10114. case 'mapAORepeat':
  10115. case 'mapAOOffset':
  10116. case 'mapAOWrap':
  10117. case 'mapAOAnisotropy':
  10118. break;
  10119. case 'mapBump':
  10120. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  10121. break;
  10122. case 'mapBumpScale':
  10123. json.bumpScale = value;
  10124. break;
  10125. case 'mapBumpRepeat':
  10126. case 'mapBumpOffset':
  10127. case 'mapBumpWrap':
  10128. case 'mapBumpAnisotropy':
  10129. break;
  10130. case 'mapNormal':
  10131. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  10132. break;
  10133. case 'mapNormalFactor':
  10134. json.normalScale = [ value, value ];
  10135. break;
  10136. case 'mapNormalRepeat':
  10137. case 'mapNormalOffset':
  10138. case 'mapNormalWrap':
  10139. case 'mapNormalAnisotropy':
  10140. break;
  10141. case 'mapSpecular':
  10142. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  10143. break;
  10144. case 'mapSpecularRepeat':
  10145. case 'mapSpecularOffset':
  10146. case 'mapSpecularWrap':
  10147. case 'mapSpecularAnisotropy':
  10148. break;
  10149. case 'mapAlpha':
  10150. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  10151. break;
  10152. case 'mapAlphaRepeat':
  10153. case 'mapAlphaOffset':
  10154. case 'mapAlphaWrap':
  10155. case 'mapAlphaAnisotropy':
  10156. break;
  10157. case 'flipSided':
  10158. json.side = THREE.BackSide;
  10159. break;
  10160. case 'doubleSided':
  10161. json.side = THREE.DoubleSide;
  10162. break;
  10163. case 'transparency':
  10164. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  10165. json.opacity = value;
  10166. break;
  10167. case 'opacity':
  10168. case 'transparent':
  10169. case 'depthTest':
  10170. case 'depthWrite':
  10171. case 'transparent':
  10172. case 'visible':
  10173. case 'wireframe':
  10174. json[ name ] = value;
  10175. break;
  10176. case 'vertexColors':
  10177. if ( value === true ) json.vertexColors = THREE.VertexColors;
  10178. if ( value === 'face' ) json.vertexColors = THREE.FaceColors;
  10179. break;
  10180. default:
  10181. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  10182. break;
  10183. }
  10184. }
  10185. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  10186. if ( json.opacity < 1 ) json.transparent = true;
  10187. materialLoader.setTextures( textures );
  10188. return materialLoader.parse( json );
  10189. };
  10190. } )()
  10191. };
  10192. THREE.Loader.Handlers = {
  10193. handlers: [],
  10194. add: function ( regex, loader ) {
  10195. this.handlers.push( regex, loader );
  10196. },
  10197. get: function ( file ) {
  10198. var handlers = this.handlers;
  10199. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  10200. var regex = handlers[ i ];
  10201. var loader = handlers[ i + 1 ];
  10202. if ( regex.test( file ) ) {
  10203. return loader;
  10204. }
  10205. }
  10206. return null;
  10207. }
  10208. };
  10209. // File:src/loaders/XHRLoader.js
  10210. /**
  10211. * @author mrdoob / http://mrdoob.com/
  10212. */
  10213. THREE.XHRLoader = function ( manager ) {
  10214. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10215. };
  10216. THREE.XHRLoader.prototype = {
  10217. constructor: THREE.XHRLoader,
  10218. load: function ( url, onLoad, onProgress, onError ) {
  10219. if ( this.path !== undefined ) url = this.path + url;
  10220. var scope = this;
  10221. var cached = THREE.Cache.get( url );
  10222. if ( cached !== undefined ) {
  10223. if ( onLoad ) {
  10224. setTimeout( function () {
  10225. onLoad( cached );
  10226. }, 0 );
  10227. }
  10228. return cached;
  10229. }
  10230. var request = new XMLHttpRequest();
  10231. request.open( 'GET', url, true );
  10232. request.addEventListener( 'load', function ( event ) {
  10233. var response = event.target.response;
  10234. THREE.Cache.add( url, response );
  10235. if ( onLoad ) onLoad( response );
  10236. scope.manager.itemEnd( url );
  10237. }, false );
  10238. if ( onProgress !== undefined ) {
  10239. request.addEventListener( 'progress', function ( event ) {
  10240. onProgress( event );
  10241. }, false );
  10242. }
  10243. request.addEventListener( 'error', function ( event ) {
  10244. if ( onError ) onError( event );
  10245. scope.manager.itemError( url );
  10246. }, false );
  10247. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  10248. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  10249. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  10250. request.send( null );
  10251. scope.manager.itemStart( url );
  10252. return request;
  10253. },
  10254. setCrossOrigin: function ( value ) {
  10255. this.crossOrigin = value;
  10256. },
  10257. setResponseType: function ( value ) {
  10258. this.responseType = value;
  10259. },
  10260. setPath: function ( value ) {
  10261. this.path = value;
  10262. },
  10263. setWithCredentials: function ( value ) {
  10264. this.withCredentials = value;
  10265. }
  10266. };
  10267. // File:src/loaders/ImageLoader.js
  10268. /**
  10269. * @author mrdoob / http://mrdoob.com/
  10270. */
  10271. THREE.ImageLoader = function ( manager ) {
  10272. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10273. };
  10274. THREE.ImageLoader.prototype = {
  10275. constructor: THREE.ImageLoader,
  10276. load: function ( url, onLoad, onProgress, onError ) {
  10277. if ( this.path !== undefined ) url = this.path + url;
  10278. var scope = this;
  10279. var cached = THREE.Cache.get( url );
  10280. if ( cached !== undefined ) {
  10281. scope.manager.itemStart( url );
  10282. if ( onLoad ) {
  10283. setTimeout( function () {
  10284. onLoad( cached );
  10285. scope.manager.itemEnd( url );
  10286. }, 0 );
  10287. } else {
  10288. scope.manager.itemEnd( url );
  10289. }
  10290. return cached;
  10291. }
  10292. var image = document.createElement( 'img' );
  10293. image.addEventListener( 'load', function ( event ) {
  10294. THREE.Cache.add( url, this );
  10295. if ( onLoad ) onLoad( this );
  10296. scope.manager.itemEnd( url );
  10297. }, false );
  10298. if ( onProgress !== undefined ) {
  10299. image.addEventListener( 'progress', function ( event ) {
  10300. onProgress( event );
  10301. }, false );
  10302. }
  10303. image.addEventListener( 'error', function ( event ) {
  10304. if ( onError ) onError( event );
  10305. scope.manager.itemError( url );
  10306. }, false );
  10307. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  10308. scope.manager.itemStart( url );
  10309. image.src = url;
  10310. return image;
  10311. },
  10312. setCrossOrigin: function ( value ) {
  10313. this.crossOrigin = value;
  10314. },
  10315. setPath: function ( value ) {
  10316. this.path = value;
  10317. }
  10318. };
  10319. // File:src/loaders/JSONLoader.js
  10320. /**
  10321. * @author mrdoob / http://mrdoob.com/
  10322. * @author alteredq / http://alteredqualia.com/
  10323. */
  10324. THREE.JSONLoader = function ( manager ) {
  10325. if ( typeof manager === 'boolean' ) {
  10326. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  10327. manager = undefined;
  10328. }
  10329. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10330. this.withCredentials = false;
  10331. };
  10332. THREE.JSONLoader.prototype = {
  10333. constructor: THREE.JSONLoader,
  10334. // Deprecated
  10335. get statusDomElement () {
  10336. if ( this._statusDomElement === undefined ) {
  10337. this._statusDomElement = document.createElement( 'div' );
  10338. }
  10339. console.warn( 'THREE.JSONLoader: .statusDomElement has been removed.' );
  10340. return this._statusDomElement;
  10341. },
  10342. load: function( url, onLoad, onProgress, onError ) {
  10343. var scope = this;
  10344. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : THREE.Loader.prototype.extractUrlBase( url );
  10345. var loader = new THREE.XHRLoader( this.manager );
  10346. loader.setCrossOrigin( this.crossOrigin );
  10347. loader.setWithCredentials( this.withCredentials );
  10348. loader.load( url, function ( text ) {
  10349. var json = JSON.parse( text );
  10350. var metadata = json.metadata;
  10351. if ( metadata !== undefined ) {
  10352. var type = metadata.type;
  10353. if ( type !== undefined ) {
  10354. if ( type.toLowerCase() === 'object' ) {
  10355. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  10356. return;
  10357. }
  10358. if ( type.toLowerCase() === 'scene' ) {
  10359. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  10360. return;
  10361. }
  10362. }
  10363. }
  10364. var object = scope.parse( json, texturePath );
  10365. onLoad( object.geometry, object.materials );
  10366. } );
  10367. },
  10368. setCrossOrigin: function ( value ) {
  10369. this.crossOrigin = value;
  10370. },
  10371. setTexturePath: function ( value ) {
  10372. this.texturePath = value;
  10373. },
  10374. parse: function ( json, texturePath ) {
  10375. var geometry = new THREE.Geometry(),
  10376. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  10377. parseModel( scale );
  10378. parseSkin();
  10379. parseMorphing( scale );
  10380. parseAnimations();
  10381. geometry.computeFaceNormals();
  10382. geometry.computeBoundingSphere();
  10383. function parseModel( scale ) {
  10384. function isBitSet( value, position ) {
  10385. return value & ( 1 << position );
  10386. }
  10387. var i, j, fi,
  10388. offset, zLength,
  10389. colorIndex, normalIndex, uvIndex, materialIndex,
  10390. type,
  10391. isQuad,
  10392. hasMaterial,
  10393. hasFaceVertexUv,
  10394. hasFaceNormal, hasFaceVertexNormal,
  10395. hasFaceColor, hasFaceVertexColor,
  10396. vertex, face, faceA, faceB, hex, normal,
  10397. uvLayer, uv, u, v,
  10398. faces = json.faces,
  10399. vertices = json.vertices,
  10400. normals = json.normals,
  10401. colors = json.colors,
  10402. nUvLayers = 0;
  10403. if ( json.uvs !== undefined ) {
  10404. // disregard empty arrays
  10405. for ( i = 0; i < json.uvs.length; i ++ ) {
  10406. if ( json.uvs[ i ].length ) nUvLayers ++;
  10407. }
  10408. for ( i = 0; i < nUvLayers; i ++ ) {
  10409. geometry.faceVertexUvs[ i ] = [];
  10410. }
  10411. }
  10412. offset = 0;
  10413. zLength = vertices.length;
  10414. while ( offset < zLength ) {
  10415. vertex = new THREE.Vector3();
  10416. vertex.x = vertices[ offset ++ ] * scale;
  10417. vertex.y = vertices[ offset ++ ] * scale;
  10418. vertex.z = vertices[ offset ++ ] * scale;
  10419. geometry.vertices.push( vertex );
  10420. }
  10421. offset = 0;
  10422. zLength = faces.length;
  10423. while ( offset < zLength ) {
  10424. type = faces[ offset ++ ];
  10425. isQuad = isBitSet( type, 0 );
  10426. hasMaterial = isBitSet( type, 1 );
  10427. hasFaceVertexUv = isBitSet( type, 3 );
  10428. hasFaceNormal = isBitSet( type, 4 );
  10429. hasFaceVertexNormal = isBitSet( type, 5 );
  10430. hasFaceColor = isBitSet( type, 6 );
  10431. hasFaceVertexColor = isBitSet( type, 7 );
  10432. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  10433. if ( isQuad ) {
  10434. faceA = new THREE.Face3();
  10435. faceA.a = faces[ offset ];
  10436. faceA.b = faces[ offset + 1 ];
  10437. faceA.c = faces[ offset + 3 ];
  10438. faceB = new THREE.Face3();
  10439. faceB.a = faces[ offset + 1 ];
  10440. faceB.b = faces[ offset + 2 ];
  10441. faceB.c = faces[ offset + 3 ];
  10442. offset += 4;
  10443. if ( hasMaterial ) {
  10444. materialIndex = faces[ offset ++ ];
  10445. faceA.materialIndex = materialIndex;
  10446. faceB.materialIndex = materialIndex;
  10447. }
  10448. // to get face <=> uv index correspondence
  10449. fi = geometry.faces.length;
  10450. if ( hasFaceVertexUv ) {
  10451. for ( i = 0; i < nUvLayers; i ++ ) {
  10452. uvLayer = json.uvs[ i ];
  10453. geometry.faceVertexUvs[ i ][ fi ] = [];
  10454. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  10455. for ( j = 0; j < 4; j ++ ) {
  10456. uvIndex = faces[ offset ++ ];
  10457. u = uvLayer[ uvIndex * 2 ];
  10458. v = uvLayer[ uvIndex * 2 + 1 ];
  10459. uv = new THREE.Vector2( u, v );
  10460. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  10461. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  10462. }
  10463. }
  10464. }
  10465. if ( hasFaceNormal ) {
  10466. normalIndex = faces[ offset ++ ] * 3;
  10467. faceA.normal.set(
  10468. normals[ normalIndex ++ ],
  10469. normals[ normalIndex ++ ],
  10470. normals[ normalIndex ]
  10471. );
  10472. faceB.normal.copy( faceA.normal );
  10473. }
  10474. if ( hasFaceVertexNormal ) {
  10475. for ( i = 0; i < 4; i ++ ) {
  10476. normalIndex = faces[ offset ++ ] * 3;
  10477. normal = new THREE.Vector3(
  10478. normals[ normalIndex ++ ],
  10479. normals[ normalIndex ++ ],
  10480. normals[ normalIndex ]
  10481. );
  10482. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  10483. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  10484. }
  10485. }
  10486. if ( hasFaceColor ) {
  10487. colorIndex = faces[ offset ++ ];
  10488. hex = colors[ colorIndex ];
  10489. faceA.color.setHex( hex );
  10490. faceB.color.setHex( hex );
  10491. }
  10492. if ( hasFaceVertexColor ) {
  10493. for ( i = 0; i < 4; i ++ ) {
  10494. colorIndex = faces[ offset ++ ];
  10495. hex = colors[ colorIndex ];
  10496. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  10497. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  10498. }
  10499. }
  10500. geometry.faces.push( faceA );
  10501. geometry.faces.push( faceB );
  10502. } else {
  10503. face = new THREE.Face3();
  10504. face.a = faces[ offset ++ ];
  10505. face.b = faces[ offset ++ ];
  10506. face.c = faces[ offset ++ ];
  10507. if ( hasMaterial ) {
  10508. materialIndex = faces[ offset ++ ];
  10509. face.materialIndex = materialIndex;
  10510. }
  10511. // to get face <=> uv index correspondence
  10512. fi = geometry.faces.length;
  10513. if ( hasFaceVertexUv ) {
  10514. for ( i = 0; i < nUvLayers; i ++ ) {
  10515. uvLayer = json.uvs[ i ];
  10516. geometry.faceVertexUvs[ i ][ fi ] = [];
  10517. for ( j = 0; j < 3; j ++ ) {
  10518. uvIndex = faces[ offset ++ ];
  10519. u = uvLayer[ uvIndex * 2 ];
  10520. v = uvLayer[ uvIndex * 2 + 1 ];
  10521. uv = new THREE.Vector2( u, v );
  10522. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  10523. }
  10524. }
  10525. }
  10526. if ( hasFaceNormal ) {
  10527. normalIndex = faces[ offset ++ ] * 3;
  10528. face.normal.set(
  10529. normals[ normalIndex ++ ],
  10530. normals[ normalIndex ++ ],
  10531. normals[ normalIndex ]
  10532. );
  10533. }
  10534. if ( hasFaceVertexNormal ) {
  10535. for ( i = 0; i < 3; i ++ ) {
  10536. normalIndex = faces[ offset ++ ] * 3;
  10537. normal = new THREE.Vector3(
  10538. normals[ normalIndex ++ ],
  10539. normals[ normalIndex ++ ],
  10540. normals[ normalIndex ]
  10541. );
  10542. face.vertexNormals.push( normal );
  10543. }
  10544. }
  10545. if ( hasFaceColor ) {
  10546. colorIndex = faces[ offset ++ ];
  10547. face.color.setHex( colors[ colorIndex ] );
  10548. }
  10549. if ( hasFaceVertexColor ) {
  10550. for ( i = 0; i < 3; i ++ ) {
  10551. colorIndex = faces[ offset ++ ];
  10552. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  10553. }
  10554. }
  10555. geometry.faces.push( face );
  10556. }
  10557. }
  10558. };
  10559. function parseSkin() {
  10560. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  10561. if ( json.skinWeights ) {
  10562. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  10563. var x = json.skinWeights[ i ];
  10564. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  10565. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  10566. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  10567. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  10568. }
  10569. }
  10570. if ( json.skinIndices ) {
  10571. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  10572. var a = json.skinIndices[ i ];
  10573. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  10574. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  10575. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  10576. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  10577. }
  10578. }
  10579. geometry.bones = json.bones;
  10580. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  10581. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  10582. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  10583. }
  10584. };
  10585. function parseMorphing( scale ) {
  10586. if ( json.morphTargets !== undefined ) {
  10587. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  10588. geometry.morphTargets[ i ] = {};
  10589. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  10590. geometry.morphTargets[ i ].vertices = [];
  10591. var dstVertices = geometry.morphTargets[ i ].vertices;
  10592. var srcVertices = json.morphTargets[ i ].vertices;
  10593. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  10594. var vertex = new THREE.Vector3();
  10595. vertex.x = srcVertices[ v ] * scale;
  10596. vertex.y = srcVertices[ v + 1 ] * scale;
  10597. vertex.z = srcVertices[ v + 2 ] * scale;
  10598. dstVertices.push( vertex );
  10599. }
  10600. }
  10601. }
  10602. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  10603. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  10604. var faces = geometry.faces;
  10605. var morphColors = json.morphColors[ 0 ].colors;
  10606. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  10607. faces[ i ].color.fromArray( morphColors, i * 3 );
  10608. }
  10609. }
  10610. }
  10611. function parseAnimations() {
  10612. var outputAnimations = [];
  10613. // parse old style Bone/Hierarchy animations
  10614. var animations = [];
  10615. if ( json.animation !== undefined ) {
  10616. animations.push( json.animation );
  10617. }
  10618. if ( json.animations !== undefined ) {
  10619. if ( json.animations.length ) {
  10620. animations = animations.concat( json.animations );
  10621. } else {
  10622. animations.push( json.animations );
  10623. }
  10624. }
  10625. for ( var i = 0; i < animations.length; i ++ ) {
  10626. var clip = THREE.AnimationClip.parseAnimation( animations[i], geometry.bones );
  10627. if ( clip ) outputAnimations.push( clip );
  10628. }
  10629. // parse implicit morph animations
  10630. if ( geometry.morphTargets ) {
  10631. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  10632. var morphAnimationClips = THREE.AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  10633. outputAnimations = outputAnimations.concat( morphAnimationClips );
  10634. }
  10635. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  10636. };
  10637. if ( json.materials === undefined || json.materials.length === 0 ) {
  10638. return { geometry: geometry };
  10639. } else {
  10640. var materials = THREE.Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  10641. return { geometry: geometry, materials: materials };
  10642. }
  10643. }
  10644. };
  10645. // File:src/loaders/LoadingManager.js
  10646. /**
  10647. * @author mrdoob / http://mrdoob.com/
  10648. */
  10649. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  10650. var scope = this;
  10651. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  10652. this.onStart = undefined;
  10653. this.onLoad = onLoad;
  10654. this.onProgress = onProgress;
  10655. this.onError = onError;
  10656. this.itemStart = function ( url ) {
  10657. itemsTotal ++;
  10658. if ( isLoading === false ) {
  10659. if ( scope.onStart !== undefined ) {
  10660. scope.onStart( url, itemsLoaded, itemsTotal );
  10661. }
  10662. }
  10663. isLoading = true;
  10664. };
  10665. this.itemEnd = function ( url ) {
  10666. itemsLoaded ++;
  10667. if ( scope.onProgress !== undefined ) {
  10668. scope.onProgress( url, itemsLoaded, itemsTotal );
  10669. }
  10670. if ( itemsLoaded === itemsTotal ) {
  10671. isLoading = false;
  10672. if ( scope.onLoad !== undefined ) {
  10673. scope.onLoad();
  10674. }
  10675. }
  10676. };
  10677. this.itemError = function ( url ) {
  10678. if ( scope.onError !== undefined ) {
  10679. scope.onError( url );
  10680. }
  10681. };
  10682. };
  10683. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  10684. // File:src/loaders/BufferGeometryLoader.js
  10685. /**
  10686. * @author mrdoob / http://mrdoob.com/
  10687. */
  10688. THREE.BufferGeometryLoader = function ( manager ) {
  10689. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10690. };
  10691. THREE.BufferGeometryLoader.prototype = {
  10692. constructor: THREE.BufferGeometryLoader,
  10693. load: function ( url, onLoad, onProgress, onError ) {
  10694. var scope = this;
  10695. var loader = new THREE.XHRLoader( scope.manager );
  10696. loader.setCrossOrigin( this.crossOrigin );
  10697. loader.load( url, function ( text ) {
  10698. onLoad( scope.parse( JSON.parse( text ) ) );
  10699. }, onProgress, onError );
  10700. },
  10701. setCrossOrigin: function ( value ) {
  10702. this.crossOrigin = value;
  10703. },
  10704. parse: function ( json ) {
  10705. var geometry = new THREE.BufferGeometry();
  10706. var index = json.data.index;
  10707. if ( index !== undefined ) {
  10708. var typedArray = new self[ index.type ]( index.array );
  10709. geometry.setIndex( new THREE.BufferAttribute( typedArray, 1 ) );
  10710. }
  10711. var attributes = json.data.attributes;
  10712. for ( var key in attributes ) {
  10713. var attribute = attributes[ key ];
  10714. var typedArray = new self[ attribute.type ]( attribute.array );
  10715. geometry.addAttribute( key, new THREE.BufferAttribute( typedArray, attribute.itemSize ) );
  10716. }
  10717. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  10718. if ( groups !== undefined ) {
  10719. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  10720. var group = groups[ i ];
  10721. geometry.addGroup( group.start, group.count );
  10722. }
  10723. }
  10724. var boundingSphere = json.data.boundingSphere;
  10725. if ( boundingSphere !== undefined ) {
  10726. var center = new THREE.Vector3();
  10727. if ( boundingSphere.center !== undefined ) {
  10728. center.fromArray( boundingSphere.center );
  10729. }
  10730. geometry.boundingSphere = new THREE.Sphere( center, boundingSphere.radius );
  10731. }
  10732. return geometry;
  10733. }
  10734. };
  10735. // File:src/loaders/MaterialLoader.js
  10736. /**
  10737. * @author mrdoob / http://mrdoob.com/
  10738. */
  10739. THREE.MaterialLoader = function ( manager ) {
  10740. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10741. this.textures = {};
  10742. };
  10743. THREE.MaterialLoader.prototype = {
  10744. constructor: THREE.MaterialLoader,
  10745. load: function ( url, onLoad, onProgress, onError ) {
  10746. var scope = this;
  10747. var loader = new THREE.XHRLoader( scope.manager );
  10748. loader.setCrossOrigin( this.crossOrigin );
  10749. loader.load( url, function ( text ) {
  10750. onLoad( scope.parse( JSON.parse( text ) ) );
  10751. }, onProgress, onError );
  10752. },
  10753. setCrossOrigin: function ( value ) {
  10754. this.crossOrigin = value;
  10755. },
  10756. setTextures: function ( value ) {
  10757. this.textures = value;
  10758. },
  10759. getTexture: function ( name ) {
  10760. var textures = this.textures;
  10761. if ( textures[ name ] === undefined ) {
  10762. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  10763. }
  10764. return textures[ name ];
  10765. },
  10766. parse: function ( json ) {
  10767. var material = new THREE[ json.type ];
  10768. material.uuid = json.uuid;
  10769. if ( json.name !== undefined ) material.name = json.name;
  10770. if ( json.color !== undefined ) material.color.setHex( json.color );
  10771. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  10772. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  10773. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  10774. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  10775. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  10776. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  10777. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  10778. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  10779. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  10780. if ( json.shading !== undefined ) material.shading = json.shading;
  10781. if ( json.blending !== undefined ) material.blending = json.blending;
  10782. if ( json.side !== undefined ) material.side = json.side;
  10783. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  10784. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  10785. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  10786. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  10787. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  10788. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  10789. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  10790. // for PointsMaterial
  10791. if ( json.size !== undefined ) material.size = json.size;
  10792. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  10793. // maps
  10794. if ( json.map !== undefined ) material.map = this.getTexture( json.map );
  10795. if ( json.alphaMap !== undefined ) {
  10796. material.alphaMap = this.getTexture( json.alphaMap );
  10797. material.transparent = true;
  10798. }
  10799. if ( json.bumpMap !== undefined ) material.bumpMap = this.getTexture( json.bumpMap );
  10800. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  10801. if ( json.normalMap !== undefined ) material.normalMap = this.getTexture( json.normalMap );
  10802. if ( json.normalScale !== undefined ) {
  10803. var normalScale = json.normalScale;
  10804. if ( Array.isArray( normalScale ) === false ) {
  10805. // Blender exporter used to export a scalar. See #7459
  10806. normalScale = [ normalScale, normalScale ];
  10807. }
  10808. material.normalScale = new THREE.Vector2().fromArray( normalScale );
  10809. }
  10810. if ( json.displacementMap !== undefined ) material.displacementMap = this.getTexture( json.displacementMap );
  10811. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  10812. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  10813. if ( json.roughnessMap !== undefined ) material.roughnessMap = this.getTexture( json.roughnessMap );
  10814. if ( json.metalnessMap !== undefined ) material.metalnessMap = this.getTexture( json.metalnessMap );
  10815. if ( json.specularMap !== undefined ) material.specularMap = this.getTexture( json.specularMap );
  10816. if ( json.envMap !== undefined ) {
  10817. material.envMap = this.getTexture( json.envMap );
  10818. material.combine = THREE.MultiplyOperation;
  10819. }
  10820. if ( json.reflectivity ) material.reflectivity = json.reflectivity;
  10821. if ( json.lightMap !== undefined ) material.lightMap = this.getTexture( json.lightMap );
  10822. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  10823. if ( json.aoMap !== undefined ) material.aoMap = this.getTexture( json.aoMap );
  10824. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  10825. // MeshFaceMaterial
  10826. if ( json.materials !== undefined ) {
  10827. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  10828. material.materials.push( this.parse( json.materials[ i ] ) );
  10829. }
  10830. }
  10831. return material;
  10832. }
  10833. };
  10834. // File:src/loaders/ObjectLoader.js
  10835. /**
  10836. * @author mrdoob / http://mrdoob.com/
  10837. */
  10838. THREE.ObjectLoader = function ( manager ) {
  10839. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10840. this.texturePath = '';
  10841. };
  10842. THREE.ObjectLoader.prototype = {
  10843. constructor: THREE.ObjectLoader,
  10844. load: function ( url, onLoad, onProgress, onError ) {
  10845. if ( this.texturePath === '' ) {
  10846. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  10847. }
  10848. var scope = this;
  10849. var loader = new THREE.XHRLoader( scope.manager );
  10850. loader.setCrossOrigin( this.crossOrigin );
  10851. loader.load( url, function ( text ) {
  10852. scope.parse( JSON.parse( text ), onLoad );
  10853. }, onProgress, onError );
  10854. },
  10855. setTexturePath: function ( value ) {
  10856. this.texturePath = value;
  10857. },
  10858. setCrossOrigin: function ( value ) {
  10859. this.crossOrigin = value;
  10860. },
  10861. parse: function ( json, onLoad ) {
  10862. var geometries = this.parseGeometries( json.geometries );
  10863. var images = this.parseImages( json.images, function () {
  10864. if ( onLoad !== undefined ) onLoad( object );
  10865. } );
  10866. var textures = this.parseTextures( json.textures, images );
  10867. var materials = this.parseMaterials( json.materials, textures );
  10868. var object = this.parseObject( json.object, geometries, materials );
  10869. if ( json.animations ) {
  10870. object.animations = this.parseAnimations( json.animations );
  10871. }
  10872. if ( json.images === undefined || json.images.length === 0 ) {
  10873. if ( onLoad !== undefined ) onLoad( object );
  10874. }
  10875. return object;
  10876. },
  10877. parseGeometries: function ( json ) {
  10878. var geometries = {};
  10879. if ( json !== undefined ) {
  10880. var geometryLoader = new THREE.JSONLoader();
  10881. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  10882. for ( var i = 0, l = json.length; i < l; i ++ ) {
  10883. var geometry;
  10884. var data = json[ i ];
  10885. switch ( data.type ) {
  10886. case 'PlaneGeometry':
  10887. case 'PlaneBufferGeometry':
  10888. geometry = new THREE[ data.type ](
  10889. data.width,
  10890. data.height,
  10891. data.widthSegments,
  10892. data.heightSegments
  10893. );
  10894. break;
  10895. case 'BoxGeometry':
  10896. case 'CubeGeometry': // backwards compatible
  10897. geometry = new THREE.BoxGeometry(
  10898. data.width,
  10899. data.height,
  10900. data.depth,
  10901. data.widthSegments,
  10902. data.heightSegments,
  10903. data.depthSegments
  10904. );
  10905. break;
  10906. case 'CircleBufferGeometry':
  10907. geometry = new THREE.CircleBufferGeometry(
  10908. data.radius,
  10909. data.segments,
  10910. data.thetaStart,
  10911. data.thetaLength
  10912. );
  10913. break;
  10914. case 'CircleGeometry':
  10915. geometry = new THREE.CircleGeometry(
  10916. data.radius,
  10917. data.segments,
  10918. data.thetaStart,
  10919. data.thetaLength
  10920. );
  10921. break;
  10922. case 'CylinderGeometry':
  10923. geometry = new THREE.CylinderGeometry(
  10924. data.radiusTop,
  10925. data.radiusBottom,
  10926. data.height,
  10927. data.radialSegments,
  10928. data.heightSegments,
  10929. data.openEnded,
  10930. data.thetaStart,
  10931. data.thetaLength
  10932. );
  10933. break;
  10934. case 'SphereGeometry':
  10935. geometry = new THREE.SphereGeometry(
  10936. data.radius,
  10937. data.widthSegments,
  10938. data.heightSegments,
  10939. data.phiStart,
  10940. data.phiLength,
  10941. data.thetaStart,
  10942. data.thetaLength
  10943. );
  10944. break;
  10945. case 'SphereBufferGeometry':
  10946. geometry = new THREE.SphereBufferGeometry(
  10947. data.radius,
  10948. data.widthSegments,
  10949. data.heightSegments,
  10950. data.phiStart,
  10951. data.phiLength,
  10952. data.thetaStart,
  10953. data.thetaLength
  10954. );
  10955. break;
  10956. case 'DodecahedronGeometry':
  10957. geometry = new THREE.DodecahedronGeometry(
  10958. data.radius,
  10959. data.detail
  10960. );
  10961. break;
  10962. case 'IcosahedronGeometry':
  10963. geometry = new THREE.IcosahedronGeometry(
  10964. data.radius,
  10965. data.detail
  10966. );
  10967. break;
  10968. case 'OctahedronGeometry':
  10969. geometry = new THREE.OctahedronGeometry(
  10970. data.radius,
  10971. data.detail
  10972. );
  10973. break;
  10974. case 'TetrahedronGeometry':
  10975. geometry = new THREE.TetrahedronGeometry(
  10976. data.radius,
  10977. data.detail
  10978. );
  10979. break;
  10980. case 'RingGeometry':
  10981. geometry = new THREE.RingGeometry(
  10982. data.innerRadius,
  10983. data.outerRadius,
  10984. data.thetaSegments,
  10985. data.phiSegments,
  10986. data.thetaStart,
  10987. data.thetaLength
  10988. );
  10989. break;
  10990. case 'TorusGeometry':
  10991. geometry = new THREE.TorusGeometry(
  10992. data.radius,
  10993. data.tube,
  10994. data.radialSegments,
  10995. data.tubularSegments,
  10996. data.arc
  10997. );
  10998. break;
  10999. case 'TorusKnotGeometry':
  11000. geometry = new THREE.TorusKnotGeometry(
  11001. data.radius,
  11002. data.tube,
  11003. data.radialSegments,
  11004. data.tubularSegments,
  11005. data.p,
  11006. data.q,
  11007. data.heightScale
  11008. );
  11009. break;
  11010. case 'BufferGeometry':
  11011. geometry = bufferGeometryLoader.parse( data );
  11012. break;
  11013. case 'Geometry':
  11014. geometry = geometryLoader.parse( data.data, this.texturePath ).geometry;
  11015. break;
  11016. default:
  11017. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  11018. continue;
  11019. }
  11020. geometry.uuid = data.uuid;
  11021. if ( data.name !== undefined ) geometry.name = data.name;
  11022. geometries[ data.uuid ] = geometry;
  11023. }
  11024. }
  11025. return geometries;
  11026. },
  11027. parseMaterials: function ( json, textures ) {
  11028. var materials = {};
  11029. if ( json !== undefined ) {
  11030. var loader = new THREE.MaterialLoader();
  11031. loader.setTextures( textures );
  11032. for ( var i = 0, l = json.length; i < l; i ++ ) {
  11033. var material = loader.parse( json[ i ] );
  11034. materials[ material.uuid ] = material;
  11035. }
  11036. }
  11037. return materials;
  11038. },
  11039. parseAnimations: function ( json ) {
  11040. var animations = [];
  11041. for ( var i = 0; i < json.length; i ++ ) {
  11042. var clip = THREE.AnimationClip.parse( json[i] );
  11043. animations.push( clip );
  11044. }
  11045. return animations;
  11046. },
  11047. parseImages: function ( json, onLoad ) {
  11048. var scope = this;
  11049. var images = {};
  11050. function loadImage( url ) {
  11051. scope.manager.itemStart( url );
  11052. return loader.load( url, function () {
  11053. scope.manager.itemEnd( url );
  11054. } );
  11055. }
  11056. if ( json !== undefined && json.length > 0 ) {
  11057. var manager = new THREE.LoadingManager( onLoad );
  11058. var loader = new THREE.ImageLoader( manager );
  11059. loader.setCrossOrigin( this.crossOrigin );
  11060. for ( var i = 0, l = json.length; i < l; i ++ ) {
  11061. var image = json[ i ];
  11062. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  11063. images[ image.uuid ] = loadImage( path );
  11064. }
  11065. }
  11066. return images;
  11067. },
  11068. parseTextures: function ( json, images ) {
  11069. function parseConstant( value ) {
  11070. if ( typeof( value ) === 'number' ) return value;
  11071. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  11072. return THREE[ value ];
  11073. }
  11074. var textures = {};
  11075. if ( json !== undefined ) {
  11076. for ( var i = 0, l = json.length; i < l; i ++ ) {
  11077. var data = json[ i ];
  11078. if ( data.image === undefined ) {
  11079. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  11080. }
  11081. if ( images[ data.image ] === undefined ) {
  11082. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  11083. }
  11084. var texture = new THREE.Texture( images[ data.image ] );
  11085. texture.needsUpdate = true;
  11086. texture.uuid = data.uuid;
  11087. if ( data.name !== undefined ) texture.name = data.name;
  11088. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping );
  11089. if ( data.offset !== undefined ) texture.offset = new THREE.Vector2( data.offset[ 0 ], data.offset[ 1 ] );
  11090. if ( data.repeat !== undefined ) texture.repeat = new THREE.Vector2( data.repeat[ 0 ], data.repeat[ 1 ] );
  11091. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter );
  11092. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter );
  11093. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  11094. if ( Array.isArray( data.wrap ) ) {
  11095. texture.wrapS = parseConstant( data.wrap[ 0 ] );
  11096. texture.wrapT = parseConstant( data.wrap[ 1 ] );
  11097. }
  11098. textures[ data.uuid ] = texture;
  11099. }
  11100. }
  11101. return textures;
  11102. },
  11103. parseObject: function () {
  11104. var matrix = new THREE.Matrix4();
  11105. return function ( data, geometries, materials ) {
  11106. var object;
  11107. function getGeometry( name ) {
  11108. if ( geometries[ name ] === undefined ) {
  11109. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  11110. }
  11111. return geometries[ name ];
  11112. }
  11113. function getMaterial( name ) {
  11114. if ( name === undefined ) return undefined;
  11115. if ( materials[ name ] === undefined ) {
  11116. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  11117. }
  11118. return materials[ name ];
  11119. }
  11120. switch ( data.type ) {
  11121. case 'Scene':
  11122. object = new THREE.Scene();
  11123. break;
  11124. case 'PerspectiveCamera':
  11125. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  11126. break;
  11127. case 'OrthographicCamera':
  11128. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  11129. break;
  11130. case 'AmbientLight':
  11131. object = new THREE.AmbientLight( data.color );
  11132. break;
  11133. case 'DirectionalLight':
  11134. object = new THREE.DirectionalLight( data.color, data.intensity );
  11135. break;
  11136. case 'PointLight':
  11137. object = new THREE.PointLight( data.color, data.intensity, data.distance, data.decay );
  11138. break;
  11139. case 'SpotLight':
  11140. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent, data.decay );
  11141. break;
  11142. case 'HemisphereLight':
  11143. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  11144. break;
  11145. case 'Mesh':
  11146. var geometry = getGeometry( data.geometry );
  11147. var material = getMaterial( data.material );
  11148. if ( geometry.bones && geometry.bones.length > 0 ) {
  11149. object = new THREE.SkinnedMesh( geometry, material );
  11150. } else {
  11151. object = new THREE.Mesh( geometry, material );
  11152. }
  11153. break;
  11154. case 'LOD':
  11155. object = new THREE.LOD();
  11156. break;
  11157. case 'Line':
  11158. object = new THREE.Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  11159. break;
  11160. case 'PointCloud':
  11161. case 'Points':
  11162. object = new THREE.Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  11163. break;
  11164. case 'Sprite':
  11165. object = new THREE.Sprite( getMaterial( data.material ) );
  11166. break;
  11167. case 'Group':
  11168. object = new THREE.Group();
  11169. break;
  11170. default:
  11171. object = new THREE.Object3D();
  11172. }
  11173. object.uuid = data.uuid;
  11174. if ( data.name !== undefined ) object.name = data.name;
  11175. if ( data.matrix !== undefined ) {
  11176. matrix.fromArray( data.matrix );
  11177. matrix.decompose( object.position, object.quaternion, object.scale );
  11178. } else {
  11179. if ( data.position !== undefined ) object.position.fromArray( data.position );
  11180. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  11181. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  11182. }
  11183. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  11184. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  11185. if ( data.visible !== undefined ) object.visible = data.visible;
  11186. if ( data.userData !== undefined ) object.userData = data.userData;
  11187. if ( data.children !== undefined ) {
  11188. for ( var child in data.children ) {
  11189. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  11190. }
  11191. }
  11192. if ( data.type === 'LOD' ) {
  11193. var levels = data.levels;
  11194. for ( var l = 0; l < levels.length; l ++ ) {
  11195. var level = levels[ l ];
  11196. var child = object.getObjectByProperty( 'uuid', level.object );
  11197. if ( child !== undefined ) {
  11198. object.addLevel( child, level.distance );
  11199. }
  11200. }
  11201. }
  11202. return object;
  11203. }
  11204. }()
  11205. };
  11206. // File:src/loaders/TextureLoader.js
  11207. /**
  11208. * @author mrdoob / http://mrdoob.com/
  11209. */
  11210. THREE.TextureLoader = function ( manager ) {
  11211. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11212. };
  11213. THREE.TextureLoader.prototype = {
  11214. constructor: THREE.TextureLoader,
  11215. load: function ( url, onLoad, onProgress, onError ) {
  11216. var texture = new THREE.Texture();
  11217. var loader = new THREE.ImageLoader( this.manager );
  11218. loader.setCrossOrigin( this.crossOrigin );
  11219. loader.setPath( this.path );
  11220. loader.load( url, function ( image ) {
  11221. texture.image = image;
  11222. texture.needsUpdate = true;
  11223. if ( onLoad !== undefined ) {
  11224. onLoad( texture );
  11225. }
  11226. }, onProgress, onError );
  11227. return texture;
  11228. },
  11229. setCrossOrigin: function ( value ) {
  11230. this.crossOrigin = value;
  11231. },
  11232. setPath: function ( value ) {
  11233. this.path = value;
  11234. }
  11235. };
  11236. // File:src/loaders/CubeTextureLoader.js
  11237. /**
  11238. * @author mrdoob / http://mrdoob.com/
  11239. */
  11240. THREE.CubeTextureLoader = function ( manager ) {
  11241. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11242. };
  11243. THREE.CubeTextureLoader.prototype = {
  11244. constructor: THREE.CubeTextureLoader,
  11245. load: function ( urls, onLoad, onProgress, onError ) {
  11246. var texture = new THREE.CubeTexture( [] );
  11247. var loader = new THREE.ImageLoader();
  11248. loader.setCrossOrigin( this.crossOrigin );
  11249. loader.setPath( this.path );
  11250. var loaded = 0;
  11251. function loadTexture( i ) {
  11252. loader.load( urls[ i ], function ( image ) {
  11253. texture.images[ i ] = image;
  11254. loaded ++;
  11255. if ( loaded === 6 ) {
  11256. texture.needsUpdate = true;
  11257. if ( onLoad ) onLoad( texture );
  11258. }
  11259. }, undefined, onError );
  11260. }
  11261. for ( var i = 0; i < urls.length; ++ i ) {
  11262. loadTexture( i );
  11263. }
  11264. return texture;
  11265. },
  11266. setCrossOrigin: function ( value ) {
  11267. this.crossOrigin = value;
  11268. },
  11269. setPath: function ( value ) {
  11270. this.path = value;
  11271. }
  11272. };
  11273. // File:src/loaders/BinaryTextureLoader.js
  11274. /**
  11275. * @author Nikos M. / https://github.com/foo123/
  11276. *
  11277. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  11278. */
  11279. THREE.DataTextureLoader = THREE.BinaryTextureLoader = function ( manager ) {
  11280. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11281. // override in sub classes
  11282. this._parser = null;
  11283. };
  11284. THREE.BinaryTextureLoader.prototype = {
  11285. constructor: THREE.BinaryTextureLoader,
  11286. load: function ( url, onLoad, onProgress, onError ) {
  11287. var scope = this;
  11288. var texture = new THREE.DataTexture();
  11289. var loader = new THREE.XHRLoader( this.manager );
  11290. loader.setCrossOrigin( this.crossOrigin );
  11291. loader.setResponseType( 'arraybuffer' );
  11292. loader.load( url, function ( buffer ) {
  11293. var texData = scope._parser( buffer );
  11294. if ( ! texData ) return;
  11295. if ( undefined !== texData.image ) {
  11296. texture.image = texData.image;
  11297. } else if ( undefined !== texData.data ) {
  11298. texture.image.width = texData.width;
  11299. texture.image.height = texData.height;
  11300. texture.image.data = texData.data;
  11301. }
  11302. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : THREE.ClampToEdgeWrapping;
  11303. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : THREE.ClampToEdgeWrapping;
  11304. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : THREE.LinearFilter;
  11305. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : THREE.LinearMipMapLinearFilter;
  11306. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  11307. if ( undefined !== texData.format ) {
  11308. texture.format = texData.format;
  11309. }
  11310. if ( undefined !== texData.type ) {
  11311. texture.type = texData.type;
  11312. }
  11313. if ( undefined !== texData.mipmaps ) {
  11314. texture.mipmaps = texData.mipmaps;
  11315. }
  11316. if ( 1 === texData.mipmapCount ) {
  11317. texture.minFilter = THREE.LinearFilter;
  11318. }
  11319. texture.needsUpdate = true;
  11320. if ( onLoad ) onLoad( texture, texData );
  11321. }, onProgress, onError );
  11322. return texture;
  11323. },
  11324. setCrossOrigin: function ( value ) {
  11325. this.crossOrigin = value;
  11326. }
  11327. };
  11328. // File:src/loaders/CompressedTextureLoader.js
  11329. /**
  11330. * @author mrdoob / http://mrdoob.com/
  11331. *
  11332. * Abstract Base class to block based textures loader (dds, pvr, ...)
  11333. */
  11334. THREE.CompressedTextureLoader = function ( manager ) {
  11335. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11336. // override in sub classes
  11337. this._parser = null;
  11338. };
  11339. THREE.CompressedTextureLoader.prototype = {
  11340. constructor: THREE.CompressedTextureLoader,
  11341. load: function ( url, onLoad, onProgress, onError ) {
  11342. var scope = this;
  11343. var images = [];
  11344. var texture = new THREE.CompressedTexture();
  11345. texture.image = images;
  11346. var loader = new THREE.XHRLoader( this.manager );
  11347. loader.setCrossOrigin( this.crossOrigin );
  11348. loader.setPath( this.path );
  11349. loader.setResponseType( 'arraybuffer' );
  11350. function loadTexture( i ) {
  11351. loader.load( url[ i ], function ( buffer ) {
  11352. var texDatas = scope._parser( buffer, true );
  11353. images[ i ] = {
  11354. width: texDatas.width,
  11355. height: texDatas.height,
  11356. format: texDatas.format,
  11357. mipmaps: texDatas.mipmaps
  11358. };
  11359. loaded += 1;
  11360. if ( loaded === 6 ) {
  11361. if ( texDatas.mipmapCount === 1 )
  11362. texture.minFilter = THREE.LinearFilter;
  11363. texture.format = texDatas.format;
  11364. texture.needsUpdate = true;
  11365. if ( onLoad ) onLoad( texture );
  11366. }
  11367. }, onProgress, onError );
  11368. }
  11369. if ( Array.isArray( url ) ) {
  11370. var loaded = 0;
  11371. for ( var i = 0, il = url.length; i < il; ++ i ) {
  11372. loadTexture( i );
  11373. }
  11374. } else {
  11375. // compressed cubemap texture stored in a single DDS file
  11376. loader.load( url, function ( buffer ) {
  11377. var texDatas = scope._parser( buffer, true );
  11378. if ( texDatas.isCubemap ) {
  11379. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  11380. for ( var f = 0; f < faces; f ++ ) {
  11381. images[ f ] = { mipmaps : [] };
  11382. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  11383. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  11384. images[ f ].format = texDatas.format;
  11385. images[ f ].width = texDatas.width;
  11386. images[ f ].height = texDatas.height;
  11387. }
  11388. }
  11389. } else {
  11390. texture.image.width = texDatas.width;
  11391. texture.image.height = texDatas.height;
  11392. texture.mipmaps = texDatas.mipmaps;
  11393. }
  11394. if ( texDatas.mipmapCount === 1 ) {
  11395. texture.minFilter = THREE.LinearFilter;
  11396. }
  11397. texture.format = texDatas.format;
  11398. texture.needsUpdate = true;
  11399. if ( onLoad ) onLoad( texture );
  11400. }, onProgress, onError );
  11401. }
  11402. return texture;
  11403. },
  11404. setCrossOrigin: function ( value ) {
  11405. this.crossOrigin = value;
  11406. },
  11407. setPath: function ( value ) {
  11408. this.path = value;
  11409. }
  11410. };
  11411. // File:src/materials/Material.js
  11412. /**
  11413. * @author mrdoob / http://mrdoob.com/
  11414. * @author alteredq / http://alteredqualia.com/
  11415. */
  11416. THREE.Material = function () {
  11417. Object.defineProperty( this, 'id', { value: THREE.MaterialIdCount ++ } );
  11418. this.uuid = THREE.Math.generateUUID();
  11419. this.name = '';
  11420. this.type = 'Material';
  11421. this.side = THREE.FrontSide;
  11422. this.opacity = 1;
  11423. this.transparent = false;
  11424. this.blending = THREE.NormalBlending;
  11425. this.blendSrc = THREE.SrcAlphaFactor;
  11426. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  11427. this.blendEquation = THREE.AddEquation;
  11428. this.blendSrcAlpha = null;
  11429. this.blendDstAlpha = null;
  11430. this.blendEquationAlpha = null;
  11431. this.depthFunc = THREE.LessEqualDepth;
  11432. this.depthTest = true;
  11433. this.depthWrite = true;
  11434. this.colorWrite = true;
  11435. this.precision = null; // override the renderer's default precision for this material
  11436. this.polygonOffset = false;
  11437. this.polygonOffsetFactor = 0;
  11438. this.polygonOffsetUnits = 0;
  11439. this.alphaTest = 0;
  11440. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  11441. this.visible = true;
  11442. this._needsUpdate = true;
  11443. };
  11444. THREE.Material.prototype = {
  11445. constructor: THREE.Material,
  11446. get needsUpdate () {
  11447. return this._needsUpdate;
  11448. },
  11449. set needsUpdate ( value ) {
  11450. if ( value === true ) this.update();
  11451. this._needsUpdate = value;
  11452. },
  11453. setValues: function ( values ) {
  11454. if ( values === undefined ) return;
  11455. for ( var key in values ) {
  11456. var newValue = values[ key ];
  11457. if ( newValue === undefined ) {
  11458. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  11459. continue;
  11460. }
  11461. var currentValue = this[ key ];
  11462. if ( currentValue === undefined ) {
  11463. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  11464. continue;
  11465. }
  11466. if ( currentValue instanceof THREE.Color ) {
  11467. currentValue.set( newValue );
  11468. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  11469. currentValue.copy( newValue );
  11470. } else if ( key === 'overdraw' ) {
  11471. // ensure overdraw is backwards-compatible with legacy boolean type
  11472. this[ key ] = Number( newValue );
  11473. } else {
  11474. this[ key ] = newValue;
  11475. }
  11476. }
  11477. },
  11478. toJSON: function ( meta ) {
  11479. var isRoot = meta === undefined;
  11480. if ( isRoot ) {
  11481. meta = {
  11482. textures: {},
  11483. images: {}
  11484. };
  11485. }
  11486. var data = {
  11487. metadata: {
  11488. version: 4.4,
  11489. type: 'Material',
  11490. generator: 'Material.toJSON'
  11491. }
  11492. };
  11493. // standard Material serialization
  11494. data.uuid = this.uuid;
  11495. data.type = this.type;
  11496. if ( this.name !== '' ) data.name = this.name;
  11497. if ( this.color instanceof THREE.Color ) data.color = this.color.getHex();
  11498. if ( this.roughness !== 0.5 ) data.roughness = this.roughness;
  11499. if ( this.metalness > 0 ) data.metalness = this.metalness;
  11500. if ( this.emissive instanceof THREE.Color ) data.emissive = this.emissive.getHex();
  11501. if ( this.specular instanceof THREE.Color ) data.specular = this.specular.getHex();
  11502. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  11503. if ( this.map instanceof THREE.Texture ) data.map = this.map.toJSON( meta ).uuid;
  11504. if ( this.alphaMap instanceof THREE.Texture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  11505. if ( this.lightMap instanceof THREE.Texture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  11506. if ( this.bumpMap instanceof THREE.Texture ) {
  11507. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  11508. data.bumpScale = this.bumpScale;
  11509. }
  11510. if ( this.normalMap instanceof THREE.Texture ) {
  11511. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  11512. data.normalScale = this.normalScale.toArray();
  11513. }
  11514. if ( this.displacementMap instanceof THREE.Texture ) {
  11515. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  11516. data.displacementScale = this.displacementScale;
  11517. data.displacementBias = this.displacementBias;
  11518. }
  11519. if ( this.roughnessMap instanceof THREE.Texture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  11520. if ( this.metalnessMap instanceof THREE.Texture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  11521. if ( this.specularMap instanceof THREE.Texture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  11522. if ( this.envMap instanceof THREE.Texture ) {
  11523. data.envMap = this.envMap.toJSON( meta ).uuid;
  11524. data.reflectivity = this.reflectivity; // Scale behind envMap
  11525. }
  11526. if ( this.size !== undefined ) data.size = this.size;
  11527. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  11528. if ( this.vertexColors !== undefined && this.vertexColors !== THREE.NoColors ) data.vertexColors = this.vertexColors;
  11529. if ( this.shading !== undefined && this.shading !== THREE.SmoothShading ) data.shading = this.shading;
  11530. if ( this.blending !== undefined && this.blending !== THREE.NormalBlending ) data.blending = this.blending;
  11531. if ( this.side !== undefined && this.side !== THREE.FrontSide ) data.side = this.side;
  11532. if ( this.opacity < 1 ) data.opacity = this.opacity;
  11533. if ( this.transparent === true ) data.transparent = this.transparent;
  11534. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  11535. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  11536. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  11537. // TODO: Copied from Object3D.toJSON
  11538. function extractFromCache ( cache ) {
  11539. var values = [];
  11540. for ( var key in cache ) {
  11541. var data = cache[ key ];
  11542. delete data.metadata;
  11543. values.push( data );
  11544. }
  11545. return values;
  11546. }
  11547. if ( isRoot ) {
  11548. var textures = extractFromCache( meta.textures );
  11549. var images = extractFromCache( meta.images );
  11550. if ( textures.length > 0 ) data.textures = textures;
  11551. if ( images.length > 0 ) data.images = images;
  11552. }
  11553. return data;
  11554. },
  11555. clone: function () {
  11556. return new this.constructor().copy( this );
  11557. },
  11558. copy: function ( source ) {
  11559. this.name = source.name;
  11560. this.side = source.side;
  11561. this.opacity = source.opacity;
  11562. this.transparent = source.transparent;
  11563. this.blending = source.blending;
  11564. this.blendSrc = source.blendSrc;
  11565. this.blendDst = source.blendDst;
  11566. this.blendEquation = source.blendEquation;
  11567. this.blendSrcAlpha = source.blendSrcAlpha;
  11568. this.blendDstAlpha = source.blendDstAlpha;
  11569. this.blendEquationAlpha = source.blendEquationAlpha;
  11570. this.depthFunc = source.depthFunc;
  11571. this.depthTest = source.depthTest;
  11572. this.depthWrite = source.depthWrite;
  11573. this.precision = source.precision;
  11574. this.polygonOffset = source.polygonOffset;
  11575. this.polygonOffsetFactor = source.polygonOffsetFactor;
  11576. this.polygonOffsetUnits = source.polygonOffsetUnits;
  11577. this.alphaTest = source.alphaTest;
  11578. this.overdraw = source.overdraw;
  11579. this.visible = source.visible;
  11580. return this;
  11581. },
  11582. update: function () {
  11583. this.dispatchEvent( { type: 'update' } );
  11584. },
  11585. dispose: function () {
  11586. this.dispatchEvent( { type: 'dispose' } );
  11587. }
  11588. };
  11589. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  11590. THREE.MaterialIdCount = 0;
  11591. // File:src/materials/LineBasicMaterial.js
  11592. /**
  11593. * @author mrdoob / http://mrdoob.com/
  11594. * @author alteredq / http://alteredqualia.com/
  11595. *
  11596. * parameters = {
  11597. * color: <hex>,
  11598. * opacity: <float>,
  11599. *
  11600. * blending: THREE.NormalBlending,
  11601. * depthTest: <bool>,
  11602. * depthWrite: <bool>,
  11603. *
  11604. * linewidth: <float>,
  11605. * linecap: "round",
  11606. * linejoin: "round",
  11607. *
  11608. * vertexColors: <bool>
  11609. *
  11610. * fog: <bool>
  11611. * }
  11612. */
  11613. THREE.LineBasicMaterial = function ( parameters ) {
  11614. THREE.Material.call( this );
  11615. this.type = 'LineBasicMaterial';
  11616. this.color = new THREE.Color( 0xffffff );
  11617. this.linewidth = 1;
  11618. this.linecap = 'round';
  11619. this.linejoin = 'round';
  11620. this.vertexColors = THREE.NoColors;
  11621. this.fog = true;
  11622. this.setValues( parameters );
  11623. };
  11624. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  11625. THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial;
  11626. THREE.LineBasicMaterial.prototype.copy = function ( source ) {
  11627. THREE.Material.prototype.copy.call( this, source );
  11628. this.color.copy( source.color );
  11629. this.linewidth = source.linewidth;
  11630. this.linecap = source.linecap;
  11631. this.linejoin = source.linejoin;
  11632. this.vertexColors = source.vertexColors;
  11633. this.fog = source.fog;
  11634. return this;
  11635. };
  11636. // File:src/materials/LineDashedMaterial.js
  11637. /**
  11638. * @author alteredq / http://alteredqualia.com/
  11639. *
  11640. * parameters = {
  11641. * color: <hex>,
  11642. * opacity: <float>,
  11643. *
  11644. * blending: THREE.NormalBlending,
  11645. * depthTest: <bool>,
  11646. * depthWrite: <bool>,
  11647. *
  11648. * linewidth: <float>,
  11649. *
  11650. * scale: <float>,
  11651. * dashSize: <float>,
  11652. * gapSize: <float>,
  11653. *
  11654. * vertexColors: THREE.NoColors / THREE.FaceColors / THREE.VertexColors
  11655. *
  11656. * fog: <bool>
  11657. * }
  11658. */
  11659. THREE.LineDashedMaterial = function ( parameters ) {
  11660. THREE.Material.call( this );
  11661. this.type = 'LineDashedMaterial';
  11662. this.color = new THREE.Color( 0xffffff );
  11663. this.linewidth = 1;
  11664. this.scale = 1;
  11665. this.dashSize = 3;
  11666. this.gapSize = 1;
  11667. this.vertexColors = THREE.NoColors;
  11668. this.fog = true;
  11669. this.setValues( parameters );
  11670. };
  11671. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  11672. THREE.LineDashedMaterial.prototype.constructor = THREE.LineDashedMaterial;
  11673. THREE.LineDashedMaterial.prototype.copy = function ( source ) {
  11674. THREE.Material.prototype.copy.call( this, source );
  11675. this.color.copy( source.color );
  11676. this.linewidth = source.linewidth;
  11677. this.scale = source.scale;
  11678. this.dashSize = source.dashSize;
  11679. this.gapSize = source.gapSize;
  11680. this.vertexColors = source.vertexColors;
  11681. this.fog = source.fog;
  11682. return this;
  11683. };
  11684. // File:src/materials/MeshBasicMaterial.js
  11685. /**
  11686. * @author mrdoob / http://mrdoob.com/
  11687. * @author alteredq / http://alteredqualia.com/
  11688. *
  11689. * parameters = {
  11690. * color: <hex>,
  11691. * opacity: <float>,
  11692. * map: new THREE.Texture( <Image> ),
  11693. *
  11694. * aoMap: new THREE.Texture( <Image> ),
  11695. * aoMapIntensity: <float>
  11696. *
  11697. * specularMap: new THREE.Texture( <Image> ),
  11698. *
  11699. * alphaMap: new THREE.Texture( <Image> ),
  11700. *
  11701. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  11702. * combine: THREE.Multiply,
  11703. * reflectivity: <float>,
  11704. * refractionRatio: <float>,
  11705. *
  11706. * shading: THREE.SmoothShading,
  11707. * blending: THREE.NormalBlending,
  11708. * depthTest: <bool>,
  11709. * depthWrite: <bool>,
  11710. *
  11711. * wireframe: <boolean>,
  11712. * wireframeLinewidth: <float>,
  11713. *
  11714. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  11715. *
  11716. * skinning: <bool>,
  11717. * morphTargets: <bool>,
  11718. *
  11719. * fog: <bool>
  11720. * }
  11721. */
  11722. THREE.MeshBasicMaterial = function ( parameters ) {
  11723. THREE.Material.call( this );
  11724. this.type = 'MeshBasicMaterial';
  11725. this.color = new THREE.Color( 0xffffff ); // emissive
  11726. this.map = null;
  11727. this.aoMap = null;
  11728. this.aoMapIntensity = 1.0;
  11729. this.specularMap = null;
  11730. this.alphaMap = null;
  11731. this.envMap = null;
  11732. this.combine = THREE.MultiplyOperation;
  11733. this.reflectivity = 1;
  11734. this.refractionRatio = 0.98;
  11735. this.fog = true;
  11736. this.shading = THREE.SmoothShading;
  11737. this.wireframe = false;
  11738. this.wireframeLinewidth = 1;
  11739. this.wireframeLinecap = 'round';
  11740. this.wireframeLinejoin = 'round';
  11741. this.vertexColors = THREE.NoColors;
  11742. this.skinning = false;
  11743. this.morphTargets = false;
  11744. this.setValues( parameters );
  11745. };
  11746. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  11747. THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial;
  11748. THREE.MeshBasicMaterial.prototype.copy = function ( source ) {
  11749. THREE.Material.prototype.copy.call( this, source );
  11750. this.color.copy( source.color );
  11751. this.map = source.map;
  11752. this.aoMap = source.aoMap;
  11753. this.aoMapIntensity = source.aoMapIntensity;
  11754. this.specularMap = source.specularMap;
  11755. this.alphaMap = source.alphaMap;
  11756. this.envMap = source.envMap;
  11757. this.combine = source.combine;
  11758. this.reflectivity = source.reflectivity;
  11759. this.refractionRatio = source.refractionRatio;
  11760. this.fog = source.fog;
  11761. this.shading = source.shading;
  11762. this.wireframe = source.wireframe;
  11763. this.wireframeLinewidth = source.wireframeLinewidth;
  11764. this.wireframeLinecap = source.wireframeLinecap;
  11765. this.wireframeLinejoin = source.wireframeLinejoin;
  11766. this.vertexColors = source.vertexColors;
  11767. this.skinning = source.skinning;
  11768. this.morphTargets = source.morphTargets;
  11769. return this;
  11770. };
  11771. // File:src/materials/MeshLambertMaterial.js
  11772. /**
  11773. * @author mrdoob / http://mrdoob.com/
  11774. * @author alteredq / http://alteredqualia.com/
  11775. *
  11776. * parameters = {
  11777. * color: <hex>,
  11778. * emissive: <hex>,
  11779. * opacity: <float>,
  11780. *
  11781. * map: new THREE.Texture( <Image> ),
  11782. *
  11783. * specularMap: new THREE.Texture( <Image> ),
  11784. *
  11785. * alphaMap: new THREE.Texture( <Image> ),
  11786. *
  11787. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  11788. * combine: THREE.Multiply,
  11789. * reflectivity: <float>,
  11790. * refractionRatio: <float>,
  11791. *
  11792. * blending: THREE.NormalBlending,
  11793. * depthTest: <bool>,
  11794. * depthWrite: <bool>,
  11795. *
  11796. * wireframe: <boolean>,
  11797. * wireframeLinewidth: <float>,
  11798. *
  11799. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  11800. *
  11801. * skinning: <bool>,
  11802. * morphTargets: <bool>,
  11803. * morphNormals: <bool>,
  11804. *
  11805. * fog: <bool>
  11806. * }
  11807. */
  11808. THREE.MeshLambertMaterial = function ( parameters ) {
  11809. THREE.Material.call( this );
  11810. this.type = 'MeshLambertMaterial';
  11811. this.color = new THREE.Color( 0xffffff ); // diffuse
  11812. this.emissive = new THREE.Color( 0x000000 );
  11813. this.map = null;
  11814. this.specularMap = null;
  11815. this.alphaMap = null;
  11816. this.envMap = null;
  11817. this.combine = THREE.MultiplyOperation;
  11818. this.reflectivity = 1;
  11819. this.refractionRatio = 0.98;
  11820. this.fog = true;
  11821. this.wireframe = false;
  11822. this.wireframeLinewidth = 1;
  11823. this.wireframeLinecap = 'round';
  11824. this.wireframeLinejoin = 'round';
  11825. this.vertexColors = THREE.NoColors;
  11826. this.skinning = false;
  11827. this.morphTargets = false;
  11828. this.morphNormals = false;
  11829. this.setValues( parameters );
  11830. };
  11831. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  11832. THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial;
  11833. THREE.MeshLambertMaterial.prototype.copy = function ( source ) {
  11834. THREE.Material.prototype.copy.call( this, source );
  11835. this.color.copy( source.color );
  11836. this.emissive.copy( source.emissive );
  11837. this.map = source.map;
  11838. this.specularMap = source.specularMap;
  11839. this.alphaMap = source.alphaMap;
  11840. this.envMap = source.envMap;
  11841. this.combine = source.combine;
  11842. this.reflectivity = source.reflectivity;
  11843. this.refractionRatio = source.refractionRatio;
  11844. this.fog = source.fog;
  11845. this.wireframe = source.wireframe;
  11846. this.wireframeLinewidth = source.wireframeLinewidth;
  11847. this.wireframeLinecap = source.wireframeLinecap;
  11848. this.wireframeLinejoin = source.wireframeLinejoin;
  11849. this.vertexColors = source.vertexColors;
  11850. this.skinning = source.skinning;
  11851. this.morphTargets = source.morphTargets;
  11852. this.morphNormals = source.morphNormals;
  11853. return this;
  11854. };
  11855. // File:src/materials/MeshPhongMaterial.js
  11856. /**
  11857. * @author mrdoob / http://mrdoob.com/
  11858. * @author alteredq / http://alteredqualia.com/
  11859. *
  11860. * parameters = {
  11861. * color: <hex>,
  11862. * emissive: <hex>,
  11863. * specular: <hex>,
  11864. * shininess: <float>,
  11865. * opacity: <float>,
  11866. *
  11867. * map: new THREE.Texture( <Image> ),
  11868. *
  11869. * lightMap: new THREE.Texture( <Image> ),
  11870. * lightMapIntensity: <float>
  11871. *
  11872. * aoMap: new THREE.Texture( <Image> ),
  11873. * aoMapIntensity: <float>
  11874. *
  11875. * emissiveMap: new THREE.Texture( <Image> ),
  11876. *
  11877. * bumpMap: new THREE.Texture( <Image> ),
  11878. * bumpScale: <float>,
  11879. *
  11880. * normalMap: new THREE.Texture( <Image> ),
  11881. * normalScale: <Vector2>,
  11882. *
  11883. * displacementMap: new THREE.Texture( <Image> ),
  11884. * displacementScale: <float>,
  11885. * displacementBias: <float>,
  11886. *
  11887. * specularMap: new THREE.Texture( <Image> ),
  11888. *
  11889. * alphaMap: new THREE.Texture( <Image> ),
  11890. *
  11891. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  11892. * combine: THREE.Multiply,
  11893. * reflectivity: <float>,
  11894. * refractionRatio: <float>,
  11895. *
  11896. * shading: THREE.SmoothShading,
  11897. * blending: THREE.NormalBlending,
  11898. * depthTest: <bool>,
  11899. * depthWrite: <bool>,
  11900. *
  11901. * wireframe: <boolean>,
  11902. * wireframeLinewidth: <float>,
  11903. *
  11904. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  11905. *
  11906. * skinning: <bool>,
  11907. * morphTargets: <bool>,
  11908. * morphNormals: <bool>,
  11909. *
  11910. * fog: <bool>
  11911. * }
  11912. */
  11913. THREE.MeshPhongMaterial = function ( parameters ) {
  11914. THREE.Material.call( this );
  11915. this.type = 'MeshPhongMaterial';
  11916. this.color = new THREE.Color( 0xffffff ); // diffuse
  11917. this.emissive = new THREE.Color( 0x000000 );
  11918. this.specular = new THREE.Color( 0x111111 );
  11919. this.shininess = 30;
  11920. this.map = null;
  11921. this.lightMap = null;
  11922. this.lightMapIntensity = 1.0;
  11923. this.aoMap = null;
  11924. this.aoMapIntensity = 1.0;
  11925. this.emissiveMap = null;
  11926. this.bumpMap = null;
  11927. this.bumpScale = 1;
  11928. this.normalMap = null;
  11929. this.normalScale = new THREE.Vector2( 1, 1 );
  11930. this.displacementMap = null;
  11931. this.displacementScale = 1;
  11932. this.displacementBias = 0;
  11933. this.specularMap = null;
  11934. this.alphaMap = null;
  11935. this.envMap = null;
  11936. this.combine = THREE.MultiplyOperation;
  11937. this.reflectivity = 1;
  11938. this.refractionRatio = 0.98;
  11939. this.fog = true;
  11940. this.shading = THREE.SmoothShading;
  11941. this.wireframe = false;
  11942. this.wireframeLinewidth = 1;
  11943. this.wireframeLinecap = 'round';
  11944. this.wireframeLinejoin = 'round';
  11945. this.vertexColors = THREE.NoColors;
  11946. this.skinning = false;
  11947. this.morphTargets = false;
  11948. this.morphNormals = false;
  11949. this.setValues( parameters );
  11950. };
  11951. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  11952. THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial;
  11953. THREE.MeshPhongMaterial.prototype.copy = function ( source ) {
  11954. THREE.Material.prototype.copy.call( this, source );
  11955. this.color.copy( source.color );
  11956. this.emissive.copy( source.emissive );
  11957. this.specular.copy( source.specular );
  11958. this.shininess = source.shininess;
  11959. this.map = source.map;
  11960. this.lightMap = source.lightMap;
  11961. this.lightMapIntensity = source.lightMapIntensity;
  11962. this.aoMap = source.aoMap;
  11963. this.aoMapIntensity = source.aoMapIntensity;
  11964. this.emissiveMap = source.emissiveMap;
  11965. this.bumpMap = source.bumpMap;
  11966. this.bumpScale = source.bumpScale;
  11967. this.normalMap = source.normalMap;
  11968. this.normalScale.copy( source.normalScale );
  11969. this.displacementMap = source.displacementMap;
  11970. this.displacementScale = source.displacementScale;
  11971. this.displacementBias = source.displacementBias;
  11972. this.specularMap = source.specularMap;
  11973. this.alphaMap = source.alphaMap;
  11974. this.envMap = source.envMap;
  11975. this.combine = source.combine;
  11976. this.reflectivity = source.reflectivity;
  11977. this.refractionRatio = source.refractionRatio;
  11978. this.fog = source.fog;
  11979. this.shading = source.shading;
  11980. this.wireframe = source.wireframe;
  11981. this.wireframeLinewidth = source.wireframeLinewidth;
  11982. this.wireframeLinecap = source.wireframeLinecap;
  11983. this.wireframeLinejoin = source.wireframeLinejoin;
  11984. this.vertexColors = source.vertexColors;
  11985. this.skinning = source.skinning;
  11986. this.morphTargets = source.morphTargets;
  11987. this.morphNormals = source.morphNormals;
  11988. return this;
  11989. };
  11990. // File:src/materials/MeshPhysicalMaterial.js
  11991. /**
  11992. * @author WestLangley / http://github.com/WestLangley
  11993. *
  11994. * parameters = {
  11995. * color: <hex>,
  11996. * roughness: <float>,
  11997. * reflectivity: <float>,
  11998. * metalness: <float>,
  11999. * emissive: <hex>,
  12000. * opacity: <float>,
  12001. *
  12002. * map: new THREE.Texture( <Image> ),
  12003. *
  12004. * lightMap: new THREE.Texture( <Image> ),
  12005. * lightMapIntensity: <float>
  12006. *
  12007. * aoMap: new THREE.Texture( <Image> ),
  12008. * aoMapIntensity: <float>
  12009. *
  12010. * emissiveMap: new THREE.Texture( <Image> ),
  12011. *
  12012. * bumpMap: new THREE.Texture( <Image> ),
  12013. * bumpScale: <float>,
  12014. *
  12015. * normalMap: new THREE.Texture( <Image> ),
  12016. * normalScale: <Vector2>,
  12017. *
  12018. * displacementMap: new THREE.Texture( <Image> ),
  12019. * displacementScale: <float>,
  12020. * displacementBias: <float>,
  12021. *
  12022. * roughnessMap: new THREE.Texture( <Image> ),
  12023. *
  12024. * reflectivityMap: new THREE.Texture( <Image> ),
  12025. *
  12026. * metalnessMap: new THREE.Texture( <Image> ),
  12027. *
  12028. * alphaMap: new THREE.Texture( <Image> ),
  12029. *
  12030. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  12031. * refractionRatio: <float>,
  12032. *
  12033. * shading: THREE.SmoothShading,
  12034. * blending: THREE.NormalBlending,
  12035. * depthTest: <bool>,
  12036. * depthWrite: <bool>,
  12037. *
  12038. * wireframe: <boolean>,
  12039. * wireframeLinewidth: <float>,
  12040. *
  12041. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  12042. *
  12043. * skinning: <bool>,
  12044. * morphTargets: <bool>,
  12045. * morphNormals: <bool>,
  12046. *
  12047. * fog: <bool>
  12048. * }
  12049. */
  12050. THREE.MeshPhysicalMaterial = function ( parameters ) {
  12051. THREE.Material.call( this );
  12052. this.type = 'MeshPhysicalMaterial';
  12053. this.color = new THREE.Color( 0xffffff ); // diffuse
  12054. this.roughness = 0.5;
  12055. this.reflectivity = 1;
  12056. this.metalness = 0;
  12057. this.emissive = new THREE.Color( 0x000000 );
  12058. this.map = null;
  12059. this.lightMap = null;
  12060. this.lightMapIntensity = 1.0;
  12061. this.aoMap = null;
  12062. this.aoMapIntensity = 1.0;
  12063. this.emissiveMap = null;
  12064. this.bumpMap = null;
  12065. this.bumpScale = 1;
  12066. this.normalMap = null;
  12067. this.normalScale = new THREE.Vector2( 1, 1 );
  12068. this.displacementMap = null;
  12069. this.displacementScale = 1;
  12070. this.displacementBias = 0;
  12071. this.roughnessMap = null;
  12072. this.reflectivityMap = null;
  12073. this.metalnessMap = null;
  12074. this.alphaMap = null;
  12075. this.envMap = null;
  12076. this.envMapIntensity = 1.0;
  12077. this.refractionRatio = 0.98;
  12078. this.fog = true;
  12079. this.shading = THREE.SmoothShading;
  12080. this.wireframe = false;
  12081. this.wireframeLinewidth = 1;
  12082. this.wireframeLinecap = 'round';
  12083. this.wireframeLinejoin = 'round';
  12084. this.vertexColors = THREE.NoColors;
  12085. this.skinning = false;
  12086. this.morphTargets = false;
  12087. this.morphNormals = false;
  12088. this.setValues( parameters );
  12089. };
  12090. THREE.MeshPhysicalMaterial.prototype = Object.create( THREE.Material.prototype );
  12091. THREE.MeshPhysicalMaterial.prototype.constructor = THREE.MeshPhysicalMaterial;
  12092. THREE.MeshPhysicalMaterial.prototype.copy = function ( source ) {
  12093. THREE.Material.prototype.copy.call( this, source );
  12094. this.color.copy( source.color );
  12095. this.roughness = source.roughness;
  12096. this.reflectivity = source.reflectivity;
  12097. this.metalness = source.metalness;
  12098. this.emissive.copy( source.emissive );
  12099. this.map = source.map;
  12100. this.lightMap = source.lightMap;
  12101. this.lightMapIntensity = source.lightMapIntensity;
  12102. this.aoMap = source.aoMap;
  12103. this.aoMapIntensity = source.aoMapIntensity;
  12104. this.emissiveMap = source.emissiveMap;
  12105. this.bumpMap = source.bumpMap;
  12106. this.bumpScale = source.bumpScale;
  12107. this.normalMap = source.normalMap;
  12108. this.normalScale.copy( source.normalScale );
  12109. this.displacementMap = source.displacementMap;
  12110. this.displacementScale = source.displacementScale;
  12111. this.displacementBias = source.displacementBias;
  12112. this.roughnessMap = source.roughnessMap;
  12113. this.reflectivityMap = source.reflectivityMap;
  12114. this.metalnessMap = source.metalnessMap;
  12115. this.alphaMap = source.alphaMap;
  12116. this.envMap = source.envMap;
  12117. this.envMapIntensity = source.envMapIntensity;
  12118. this.refractionRatio = source.refractionRatio;
  12119. this.fog = source.fog;
  12120. this.shading = source.shading;
  12121. this.wireframe = source.wireframe;
  12122. this.wireframeLinewidth = source.wireframeLinewidth;
  12123. this.wireframeLinecap = source.wireframeLinecap;
  12124. this.wireframeLinejoin = source.wireframeLinejoin;
  12125. this.vertexColors = source.vertexColors;
  12126. this.skinning = source.skinning;
  12127. this.morphTargets = source.morphTargets;
  12128. this.morphNormals = source.morphNormals;
  12129. return this;
  12130. };
  12131. // File:src/materials/MeshDepthMaterial.js
  12132. /**
  12133. * @author mrdoob / http://mrdoob.com/
  12134. * @author alteredq / http://alteredqualia.com/
  12135. *
  12136. * parameters = {
  12137. * opacity: <float>,
  12138. *
  12139. * blending: THREE.NormalBlending,
  12140. * depthTest: <bool>,
  12141. * depthWrite: <bool>,
  12142. *
  12143. * wireframe: <boolean>,
  12144. * wireframeLinewidth: <float>
  12145. * }
  12146. */
  12147. THREE.MeshDepthMaterial = function ( parameters ) {
  12148. THREE.Material.call( this );
  12149. this.type = 'MeshDepthMaterial';
  12150. this.morphTargets = false;
  12151. this.wireframe = false;
  12152. this.wireframeLinewidth = 1;
  12153. this.setValues( parameters );
  12154. };
  12155. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  12156. THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial;
  12157. THREE.MeshDepthMaterial.prototype.copy = function ( source ) {
  12158. THREE.Material.prototype.copy.call( this, source );
  12159. this.wireframe = source.wireframe;
  12160. this.wireframeLinewidth = source.wireframeLinewidth;
  12161. return this;
  12162. };
  12163. // File:src/materials/MeshNormalMaterial.js
  12164. /**
  12165. * @author mrdoob / http://mrdoob.com/
  12166. *
  12167. * parameters = {
  12168. * opacity: <float>,
  12169. *
  12170. * shading: THREE.FlatShading,
  12171. * blending: THREE.NormalBlending,
  12172. * depthTest: <bool>,
  12173. * depthWrite: <bool>,
  12174. *
  12175. * wireframe: <boolean>,
  12176. * wireframeLinewidth: <float>
  12177. * }
  12178. */
  12179. THREE.MeshNormalMaterial = function ( parameters ) {
  12180. THREE.Material.call( this, parameters );
  12181. this.type = 'MeshNormalMaterial';
  12182. this.wireframe = false;
  12183. this.wireframeLinewidth = 1;
  12184. this.morphTargets = false;
  12185. this.setValues( parameters );
  12186. };
  12187. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  12188. THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial;
  12189. THREE.MeshNormalMaterial.prototype.copy = function ( source ) {
  12190. THREE.Material.prototype.copy.call( this, source );
  12191. this.wireframe = source.wireframe;
  12192. this.wireframeLinewidth = source.wireframeLinewidth;
  12193. return this;
  12194. };
  12195. // File:src/materials/MultiMaterial.js
  12196. /**
  12197. * @author mrdoob / http://mrdoob.com/
  12198. */
  12199. THREE.MultiMaterial = function ( materials ) {
  12200. this.uuid = THREE.Math.generateUUID();
  12201. this.type = 'MultiMaterial';
  12202. this.materials = materials instanceof Array ? materials : [];
  12203. this.visible = true;
  12204. };
  12205. THREE.MultiMaterial.prototype = {
  12206. constructor: THREE.MultiMaterial,
  12207. toJSON: function ( meta ) {
  12208. var output = {
  12209. metadata: {
  12210. version: 4.2,
  12211. type: 'material',
  12212. generator: 'MaterialExporter'
  12213. },
  12214. uuid: this.uuid,
  12215. type: this.type,
  12216. materials: []
  12217. };
  12218. var materials = this.materials;
  12219. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  12220. var material = materials[ i ].toJSON( meta );
  12221. delete material.metadata;
  12222. output.materials.push( material );
  12223. }
  12224. output.visible = this.visible;
  12225. return output;
  12226. },
  12227. clone: function () {
  12228. var material = new this.constructor();
  12229. for ( var i = 0; i < this.materials.length; i ++ ) {
  12230. material.materials.push( this.materials[ i ].clone() );
  12231. }
  12232. material.visible = this.visible;
  12233. return material;
  12234. }
  12235. };
  12236. // backwards compatibility
  12237. THREE.MeshFaceMaterial = THREE.MultiMaterial;
  12238. // File:src/materials/PointsMaterial.js
  12239. /**
  12240. * @author mrdoob / http://mrdoob.com/
  12241. * @author alteredq / http://alteredqualia.com/
  12242. *
  12243. * parameters = {
  12244. * color: <hex>,
  12245. * opacity: <float>,
  12246. * map: new THREE.Texture( <Image> ),
  12247. *
  12248. * size: <float>,
  12249. * sizeAttenuation: <bool>,
  12250. *
  12251. * blending: THREE.NormalBlending,
  12252. * depthTest: <bool>,
  12253. * depthWrite: <bool>,
  12254. *
  12255. * vertexColors: <bool>,
  12256. *
  12257. * fog: <bool>
  12258. * }
  12259. */
  12260. THREE.PointsMaterial = function ( parameters ) {
  12261. THREE.Material.call( this );
  12262. this.type = 'PointsMaterial';
  12263. this.color = new THREE.Color( 0xffffff );
  12264. this.map = null;
  12265. this.size = 1;
  12266. this.sizeAttenuation = true;
  12267. this.vertexColors = THREE.NoColors;
  12268. this.fog = true;
  12269. this.setValues( parameters );
  12270. };
  12271. THREE.PointsMaterial.prototype = Object.create( THREE.Material.prototype );
  12272. THREE.PointsMaterial.prototype.constructor = THREE.PointsMaterial;
  12273. THREE.PointsMaterial.prototype.copy = function ( source ) {
  12274. THREE.Material.prototype.copy.call( this, source );
  12275. this.color.copy( source.color );
  12276. this.map = source.map;
  12277. this.size = source.size;
  12278. this.sizeAttenuation = source.sizeAttenuation;
  12279. this.vertexColors = source.vertexColors;
  12280. this.fog = source.fog;
  12281. return this;
  12282. };
  12283. // File:src/materials/ShaderMaterial.js
  12284. /**
  12285. * @author alteredq / http://alteredqualia.com/
  12286. *
  12287. * parameters = {
  12288. * defines: { "label" : "value" },
  12289. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  12290. *
  12291. * fragmentShader: <string>,
  12292. * vertexShader: <string>,
  12293. *
  12294. * shading: THREE.SmoothShading,
  12295. * blending: THREE.NormalBlending,
  12296. * depthTest: <bool>,
  12297. * depthWrite: <bool>,
  12298. *
  12299. * wireframe: <boolean>,
  12300. * wireframeLinewidth: <float>,
  12301. *
  12302. * lights: <bool>,
  12303. *
  12304. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  12305. *
  12306. * skinning: <bool>,
  12307. * morphTargets: <bool>,
  12308. * morphNormals: <bool>,
  12309. *
  12310. * fog: <bool>
  12311. * }
  12312. */
  12313. THREE.ShaderMaterial = function ( parameters ) {
  12314. THREE.Material.call( this );
  12315. this.type = 'ShaderMaterial';
  12316. this.defines = {};
  12317. this.uniforms = {};
  12318. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  12319. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  12320. this.shading = THREE.SmoothShading;
  12321. this.linewidth = 1;
  12322. this.wireframe = false;
  12323. this.wireframeLinewidth = 1;
  12324. this.fog = false; // set to use scene fog
  12325. this.lights = false; // set to use scene lights
  12326. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  12327. this.skinning = false; // set to use skinning attribute streams
  12328. this.morphTargets = false; // set to use morph targets
  12329. this.morphNormals = false; // set to use morph normals
  12330. this.extensions = {
  12331. derivatives: false, // set to use derivatives
  12332. fragDepth: false, // set to use fragment depth values
  12333. drawBuffers: false, // set to use draw buffers
  12334. shaderTextureLOD: false // set to use shader texture LOD
  12335. };
  12336. // When rendered geometry doesn't include these attributes but the material does,
  12337. // use these default values in WebGL. This avoids errors when buffer data is missing.
  12338. this.defaultAttributeValues = {
  12339. 'color': [ 1, 1, 1 ],
  12340. 'uv': [ 0, 0 ],
  12341. 'uv2': [ 0, 0 ]
  12342. };
  12343. this.index0AttributeName = undefined;
  12344. if ( parameters !== undefined ) {
  12345. if ( parameters.attributes !== undefined ) {
  12346. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  12347. }
  12348. this.setValues( parameters );
  12349. }
  12350. };
  12351. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  12352. THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial;
  12353. THREE.ShaderMaterial.prototype.copy = function ( source ) {
  12354. THREE.Material.prototype.copy.call( this, source );
  12355. this.fragmentShader = source.fragmentShader;
  12356. this.vertexShader = source.vertexShader;
  12357. this.uniforms = THREE.UniformsUtils.clone( source.uniforms );
  12358. this.attributes = source.attributes;
  12359. this.defines = source.defines;
  12360. this.shading = source.shading;
  12361. this.wireframe = source.wireframe;
  12362. this.wireframeLinewidth = source.wireframeLinewidth;
  12363. this.fog = source.fog;
  12364. this.lights = source.lights;
  12365. this.vertexColors = source.vertexColors;
  12366. this.skinning = source.skinning;
  12367. this.morphTargets = source.morphTargets;
  12368. this.morphNormals = source.morphNormals;
  12369. this.extensions = source.extensions;
  12370. return this;
  12371. };
  12372. THREE.ShaderMaterial.prototype.toJSON = function ( meta ) {
  12373. var data = THREE.Material.prototype.toJSON.call( this, meta );
  12374. data.uniforms = this.uniforms;
  12375. data.attributes = this.attributes;
  12376. data.vertexShader = this.vertexShader;
  12377. data.fragmentShader = this.fragmentShader;
  12378. return data;
  12379. };
  12380. // File:src/materials/RawShaderMaterial.js
  12381. /**
  12382. * @author mrdoob / http://mrdoob.com/
  12383. */
  12384. THREE.RawShaderMaterial = function ( parameters ) {
  12385. THREE.ShaderMaterial.call( this, parameters );
  12386. this.type = 'RawShaderMaterial';
  12387. };
  12388. THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype );
  12389. THREE.RawShaderMaterial.prototype.constructor = THREE.RawShaderMaterial;
  12390. // File:src/materials/SpriteMaterial.js
  12391. /**
  12392. * @author alteredq / http://alteredqualia.com/
  12393. *
  12394. * parameters = {
  12395. * color: <hex>,
  12396. * opacity: <float>,
  12397. * map: new THREE.Texture( <Image> ),
  12398. *
  12399. * blending: THREE.NormalBlending,
  12400. * depthTest: <bool>,
  12401. * depthWrite: <bool>,
  12402. *
  12403. * uvOffset: new THREE.Vector2(),
  12404. * uvScale: new THREE.Vector2(),
  12405. *
  12406. * fog: <bool>
  12407. * }
  12408. */
  12409. THREE.SpriteMaterial = function ( parameters ) {
  12410. THREE.Material.call( this );
  12411. this.type = 'SpriteMaterial';
  12412. this.color = new THREE.Color( 0xffffff );
  12413. this.map = null;
  12414. this.rotation = 0;
  12415. this.fog = false;
  12416. // set parameters
  12417. this.setValues( parameters );
  12418. };
  12419. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  12420. THREE.SpriteMaterial.prototype.constructor = THREE.SpriteMaterial;
  12421. THREE.SpriteMaterial.prototype.copy = function ( source ) {
  12422. THREE.Material.prototype.copy.call( this, source );
  12423. this.color.copy( source.color );
  12424. this.map = source.map;
  12425. this.rotation = source.rotation;
  12426. this.fog = source.fog;
  12427. return this;
  12428. };
  12429. // File:src/textures/Texture.js
  12430. /**
  12431. * @author mrdoob / http://mrdoob.com/
  12432. * @author alteredq / http://alteredqualia.com/
  12433. * @author szimek / https://github.com/szimek/
  12434. */
  12435. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  12436. Object.defineProperty( this, 'id', { value: THREE.TextureIdCount ++ } );
  12437. this.uuid = THREE.Math.generateUUID();
  12438. this.name = '';
  12439. this.sourceFile = '';
  12440. this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE;
  12441. this.mipmaps = [];
  12442. this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING;
  12443. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  12444. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  12445. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  12446. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  12447. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  12448. this.format = format !== undefined ? format : THREE.RGBAFormat;
  12449. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  12450. this.offset = new THREE.Vector2( 0, 0 );
  12451. this.repeat = new THREE.Vector2( 1, 1 );
  12452. this.generateMipmaps = true;
  12453. this.premultiplyAlpha = false;
  12454. this.flipY = true;
  12455. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  12456. this.version = 0;
  12457. this.onUpdate = null;
  12458. };
  12459. THREE.Texture.DEFAULT_IMAGE = undefined;
  12460. THREE.Texture.DEFAULT_MAPPING = THREE.UVMapping;
  12461. THREE.Texture.prototype = {
  12462. constructor: THREE.Texture,
  12463. set needsUpdate ( value ) {
  12464. if ( value === true ) this.version ++;
  12465. },
  12466. clone: function () {
  12467. return new this.constructor().copy( this );
  12468. },
  12469. copy: function ( source ) {
  12470. this.image = source.image;
  12471. this.mipmaps = source.mipmaps.slice( 0 );
  12472. this.mapping = source.mapping;
  12473. this.wrapS = source.wrapS;
  12474. this.wrapT = source.wrapT;
  12475. this.magFilter = source.magFilter;
  12476. this.minFilter = source.minFilter;
  12477. this.anisotropy = source.anisotropy;
  12478. this.format = source.format;
  12479. this.type = source.type;
  12480. this.offset.copy( source.offset );
  12481. this.repeat.copy( source.repeat );
  12482. this.generateMipmaps = source.generateMipmaps;
  12483. this.premultiplyAlpha = source.premultiplyAlpha;
  12484. this.flipY = source.flipY;
  12485. this.unpackAlignment = source.unpackAlignment;
  12486. return this;
  12487. },
  12488. toJSON: function ( meta ) {
  12489. if ( meta.textures[ this.uuid ] !== undefined ) {
  12490. return meta.textures[ this.uuid ];
  12491. }
  12492. function getDataURL( image ) {
  12493. var canvas;
  12494. if ( image.toDataURL !== undefined ) {
  12495. canvas = image;
  12496. } else {
  12497. canvas = document.createElement( 'canvas' );
  12498. canvas.width = image.width;
  12499. canvas.height = image.height;
  12500. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  12501. }
  12502. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  12503. return canvas.toDataURL( 'image/jpeg', 0.6 );
  12504. } else {
  12505. return canvas.toDataURL( 'image/png' );
  12506. }
  12507. }
  12508. var output = {
  12509. metadata: {
  12510. version: 4.4,
  12511. type: 'Texture',
  12512. generator: 'Texture.toJSON'
  12513. },
  12514. uuid: this.uuid,
  12515. name: this.name,
  12516. mapping: this.mapping,
  12517. repeat: [ this.repeat.x, this.repeat.y ],
  12518. offset: [ this.offset.x, this.offset.y ],
  12519. wrap: [ this.wrapS, this.wrapT ],
  12520. minFilter: this.minFilter,
  12521. magFilter: this.magFilter,
  12522. anisotropy: this.anisotropy
  12523. };
  12524. if ( this.image !== undefined ) {
  12525. // TODO: Move to THREE.Image
  12526. var image = this.image;
  12527. if ( image.uuid === undefined ) {
  12528. image.uuid = THREE.Math.generateUUID(); // UGH
  12529. }
  12530. if ( meta.images[ image.uuid ] === undefined ) {
  12531. meta.images[ image.uuid ] = {
  12532. uuid: image.uuid,
  12533. url: getDataURL( image )
  12534. };
  12535. }
  12536. output.image = image.uuid;
  12537. }
  12538. meta.textures[ this.uuid ] = output;
  12539. return output;
  12540. },
  12541. dispose: function () {
  12542. this.dispatchEvent( { type: 'dispose' } );
  12543. },
  12544. transformUv: function ( uv ) {
  12545. if ( this.mapping !== THREE.UVMapping ) return;
  12546. uv.multiply( this.repeat );
  12547. uv.add( this.offset );
  12548. if ( uv.x < 0 || uv.x > 1 ) {
  12549. switch ( this.wrapS ) {
  12550. case THREE.RepeatWrapping:
  12551. uv.x = uv.x - Math.floor( uv.x );
  12552. break;
  12553. case THREE.ClampToEdgeWrapping:
  12554. uv.x = uv.x < 0 ? 0 : 1;
  12555. break;
  12556. case THREE.MirroredRepeatWrapping:
  12557. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  12558. uv.x = Math.ceil( uv.x ) - uv.x;
  12559. } else {
  12560. uv.x = uv.x - Math.floor( uv.x );
  12561. }
  12562. break;
  12563. }
  12564. }
  12565. if ( uv.y < 0 || uv.y > 1 ) {
  12566. switch ( this.wrapT ) {
  12567. case THREE.RepeatWrapping:
  12568. uv.y = uv.y - Math.floor( uv.y );
  12569. break;
  12570. case THREE.ClampToEdgeWrapping:
  12571. uv.y = uv.y < 0 ? 0 : 1;
  12572. break;
  12573. case THREE.MirroredRepeatWrapping:
  12574. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  12575. uv.y = Math.ceil( uv.y ) - uv.y;
  12576. } else {
  12577. uv.y = uv.y - Math.floor( uv.y );
  12578. }
  12579. break;
  12580. }
  12581. }
  12582. if ( this.flipY ) {
  12583. uv.y = 1 - uv.y;
  12584. }
  12585. }
  12586. };
  12587. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  12588. THREE.TextureIdCount = 0;
  12589. // File:src/textures/CanvasTexture.js
  12590. /**
  12591. * @author mrdoob / http://mrdoob.com/
  12592. */
  12593. THREE.CanvasTexture = function ( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  12594. THREE.Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12595. this.needsUpdate = true;
  12596. };
  12597. THREE.CanvasTexture.prototype = Object.create( THREE.Texture.prototype );
  12598. THREE.CanvasTexture.prototype.constructor = THREE.CanvasTexture;
  12599. // File:src/textures/CubeTexture.js
  12600. /**
  12601. * @author mrdoob / http://mrdoob.com/
  12602. */
  12603. THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  12604. mapping = mapping !== undefined ? mapping : THREE.CubeReflectionMapping;
  12605. THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12606. this.images = images;
  12607. this.flipY = false;
  12608. };
  12609. THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype );
  12610. THREE.CubeTexture.prototype.constructor = THREE.CubeTexture;
  12611. THREE.CubeTexture.prototype.copy = function ( source ) {
  12612. THREE.Texture.prototype.copy.call( this, source );
  12613. this.images = source.images;
  12614. return this;
  12615. };
  12616. // File:src/textures/CompressedTexture.js
  12617. /**
  12618. * @author alteredq / http://alteredqualia.com/
  12619. */
  12620. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  12621. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12622. this.image = { width: width, height: height };
  12623. this.mipmaps = mipmaps;
  12624. // no flipping for cube textures
  12625. // (also flipping doesn't work for compressed textures )
  12626. this.flipY = false;
  12627. // can't generate mipmaps for compressed textures
  12628. // mips must be embedded in DDS files
  12629. this.generateMipmaps = false;
  12630. };
  12631. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  12632. THREE.CompressedTexture.prototype.constructor = THREE.CompressedTexture;
  12633. // File:src/textures/DataTexture.js
  12634. /**
  12635. * @author alteredq / http://alteredqualia.com/
  12636. */
  12637. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  12638. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12639. this.image = { data: data, width: width, height: height };
  12640. this.magFilter = magFilter !== undefined ? magFilter : THREE.NearestFilter;
  12641. this.minFilter = minFilter !== undefined ? minFilter : THREE.NearestFilter;
  12642. this.flipY = false;
  12643. this.generateMipmaps = false;
  12644. };
  12645. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  12646. THREE.DataTexture.prototype.constructor = THREE.DataTexture;
  12647. // File:src/textures/VideoTexture.js
  12648. /**
  12649. * @author mrdoob / http://mrdoob.com/
  12650. */
  12651. THREE.VideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  12652. THREE.Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12653. this.generateMipmaps = false;
  12654. var scope = this;
  12655. function update() {
  12656. requestAnimationFrame( update );
  12657. if ( video.readyState === video.HAVE_ENOUGH_DATA ) {
  12658. scope.needsUpdate = true;
  12659. }
  12660. }
  12661. update();
  12662. };
  12663. THREE.VideoTexture.prototype = Object.create( THREE.Texture.prototype );
  12664. THREE.VideoTexture.prototype.constructor = THREE.VideoTexture;
  12665. // File:src/objects/Group.js
  12666. /**
  12667. * @author mrdoob / http://mrdoob.com/
  12668. */
  12669. THREE.Group = function () {
  12670. THREE.Object3D.call( this );
  12671. this.type = 'Group';
  12672. };
  12673. THREE.Group.prototype = Object.create( THREE.Object3D.prototype );
  12674. THREE.Group.prototype.constructor = THREE.Group;
  12675. // File:src/objects/Points.js
  12676. /**
  12677. * @author alteredq / http://alteredqualia.com/
  12678. */
  12679. THREE.Points = function ( geometry, material ) {
  12680. THREE.Object3D.call( this );
  12681. this.type = 'Points';
  12682. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  12683. this.material = material !== undefined ? material : new THREE.PointsMaterial( { color: Math.random() * 0xffffff } );
  12684. };
  12685. THREE.Points.prototype = Object.create( THREE.Object3D.prototype );
  12686. THREE.Points.prototype.constructor = THREE.Points;
  12687. THREE.Points.prototype.raycast = ( function () {
  12688. var inverseMatrix = new THREE.Matrix4();
  12689. var ray = new THREE.Ray();
  12690. return function raycast( raycaster, intersects ) {
  12691. var object = this;
  12692. var geometry = object.geometry;
  12693. var threshold = raycaster.params.Points.threshold;
  12694. inverseMatrix.getInverse( this.matrixWorld );
  12695. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  12696. if ( geometry.boundingBox !== null ) {
  12697. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  12698. }
  12699. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  12700. var localThresholdSq = localThreshold * localThreshold;
  12701. var position = new THREE.Vector3();
  12702. function testPoint( point, index ) {
  12703. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  12704. if ( rayPointDistanceSq < localThresholdSq ) {
  12705. var intersectPoint = ray.closestPointToPoint( point );
  12706. intersectPoint.applyMatrix4( object.matrixWorld );
  12707. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  12708. if ( distance < raycaster.near || distance > raycaster.far ) return;
  12709. intersects.push( {
  12710. distance: distance,
  12711. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  12712. point: intersectPoint.clone(),
  12713. index: index,
  12714. face: null,
  12715. object: object
  12716. } );
  12717. }
  12718. }
  12719. if ( geometry instanceof THREE.BufferGeometry ) {
  12720. var index = geometry.index;
  12721. var attributes = geometry.attributes;
  12722. var positions = attributes.position.array;
  12723. if ( index !== null ) {
  12724. var indices = index.array;
  12725. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  12726. var a = indices[ i ];
  12727. position.fromArray( positions, a * 3 );
  12728. testPoint( position, a );
  12729. }
  12730. } else {
  12731. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  12732. position.fromArray( positions, i * 3 );
  12733. testPoint( position, i );
  12734. }
  12735. }
  12736. } else {
  12737. var vertices = geometry.vertices;
  12738. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  12739. testPoint( vertices[ i ], i );
  12740. }
  12741. }
  12742. };
  12743. }() );
  12744. THREE.Points.prototype.clone = function () {
  12745. return new this.constructor( this.geometry, this.material ).copy( this );
  12746. };
  12747. // File:src/objects/Line.js
  12748. /**
  12749. * @author mrdoob / http://mrdoob.com/
  12750. */
  12751. THREE.Line = function ( geometry, material, mode ) {
  12752. if ( mode === 1 ) {
  12753. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  12754. return new THREE.LineSegments( geometry, material );
  12755. }
  12756. THREE.Object3D.call( this );
  12757. this.type = 'Line';
  12758. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  12759. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  12760. };
  12761. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  12762. THREE.Line.prototype.constructor = THREE.Line;
  12763. THREE.Line.prototype.raycast = ( function () {
  12764. var inverseMatrix = new THREE.Matrix4();
  12765. var ray = new THREE.Ray();
  12766. var sphere = new THREE.Sphere();
  12767. return function raycast( raycaster, intersects ) {
  12768. var precision = raycaster.linePrecision;
  12769. var precisionSq = precision * precision;
  12770. var geometry = this.geometry;
  12771. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  12772. // Checking boundingSphere distance to ray
  12773. sphere.copy( geometry.boundingSphere );
  12774. sphere.applyMatrix4( this.matrixWorld );
  12775. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  12776. inverseMatrix.getInverse( this.matrixWorld );
  12777. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  12778. var vStart = new THREE.Vector3();
  12779. var vEnd = new THREE.Vector3();
  12780. var interSegment = new THREE.Vector3();
  12781. var interRay = new THREE.Vector3();
  12782. var step = this instanceof THREE.LineSegments ? 2 : 1;
  12783. if ( geometry instanceof THREE.BufferGeometry ) {
  12784. var index = geometry.index;
  12785. var attributes = geometry.attributes;
  12786. if ( index !== null ) {
  12787. var indices = index.array;
  12788. var positions = attributes.position.array;
  12789. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  12790. var a = indices[ i ];
  12791. var b = indices[ i + 1 ];
  12792. vStart.fromArray( positions, a * 3 );
  12793. vEnd.fromArray( positions, b * 3 );
  12794. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  12795. if ( distSq > precisionSq ) continue;
  12796. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  12797. var distance = raycaster.ray.origin.distanceTo( interRay );
  12798. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  12799. intersects.push( {
  12800. distance: distance,
  12801. // What do we want? intersection point on the ray or on the segment??
  12802. // point: raycaster.ray.at( distance ),
  12803. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  12804. index: i,
  12805. face: null,
  12806. faceIndex: null,
  12807. object: this
  12808. } );
  12809. }
  12810. } else {
  12811. var positions = attributes.position.array;
  12812. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  12813. vStart.fromArray( positions, 3 * i );
  12814. vEnd.fromArray( positions, 3 * i + 3 );
  12815. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  12816. if ( distSq > precisionSq ) continue;
  12817. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  12818. var distance = raycaster.ray.origin.distanceTo( interRay );
  12819. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  12820. intersects.push( {
  12821. distance: distance,
  12822. // What do we want? intersection point on the ray or on the segment??
  12823. // point: raycaster.ray.at( distance ),
  12824. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  12825. index: i,
  12826. face: null,
  12827. faceIndex: null,
  12828. object: this
  12829. } );
  12830. }
  12831. }
  12832. } else if ( geometry instanceof THREE.Geometry ) {
  12833. var vertices = geometry.vertices;
  12834. var nbVertices = vertices.length;
  12835. for ( var i = 0; i < nbVertices - 1; i += step ) {
  12836. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  12837. if ( distSq > precisionSq ) continue;
  12838. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  12839. var distance = raycaster.ray.origin.distanceTo( interRay );
  12840. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  12841. intersects.push( {
  12842. distance: distance,
  12843. // What do we want? intersection point on the ray or on the segment??
  12844. // point: raycaster.ray.at( distance ),
  12845. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  12846. index: i,
  12847. face: null,
  12848. faceIndex: null,
  12849. object: this
  12850. } );
  12851. }
  12852. }
  12853. };
  12854. }() );
  12855. THREE.Line.prototype.clone = function () {
  12856. return new this.constructor( this.geometry, this.material ).copy( this );
  12857. };
  12858. // DEPRECATED
  12859. THREE.LineStrip = 0;
  12860. THREE.LinePieces = 1;
  12861. // File:src/objects/LineSegments.js
  12862. /**
  12863. * @author mrdoob / http://mrdoob.com/
  12864. */
  12865. THREE.LineSegments = function ( geometry, material ) {
  12866. THREE.Line.call( this, geometry, material );
  12867. this.type = 'LineSegments';
  12868. };
  12869. THREE.LineSegments.prototype = Object.create( THREE.Line.prototype );
  12870. THREE.LineSegments.prototype.constructor = THREE.LineSegments;
  12871. // File:src/objects/Mesh.js
  12872. /**
  12873. * @author mrdoob / http://mrdoob.com/
  12874. * @author alteredq / http://alteredqualia.com/
  12875. * @author mikael emtinger / http://gomo.se/
  12876. * @author jonobr1 / http://jonobr1.com/
  12877. */
  12878. THREE.Mesh = function ( geometry, material ) {
  12879. THREE.Object3D.call( this );
  12880. this.type = 'Mesh';
  12881. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  12882. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  12883. this.updateMorphTargets();
  12884. };
  12885. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  12886. THREE.Mesh.prototype.constructor = THREE.Mesh;
  12887. THREE.Mesh.prototype.updateMorphTargets = function () {
  12888. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  12889. this.morphTargetBase = - 1;
  12890. this.morphTargetInfluences = [];
  12891. this.morphTargetDictionary = {};
  12892. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  12893. this.morphTargetInfluences.push( 0 );
  12894. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  12895. }
  12896. }
  12897. };
  12898. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  12899. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  12900. return this.morphTargetDictionary[ name ];
  12901. }
  12902. console.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' );
  12903. return 0;
  12904. };
  12905. THREE.Mesh.prototype.raycast = ( function () {
  12906. var inverseMatrix = new THREE.Matrix4();
  12907. var ray = new THREE.Ray();
  12908. var sphere = new THREE.Sphere();
  12909. var vA = new THREE.Vector3();
  12910. var vB = new THREE.Vector3();
  12911. var vC = new THREE.Vector3();
  12912. var tempA = new THREE.Vector3();
  12913. var tempB = new THREE.Vector3();
  12914. var tempC = new THREE.Vector3();
  12915. var uvA = new THREE.Vector2();
  12916. var uvB = new THREE.Vector2();
  12917. var uvC = new THREE.Vector2();
  12918. var barycoord = new THREE.Vector3();
  12919. var intersectionPoint = new THREE.Vector3();
  12920. var intersectionPointWorld = new THREE.Vector3();
  12921. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  12922. THREE.Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  12923. uv1.multiplyScalar( barycoord.x );
  12924. uv2.multiplyScalar( barycoord.y );
  12925. uv3.multiplyScalar( barycoord.z );
  12926. uv1.add( uv2 ).add( uv3 );
  12927. return uv1.clone();
  12928. }
  12929. function checkIntersection( object, raycaster, ray, pA, pB, pC, point ){
  12930. var intersect;
  12931. var material = object.material;
  12932. if ( material.side === THREE.BackSide ) {
  12933. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  12934. } else {
  12935. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== THREE.DoubleSide, point );
  12936. }
  12937. if ( intersect === null ) return null;
  12938. intersectionPointWorld.copy( point );
  12939. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  12940. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  12941. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  12942. return {
  12943. distance: distance,
  12944. point: intersectionPointWorld.clone(),
  12945. object: object
  12946. };
  12947. }
  12948. function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) {
  12949. vA.fromArray( positions, a * 3 );
  12950. vB.fromArray( positions, b * 3 );
  12951. vC.fromArray( positions, c * 3 );
  12952. var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint );
  12953. if ( intersection ) {
  12954. if ( uvs ) {
  12955. uvA.fromArray( uvs, a * 2 );
  12956. uvB.fromArray( uvs, b * 2 );
  12957. uvC.fromArray( uvs, c * 2 );
  12958. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  12959. }
  12960. intersection.face = new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) );
  12961. intersection.faceIndex = a;
  12962. }
  12963. return intersection;
  12964. }
  12965. return function raycast( raycaster, intersects ) {
  12966. var geometry = this.geometry;
  12967. var material = this.material;
  12968. if ( material === undefined ) return;
  12969. // Checking boundingSphere distance to ray
  12970. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  12971. var matrixWorld = this.matrixWorld;
  12972. sphere.copy( geometry.boundingSphere );
  12973. sphere.applyMatrix4( matrixWorld );
  12974. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  12975. // Check boundingBox before continuing
  12976. inverseMatrix.getInverse( matrixWorld );
  12977. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  12978. if ( geometry.boundingBox !== null ) {
  12979. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  12980. }
  12981. var uvs, intersection;
  12982. if ( geometry instanceof THREE.BufferGeometry ) {
  12983. var a, b, c;
  12984. var index = geometry.index;
  12985. var attributes = geometry.attributes;
  12986. var positions = attributes.position.array;
  12987. if ( attributes.uv !== undefined ){
  12988. uvs = attributes.uv.array;
  12989. }
  12990. if ( index !== null ) {
  12991. var indices = index.array;
  12992. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  12993. a = indices[ i ];
  12994. b = indices[ i + 1 ];
  12995. c = indices[ i + 2 ];
  12996. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  12997. if ( intersection ) {
  12998. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  12999. intersects.push( intersection );
  13000. }
  13001. }
  13002. } else {
  13003. for ( var i = 0, l = positions.length; i < l; i += 9 ) {
  13004. a = i / 3;
  13005. b = a + 1;
  13006. c = a + 2;
  13007. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  13008. if ( intersection ) {
  13009. intersection.index = a; // triangle number in positions buffer semantics
  13010. intersects.push( intersection );
  13011. }
  13012. }
  13013. }
  13014. } else if ( geometry instanceof THREE.Geometry ) {
  13015. var fvA, fvB, fvC;
  13016. var isFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  13017. var materials = isFaceMaterial === true ? material.materials : null;
  13018. var vertices = geometry.vertices;
  13019. var faces = geometry.faces;
  13020. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  13021. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  13022. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  13023. var face = faces[ f ];
  13024. var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material;
  13025. if ( faceMaterial === undefined ) continue;
  13026. fvA = vertices[ face.a ];
  13027. fvB = vertices[ face.b ];
  13028. fvC = vertices[ face.c ];
  13029. if ( faceMaterial.morphTargets === true ) {
  13030. var morphTargets = geometry.morphTargets;
  13031. var morphInfluences = this.morphTargetInfluences;
  13032. vA.set( 0, 0, 0 );
  13033. vB.set( 0, 0, 0 );
  13034. vC.set( 0, 0, 0 );
  13035. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  13036. var influence = morphInfluences[ t ];
  13037. if ( influence === 0 ) continue;
  13038. var targets = morphTargets[ t ].vertices;
  13039. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  13040. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  13041. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  13042. }
  13043. vA.add( fvA );
  13044. vB.add( fvB );
  13045. vC.add( fvC );
  13046. fvA = vA;
  13047. fvB = vB;
  13048. fvC = vC;
  13049. }
  13050. intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  13051. if ( intersection ) {
  13052. if ( uvs ) {
  13053. var uvs_f = uvs[ f ];
  13054. uvA.copy( uvs_f[ 0 ] );
  13055. uvB.copy( uvs_f[ 1 ] );
  13056. uvC.copy( uvs_f[ 2 ] );
  13057. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  13058. }
  13059. intersection.face = face;
  13060. intersection.faceIndex = f;
  13061. intersects.push( intersection );
  13062. }
  13063. }
  13064. }
  13065. };
  13066. }() );
  13067. THREE.Mesh.prototype.clone = function () {
  13068. return new this.constructor( this.geometry, this.material ).copy( this );
  13069. };
  13070. // File:src/objects/Bone.js
  13071. /**
  13072. * @author mikael emtinger / http://gomo.se/
  13073. * @author alteredq / http://alteredqualia.com/
  13074. * @author ikerr / http://verold.com
  13075. */
  13076. THREE.Bone = function ( skin ) {
  13077. THREE.Object3D.call( this );
  13078. this.type = 'Bone';
  13079. this.skin = skin;
  13080. };
  13081. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  13082. THREE.Bone.prototype.constructor = THREE.Bone;
  13083. THREE.Bone.prototype.copy = function ( source ) {
  13084. THREE.Object3D.prototype.copy.call( this, source );
  13085. this.skin = source.skin;
  13086. return this;
  13087. };
  13088. // File:src/objects/Skeleton.js
  13089. /**
  13090. * @author mikael emtinger / http://gomo.se/
  13091. * @author alteredq / http://alteredqualia.com/
  13092. * @author michael guerrero / http://realitymeltdown.com
  13093. * @author ikerr / http://verold.com
  13094. */
  13095. THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) {
  13096. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  13097. this.identityMatrix = new THREE.Matrix4();
  13098. // copy the bone array
  13099. bones = bones || [];
  13100. this.bones = bones.slice( 0 );
  13101. // create a bone texture or an array of floats
  13102. if ( this.useVertexTexture ) {
  13103. // layout (1 matrix = 4 pixels)
  13104. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  13105. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  13106. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  13107. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  13108. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  13109. var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  13110. size = THREE.Math.nextPowerOfTwo( Math.ceil( size ) );
  13111. size = Math.max( size, 4 );
  13112. this.boneTextureWidth = size;
  13113. this.boneTextureHeight = size;
  13114. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  13115. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  13116. } else {
  13117. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  13118. }
  13119. // use the supplied bone inverses or calculate the inverses
  13120. if ( boneInverses === undefined ) {
  13121. this.calculateInverses();
  13122. } else {
  13123. if ( this.bones.length === boneInverses.length ) {
  13124. this.boneInverses = boneInverses.slice( 0 );
  13125. } else {
  13126. console.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  13127. this.boneInverses = [];
  13128. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13129. this.boneInverses.push( new THREE.Matrix4() );
  13130. }
  13131. }
  13132. }
  13133. };
  13134. THREE.Skeleton.prototype.calculateInverses = function () {
  13135. this.boneInverses = [];
  13136. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13137. var inverse = new THREE.Matrix4();
  13138. if ( this.bones[ b ] ) {
  13139. inverse.getInverse( this.bones[ b ].matrixWorld );
  13140. }
  13141. this.boneInverses.push( inverse );
  13142. }
  13143. };
  13144. THREE.Skeleton.prototype.pose = function () {
  13145. var bone;
  13146. // recover the bind-time world matrices
  13147. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13148. bone = this.bones[ b ];
  13149. if ( bone ) {
  13150. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  13151. }
  13152. }
  13153. // compute the local matrices, positions, rotations and scales
  13154. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13155. bone = this.bones[ b ];
  13156. if ( bone ) {
  13157. if ( bone.parent ) {
  13158. bone.matrix.getInverse( bone.parent.matrixWorld );
  13159. bone.matrix.multiply( bone.matrixWorld );
  13160. } else {
  13161. bone.matrix.copy( bone.matrixWorld );
  13162. }
  13163. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  13164. }
  13165. }
  13166. };
  13167. THREE.Skeleton.prototype.update = ( function () {
  13168. var offsetMatrix = new THREE.Matrix4();
  13169. return function update() {
  13170. // flatten bone matrices to array
  13171. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13172. // compute the offset between the current and the original transform
  13173. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  13174. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  13175. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  13176. }
  13177. if ( this.useVertexTexture ) {
  13178. this.boneTexture.needsUpdate = true;
  13179. }
  13180. };
  13181. } )();
  13182. THREE.Skeleton.prototype.clone = function () {
  13183. return new THREE.Skeleton( this.bones, this.boneInverses, this.useVertexTexture );
  13184. };
  13185. // File:src/objects/SkinnedMesh.js
  13186. /**
  13187. * @author mikael emtinger / http://gomo.se/
  13188. * @author alteredq / http://alteredqualia.com/
  13189. * @author ikerr / http://verold.com
  13190. */
  13191. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  13192. THREE.Mesh.call( this, geometry, material );
  13193. this.type = 'SkinnedMesh';
  13194. this.bindMode = "attached";
  13195. this.bindMatrix = new THREE.Matrix4();
  13196. this.bindMatrixInverse = new THREE.Matrix4();
  13197. // init bones
  13198. // TODO: remove bone creation as there is no reason (other than
  13199. // convenience) for THREE.SkinnedMesh to do this.
  13200. var bones = [];
  13201. if ( this.geometry && this.geometry.bones !== undefined ) {
  13202. var bone, gbone;
  13203. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13204. gbone = this.geometry.bones[ b ];
  13205. bone = new THREE.Bone( this );
  13206. bones.push( bone );
  13207. bone.name = gbone.name;
  13208. bone.position.fromArray( gbone.pos );
  13209. bone.quaternion.fromArray( gbone.rotq );
  13210. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  13211. }
  13212. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13213. gbone = this.geometry.bones[ b ];
  13214. if ( gbone.parent !== - 1 && gbone.parent !== null) {
  13215. bones[ gbone.parent ].add( bones[ b ] );
  13216. } else {
  13217. this.add( bones[ b ] );
  13218. }
  13219. }
  13220. }
  13221. this.normalizeSkinWeights();
  13222. this.updateMatrixWorld( true );
  13223. this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld );
  13224. };
  13225. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  13226. THREE.SkinnedMesh.prototype.constructor = THREE.SkinnedMesh;
  13227. THREE.SkinnedMesh.prototype.bind = function( skeleton, bindMatrix ) {
  13228. this.skeleton = skeleton;
  13229. if ( bindMatrix === undefined ) {
  13230. this.updateMatrixWorld( true );
  13231. this.skeleton.calculateInverses();
  13232. bindMatrix = this.matrixWorld;
  13233. }
  13234. this.bindMatrix.copy( bindMatrix );
  13235. this.bindMatrixInverse.getInverse( bindMatrix );
  13236. };
  13237. THREE.SkinnedMesh.prototype.pose = function () {
  13238. this.skeleton.pose();
  13239. };
  13240. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  13241. if ( this.geometry instanceof THREE.Geometry ) {
  13242. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  13243. var sw = this.geometry.skinWeights[ i ];
  13244. var scale = 1.0 / sw.lengthManhattan();
  13245. if ( scale !== Infinity ) {
  13246. sw.multiplyScalar( scale );
  13247. } else {
  13248. sw.set( 1 ); // this will be normalized by the shader anyway
  13249. }
  13250. }
  13251. } else {
  13252. // skinning weights assumed to be normalized for THREE.BufferGeometry
  13253. }
  13254. };
  13255. THREE.SkinnedMesh.prototype.updateMatrixWorld = function( force ) {
  13256. THREE.Mesh.prototype.updateMatrixWorld.call( this, true );
  13257. if ( this.bindMode === "attached" ) {
  13258. this.bindMatrixInverse.getInverse( this.matrixWorld );
  13259. } else if ( this.bindMode === "detached" ) {
  13260. this.bindMatrixInverse.getInverse( this.bindMatrix );
  13261. } else {
  13262. console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode );
  13263. }
  13264. };
  13265. THREE.SkinnedMesh.prototype.clone = function() {
  13266. return new this.constructor( this.geometry, this.material, this.useVertexTexture ).copy( this );
  13267. };
  13268. // File:src/objects/LOD.js
  13269. /**
  13270. * @author mikael emtinger / http://gomo.se/
  13271. * @author alteredq / http://alteredqualia.com/
  13272. * @author mrdoob / http://mrdoob.com/
  13273. */
  13274. THREE.LOD = function () {
  13275. THREE.Object3D.call( this );
  13276. this.type = 'LOD';
  13277. Object.defineProperties( this, {
  13278. levels: {
  13279. enumerable: true,
  13280. value: []
  13281. },
  13282. objects: {
  13283. get: function () {
  13284. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  13285. return this.levels;
  13286. }
  13287. }
  13288. } );
  13289. };
  13290. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  13291. THREE.LOD.prototype.constructor = THREE.LOD;
  13292. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  13293. if ( distance === undefined ) distance = 0;
  13294. distance = Math.abs( distance );
  13295. var levels = this.levels;
  13296. for ( var l = 0; l < levels.length; l ++ ) {
  13297. if ( distance < levels[ l ].distance ) {
  13298. break;
  13299. }
  13300. }
  13301. levels.splice( l, 0, { distance: distance, object: object } );
  13302. this.add( object );
  13303. };
  13304. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  13305. var levels = this.levels;
  13306. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13307. if ( distance < levels[ i ].distance ) {
  13308. break;
  13309. }
  13310. }
  13311. return levels[ i - 1 ].object;
  13312. };
  13313. THREE.LOD.prototype.raycast = ( function () {
  13314. var matrixPosition = new THREE.Vector3();
  13315. return function raycast( raycaster, intersects ) {
  13316. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13317. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  13318. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  13319. };
  13320. }() );
  13321. THREE.LOD.prototype.update = function () {
  13322. var v1 = new THREE.Vector3();
  13323. var v2 = new THREE.Vector3();
  13324. return function update( camera ) {
  13325. var levels = this.levels;
  13326. if ( levels.length > 1 ) {
  13327. v1.setFromMatrixPosition( camera.matrixWorld );
  13328. v2.setFromMatrixPosition( this.matrixWorld );
  13329. var distance = v1.distanceTo( v2 );
  13330. levels[ 0 ].object.visible = true;
  13331. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13332. if ( distance >= levels[ i ].distance ) {
  13333. levels[ i - 1 ].object.visible = false;
  13334. levels[ i ].object.visible = true;
  13335. } else {
  13336. break;
  13337. }
  13338. }
  13339. for ( ; i < l; i ++ ) {
  13340. levels[ i ].object.visible = false;
  13341. }
  13342. }
  13343. };
  13344. }();
  13345. THREE.LOD.prototype.copy = function ( source ) {
  13346. THREE.Object3D.prototype.copy.call( this, source, false );
  13347. var levels = source.levels;
  13348. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13349. var level = levels[ i ];
  13350. this.addLevel( level.object.clone(), level.distance );
  13351. }
  13352. return this;
  13353. };
  13354. THREE.LOD.prototype.toJSON = function ( meta ) {
  13355. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  13356. data.object.levels = [];
  13357. var levels = this.levels;
  13358. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13359. var level = levels[ i ];
  13360. data.object.levels.push( {
  13361. object: level.object.uuid,
  13362. distance: level.distance
  13363. } );
  13364. }
  13365. return data;
  13366. };
  13367. // File:src/objects/Sprite.js
  13368. /**
  13369. * @author mikael emtinger / http://gomo.se/
  13370. * @author alteredq / http://alteredqualia.com/
  13371. */
  13372. THREE.Sprite = ( function () {
  13373. var indices = new Uint16Array( [ 0, 1, 2, 0, 2, 3 ] );
  13374. var vertices = new Float32Array( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0, - 0.5, 0.5, 0 ] );
  13375. var uvs = new Float32Array( [ 0, 0, 1, 0, 1, 1, 0, 1 ] );
  13376. var geometry = new THREE.BufferGeometry();
  13377. geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  13378. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  13379. geometry.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  13380. return function Sprite( material ) {
  13381. THREE.Object3D.call( this );
  13382. this.type = 'Sprite';
  13383. this.geometry = geometry;
  13384. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  13385. };
  13386. } )();
  13387. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  13388. THREE.Sprite.prototype.constructor = THREE.Sprite;
  13389. THREE.Sprite.prototype.raycast = ( function () {
  13390. var matrixPosition = new THREE.Vector3();
  13391. return function raycast( raycaster, intersects ) {
  13392. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13393. var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition );
  13394. var guessSizeSq = this.scale.x * this.scale.y;
  13395. if ( distanceSq > guessSizeSq ) {
  13396. return;
  13397. }
  13398. intersects.push( {
  13399. distance: Math.sqrt( distanceSq ),
  13400. point: this.position,
  13401. face: null,
  13402. object: this
  13403. } );
  13404. };
  13405. }() );
  13406. THREE.Sprite.prototype.clone = function () {
  13407. return new this.constructor( this.material ).copy( this );
  13408. };
  13409. // Backwards compatibility
  13410. THREE.Particle = THREE.Sprite;
  13411. // File:src/objects/LensFlare.js
  13412. /**
  13413. * @author mikael emtinger / http://gomo.se/
  13414. * @author alteredq / http://alteredqualia.com/
  13415. */
  13416. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  13417. THREE.Object3D.call( this );
  13418. this.lensFlares = [];
  13419. this.positionScreen = new THREE.Vector3();
  13420. this.customUpdateCallback = undefined;
  13421. if ( texture !== undefined ) {
  13422. this.add( texture, size, distance, blending, color );
  13423. }
  13424. };
  13425. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  13426. THREE.LensFlare.prototype.constructor = THREE.LensFlare;
  13427. /*
  13428. * Add: adds another flare
  13429. */
  13430. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  13431. if ( size === undefined ) size = - 1;
  13432. if ( distance === undefined ) distance = 0;
  13433. if ( opacity === undefined ) opacity = 1;
  13434. if ( color === undefined ) color = new THREE.Color( 0xffffff );
  13435. if ( blending === undefined ) blending = THREE.NormalBlending;
  13436. distance = Math.min( distance, Math.max( 0, distance ) );
  13437. this.lensFlares.push( {
  13438. texture: texture, // THREE.Texture
  13439. size: size, // size in pixels (-1 = use texture.width)
  13440. distance: distance, // distance (0-1) from light source (0=at light source)
  13441. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  13442. scale: 1, // scale
  13443. rotation: 0, // rotation
  13444. opacity: opacity, // opacity
  13445. color: color, // color
  13446. blending: blending // blending
  13447. } );
  13448. };
  13449. /*
  13450. * Update lens flares update positions on all flares based on the screen position
  13451. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  13452. */
  13453. THREE.LensFlare.prototype.updateLensFlares = function () {
  13454. var f, fl = this.lensFlares.length;
  13455. var flare;
  13456. var vecX = - this.positionScreen.x * 2;
  13457. var vecY = - this.positionScreen.y * 2;
  13458. for ( f = 0; f < fl; f ++ ) {
  13459. flare = this.lensFlares[ f ];
  13460. flare.x = this.positionScreen.x + vecX * flare.distance;
  13461. flare.y = this.positionScreen.y + vecY * flare.distance;
  13462. flare.wantedRotation = flare.x * Math.PI * 0.25;
  13463. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  13464. }
  13465. };
  13466. THREE.LensFlare.prototype.copy = function ( source ) {
  13467. THREE.Object3D.prototype.copy.call( this, source );
  13468. this.positionScreen.copy( source.positionScreen );
  13469. this.customUpdateCallback = source.customUpdateCallback;
  13470. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  13471. this.lensFlares.push( source.lensFlares[ i ] );
  13472. }
  13473. return this;
  13474. };
  13475. // File:src/scenes/Scene.js
  13476. /**
  13477. * @author mrdoob / http://mrdoob.com/
  13478. */
  13479. THREE.Scene = function () {
  13480. THREE.Object3D.call( this );
  13481. this.type = 'Scene';
  13482. this.fog = null;
  13483. this.overrideMaterial = null;
  13484. this.autoUpdate = true; // checked by the renderer
  13485. };
  13486. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  13487. THREE.Scene.prototype.constructor = THREE.Scene;
  13488. THREE.Scene.prototype.copy = function ( source ) {
  13489. THREE.Object3D.prototype.copy.call( this, source );
  13490. if ( source.fog !== null ) this.fog = source.fog.clone();
  13491. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13492. this.autoUpdate = source.autoUpdate;
  13493. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13494. return this;
  13495. };
  13496. // File:src/scenes/Fog.js
  13497. /**
  13498. * @author mrdoob / http://mrdoob.com/
  13499. * @author alteredq / http://alteredqualia.com/
  13500. */
  13501. THREE.Fog = function ( color, near, far ) {
  13502. this.name = '';
  13503. this.color = new THREE.Color( color );
  13504. this.near = ( near !== undefined ) ? near : 1;
  13505. this.far = ( far !== undefined ) ? far : 1000;
  13506. };
  13507. THREE.Fog.prototype.clone = function () {
  13508. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  13509. };
  13510. // File:src/scenes/FogExp2.js
  13511. /**
  13512. * @author mrdoob / http://mrdoob.com/
  13513. * @author alteredq / http://alteredqualia.com/
  13514. */
  13515. THREE.FogExp2 = function ( color, density ) {
  13516. this.name = '';
  13517. this.color = new THREE.Color( color );
  13518. this.density = ( density !== undefined ) ? density : 0.00025;
  13519. };
  13520. THREE.FogExp2.prototype.clone = function () {
  13521. return new THREE.FogExp2( this.color.getHex(), this.density );
  13522. };
  13523. // File:src/renderers/shaders/ShaderChunk.js
  13524. THREE.ShaderChunk = {};
  13525. // File:src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl
  13526. THREE.ShaderChunk[ 'alphamap_fragment'] = "#ifdef USE_ALPHAMAP\n diffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  13527. // File:src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl
  13528. THREE.ShaderChunk[ 'alphamap_pars_fragment'] = "#ifdef USE_ALPHAMAP\n uniform sampler2D alphaMap;\n#endif\n";
  13529. // File:src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl
  13530. THREE.ShaderChunk[ 'alphatest_fragment'] = "#ifdef ALPHATEST\n if ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  13531. // File:src/renderers/shaders/ShaderChunk/aomap_fragment.glsl
  13532. THREE.ShaderChunk[ 'aomap_fragment'] = "#ifdef USE_AOMAP\n reflectedLight.indirectDiffuse *= ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n#endif\n";
  13533. // File:src/renderers/shaders/ShaderChunk/aomap_pars_fragment.glsl
  13534. THREE.ShaderChunk[ 'aomap_pars_fragment'] = "#ifdef USE_AOMAP\n uniform sampler2D aoMap;\n uniform float aoMapIntensity;\n#endif";
  13535. // File:src/renderers/shaders/ShaderChunk/begin_vertex.glsl
  13536. THREE.ShaderChunk[ 'begin_vertex'] = "\nvec3 transformed = vec3( position );\n";
  13537. // File:src/renderers/shaders/ShaderChunk/beginnormal_vertex.glsl
  13538. THREE.ShaderChunk[ 'beginnormal_vertex'] = "\nvec3 objectNormal = vec3( normal );\n";
  13539. // File:src/renderers/shaders/ShaderChunk/bsdfs.glsl
  13540. THREE.ShaderChunk[ 'bsdfs'] = "float calcLightAttenuation( float lightDistance, float cutoffDistance, float decayExponent ) {\n if ( decayExponent > 0.0 ) {\n return pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n }\n return 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n return diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n float fresnel = exp2( ( -5.55437 * dotLH - 6.98316 ) * dotLH );\n return ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( in float alpha, in float dotNL, in float dotNV ) {\n float a2 = alpha * alpha;\n float gl = dotNL + pow( a2 + ( 1.0 - a2 ) * dotNL * dotNL, 0.5 );\n float gv = dotNV + pow( a2 + ( 1.0 - a2 ) * dotNV * dotNV, 0.5 );\n return 1.0 / ( gl * gv );\n}\nfloat D_GGX( in float alpha, in float dotNH ) {\n float a2 = alpha * alpha;\n float denom = dotNH * dotNH * ( a2 - 1.0 ) + 1.0;\n return a2 / ( denom * denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n \n float alpha = roughness * roughness;\n vec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n float dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n float dotNH = saturate( dot( geometry.normal, halfDir ) );\n float dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n vec3 F = F_Schlick( specularColor, dotLH );\n float G = G_GGX_Smith( alpha, dotNL, dotNV );\n float D = D_GGX( alpha, dotNH );\n return F * ( G * D );\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, vec3 specularColor, float roughness ) {\n float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n return specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n return 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n return ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n vec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n float dotNH = saturate( dot( geometry.normal, halfDir ) );\n float dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n vec3 F = F_Schlick( specularColor, dotLH );\n float G = G_BlinnPhong_Implicit( );\n float D = D_BlinnPhong( shininess, dotNH );\n return F * ( G * D );\n} // validated";
  13541. // File:src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl
  13542. THREE.ShaderChunk[ 'bumpmap_pars_fragment'] = "#ifdef USE_BUMPMAP\n uniform sampler2D bumpMap;\n uniform float bumpScale;\n vec2 dHdxy_fwd() {\n vec2 dSTdx = dFdx( vUv );\n vec2 dSTdy = dFdy( vUv );\n float Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n return vec2( dBx, dBy );\n }\n vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n vec3 vSigmaX = dFdx( surf_pos );\n vec3 vSigmaY = dFdy( surf_pos );\n vec3 vN = surf_norm;\n vec3 R1 = cross( vSigmaY, vN );\n vec3 R2 = cross( vN, vSigmaX );\n float fDet = dot( vSigmaX, R1 );\n vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n return normalize( abs( fDet ) * surf_norm - vGrad );\n }\n#endif\n";
  13543. // File:src/renderers/shaders/ShaderChunk/color_fragment.glsl
  13544. THREE.ShaderChunk[ 'color_fragment'] = "#ifdef USE_COLOR\n diffuseColor.rgb *= vColor;\n#endif";
  13545. // File:src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl
  13546. THREE.ShaderChunk[ 'color_pars_fragment'] = "#ifdef USE_COLOR\n varying vec3 vColor;\n#endif\n";
  13547. // File:src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl
  13548. THREE.ShaderChunk[ 'color_pars_vertex'] = "#ifdef USE_COLOR\n varying vec3 vColor;\n#endif";
  13549. // File:src/renderers/shaders/ShaderChunk/color_vertex.glsl
  13550. THREE.ShaderChunk[ 'color_vertex'] = "#ifdef USE_COLOR\n vColor.xyz = color.xyz;\n#endif";
  13551. // File:src/renderers/shaders/ShaderChunk/common.glsl
  13552. THREE.ShaderChunk[ 'common'] = "#define PI 3.14159\n#define PI2 6.28318\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nstruct IncidentLight {\n vec3 color;\n vec3 direction;\n};\nstruct ReflectedLight {\n vec3 directDiffuse;\n vec3 directSpecular;\n vec3 indirectDiffuse;\n vec3 indirectSpecular;\n};\nstruct GeometricContext {\n vec3 position;\n vec3 normal;\n vec3 viewDir;\n};\nvec3 transformDirection( in vec3 normal, in mat4 matrix ) {\n return normalize( ( matrix * vec4( normal, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 normal, in mat4 matrix ) {\n return normalize( ( vec4( normal, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n float distance = dot( planeNormal, point - pointOnPlane );\n return - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n return sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n return lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nvec3 inputToLinear( in vec3 a ) {\n #ifdef GAMMA_INPUT\n return pow( a, vec3( float( GAMMA_FACTOR ) ) );\n #else\n return a;\n #endif\n}\nvec3 linearToOutput( in vec3 a ) {\n #ifdef GAMMA_OUTPUT\n return pow( a, vec3( 1.0 / float( GAMMA_FACTOR ) ) );\n #else\n return a;\n #endif\n}\n";
  13553. // File:src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl
  13554. THREE.ShaderChunk[ 'defaultnormal_vertex'] = "#ifdef FLIP_SIDED\n objectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  13555. // File:src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl
  13556. THREE.ShaderChunk[ 'displacementmap_vertex'] = "#ifdef USE_DISPLACEMENTMAP\n transformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  13557. // File:src/renderers/shaders/ShaderChunk/displacementmap_pars_vertex.glsl
  13558. THREE.ShaderChunk[ 'displacementmap_pars_vertex'] = "#ifdef USE_DISPLACEMENTMAP\n uniform sampler2D displacementMap;\n uniform float displacementScale;\n uniform float displacementBias;\n#endif\n";
  13559. // File:src/renderers/shaders/ShaderChunk/emissivemap_fragment.glsl
  13560. THREE.ShaderChunk[ 'emissivemap_fragment'] = "#ifdef USE_EMISSIVEMAP\n vec4 emissiveColor = texture2D( emissiveMap, vUv );\n emissiveColor.rgb = inputToLinear( emissiveColor.rgb );\n totalEmissiveLight *= emissiveColor.rgb;\n#endif\n";
  13561. // File:src/renderers/shaders/ShaderChunk/emissivemap_pars_fragment.glsl
  13562. THREE.ShaderChunk[ 'emissivemap_pars_fragment'] = "#ifdef USE_EMISSIVEMAP\n uniform sampler2D emissiveMap;\n#endif\n";
  13563. // File:src/renderers/shaders/ShaderChunk/envmap_fragment.glsl
  13564. THREE.ShaderChunk[ 'envmap_fragment'] = "#ifdef USE_ENVMAP\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n #ifdef ENVMAP_MODE_REFLECTION\n vec3 reflectVec = reflect( cameraToVertex, worldNormal );\n #else\n vec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n #endif\n #else\n vec3 reflectVec = vReflect;\n #endif\n #ifdef DOUBLE_SIDED\n float flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n #else\n float flipNormal = 1.0;\n #endif\n #ifdef ENVMAP_TYPE_CUBE\n vec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n #elif defined( ENVMAP_TYPE_EQUIREC )\n vec2 sampleUV;\n sampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n sampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n vec4 envColor = texture2D( envMap, sampleUV );\n #elif defined( ENVMAP_TYPE_SPHERE )\n vec3 reflectView = flipNormal * normalize((viewMatrix * vec4( reflectVec, 0.0 )).xyz + vec3(0.0,0.0,1.0));\n vec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n #endif\n envColor.xyz = inputToLinear( envColor.xyz );\n #ifdef ENVMAP_BLENDING_MULTIPLY\n outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n #elif defined( ENVMAP_BLENDING_MIX )\n outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n #elif defined( ENVMAP_BLENDING_ADD )\n outgoingLight += envColor.xyz * specularStrength * reflectivity;\n #endif\n#endif\n";
  13565. // File:src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl
  13566. THREE.ShaderChunk[ 'envmap_pars_fragment'] = "#ifdef USE_ENVMAP\n uniform float reflectivity;\n #ifdef ENVMAP_TYPE_CUBE\n uniform samplerCube envMap;\n #else\n uniform sampler2D envMap;\n #endif\n uniform float flipEnvMap;\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n uniform float refractionRatio;\n #else\n varying vec3 vReflect;\n #endif\n#endif\n";
  13567. // File:src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl
  13568. THREE.ShaderChunk[ 'envmap_pars_vertex'] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG ) && ! defined( PHYSICAL )\n varying vec3 vReflect;\n uniform float refractionRatio;\n#endif\n";
  13569. // File:src/renderers/shaders/ShaderChunk/envmap_vertex.glsl
  13570. THREE.ShaderChunk[ 'envmap_vertex'] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG ) && ! defined( PHYSICAL )\n vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n #ifdef ENVMAP_MODE_REFLECTION\n vReflect = reflect( cameraToVertex, worldNormal );\n #else\n vReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n #endif\n#endif\n";
  13571. // File:src/renderers/shaders/ShaderChunk/fog_fragment.glsl
  13572. THREE.ShaderChunk[ 'fog_fragment'] = "#ifdef USE_FOG\n #ifdef USE_LOGDEPTHBUF_EXT\n float depth = gl_FragDepthEXT / gl_FragCoord.w;\n #else\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n #endif\n #ifdef FOG_EXP2\n float fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n #else\n float fogFactor = smoothstep( fogNear, fogFar, depth );\n #endif\n \n outgoingLight = mix( outgoingLight, fogColor, fogFactor );\n#endif";
  13573. // File:src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl
  13574. THREE.ShaderChunk[ 'fog_pars_fragment'] = "#ifdef USE_FOG\n uniform vec3 fogColor;\n #ifdef FOG_EXP2\n uniform float fogDensity;\n #else\n uniform float fogNear;\n uniform float fogFar;\n #endif\n#endif";
  13575. // File:src/renderers/shaders/ShaderChunk/lights_pars.glsl
  13576. THREE.ShaderChunk[ 'lights_pars'] = "uniform vec3 ambientLightColor;\n#if MAX_DIR_LIGHTS > 0\n struct DirectionalLight {\n vec3 direction;\n vec3 color;\n };\n uniform DirectionalLight directionalLights[ MAX_DIR_LIGHTS ];\n IncidentLight getDirectionalDirectLight( const in DirectionalLight directionalLight, const in GeometricContext geometry ) { \n IncidentLight directLight;\n \n directLight.color = directionalLight.color;\n directLight.direction = directionalLight.direction; \n return directLight;\n }\n#endif\n#if MAX_POINT_LIGHTS > 0\n struct PointLight {\n vec3 position;\n vec3 color;\n float distance;\n float decay;\n };\n uniform PointLight pointLights[ MAX_POINT_LIGHTS ];\n IncidentLight getPointDirectLight( const in PointLight pointLight, const in GeometricContext geometry ) { \n \n IncidentLight directLight;\n \n vec3 lVector = pointLight.position - geometry.position; \n directLight.direction = normalize( lVector ); \n \n directLight.color = pointLight.color; \n directLight.color *= calcLightAttenuation( length( lVector ), pointLight.distance, pointLight.decay ); \n \n return directLight;\n }\n#endif\n#if MAX_SPOT_LIGHTS > 0\n struct SpotLight {\n vec3 position;\n vec3 direction;\n vec3 color;\n float distance;\n float decay;\n float angleCos;\n float exponent;\n };\n uniform SpotLight spotLights[ MAX_SPOT_LIGHTS ];\n IncidentLight getSpotDirectLight( const in SpotLight spotLight, const in GeometricContext geometry ) {\n \n IncidentLight directLight;\n vec3 lVector = spotLight.position - geometry.position;\n directLight.direction = normalize( lVector );\n \n float spotEffect = dot( spotLight.direction, directLight.direction );\n spotEffect = saturate( pow( saturate( spotEffect ), spotLight.exponent ) );\n \n directLight.color = spotLight.color;\n directLight.color *= ( spotEffect * calcLightAttenuation( length( lVector ), spotLight.distance, spotLight.decay ) );\n return directLight;\n }\n#endif\n#if MAX_HEMI_LIGHTS > 0\n struct HemisphereLight {\n vec3 direction;\n vec3 skyColor;\n vec3 groundColor;\n };\n uniform HemisphereLight hemisphereLights[ MAX_HEMI_LIGHTS ];\n vec3 getHemisphereIndirectLightColor( const in HemisphereLight hemiLight, const in GeometricContext geometry ) { \n \n float dotNL = dot( geometry.normal, hemiLight.direction );\n float hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n return mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n }\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n vec3 getSpecularLightProbeIndirectLightColor( const in GeometricContext geometry, const in float lodLevel ) { \n \n #ifdef ENVMAP_MODE_REFLECTION\n vec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n #else\n vec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n #endif\n #ifdef DOUBLE_SIDED\n float flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n #else\n float flipNormal = 1.0;\n #endif\n reflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n #ifdef ENVMAP_TYPE_CUBE\n #if defined( TEXTURE_CUBE_LOD_EXT ) \n vec4 envMapColor = textureCubeLodEXT( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ), lodLevel );\n #else\n vec4 envMapColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n #endif\n #elif defined( ENVMAP_TYPE_EQUIREC )\n vec2 sampleUV;\n sampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n sampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n vec4 envMapColor = texture2D( envMap, sampleUV );\n #elif defined( ENVMAP_TYPE_SPHERE )\n vec3 reflectView = flipNormal * normalize((viewMatrix * vec4( reflectVec, 0.0 )).xyz + vec3(0.0,0.0,1.0));\n vec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n #endif\n envMapColor.rgb = inputToLinear( envMapColor.rgb );\n return envMapColor.rgb * reflectivity;\n }\n#endif\n";
  13577. // File:src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl
  13578. THREE.ShaderChunk[ 'lightmap_pars_fragment'] = "#ifdef USE_LIGHTMAP\n uniform sampler2D lightMap;\n uniform float lightMapIntensity;\n#endif";
  13579. // File:src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl
  13580. THREE.ShaderChunk[ 'lights_lambert_vertex'] = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry = GeometricContext( mvPosition.xyz, normalize( transformedNormal ), normalize( -mvPosition.xyz ) );\nGeometricContext backGeometry = GeometricContext( geometry.position, -geometry.normal, geometry.viewDir );\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n vLightBack = vec3( 0.0 );\n#endif\n#if MAX_POINT_LIGHTS > 0\n for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {\n IncidentLight directLight = getPointDirectLight( pointLights[ i ], geometry );\n float dotNL = dot( geometry.normal, directLight.direction );\n vec3 directLightColor_Diffuse = directLight.color * BRDF_Diffuse_Lambert( diffuse );\n vLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n #ifdef DOUBLE_SIDED\n vLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n #endif\n }\n#endif\n#if MAX_SPOT_LIGHTS > 0\n for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {\n IncidentLight directLight = getSpotDirectLight( spotLights[ i ], geometry );\n float dotNL = dot( geometry.normal, directLight.direction );\n vec3 directLightColor_Diffuse = directLight.color * BRDF_Diffuse_Lambert( diffuse );\n vLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n #ifdef DOUBLE_SIDED\n vLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n #endif\n }\n#endif\n#if MAX_DIR_LIGHTS > 0\n for ( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {\n IncidentLight directLight = getDirectionalDirectLight( directionalLights[ i ], geometry );\n float dotNL = dot( geometry.normal, directLight.direction );\n vec3 directLightColor_Diffuse = directLight.color * BRDF_Diffuse_Lambert( diffuse );\n vLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n #ifdef DOUBLE_SIDED\n vLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n #endif\n }\n#endif\n {\n vLightFront += ambientLightColor;\n #ifdef DOUBLE_SIDED\n vLightBack += ambientLightColor;\n #endif\n #if MAX_HEMI_LIGHTS > 0\n for ( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {\n vLightFront += getHemisphereIndirectLightColor( hemisphereLights[ i ], geometry );\n #ifdef DOUBLE_SIDED\n vLightBack += getHemisphereIndirectLightColor( hemisphereLights[ i ], backGeometry );\n #endif\n }\n #endif\n }\n";
  13581. // File:src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl
  13582. THREE.ShaderChunk[ 'lights_phong_fragment'] = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n#ifdef METAL\n material.diffuseColor = vec3( 0.0 );\n#endif\n";
  13583. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl
  13584. THREE.ShaderChunk[ 'lights_phong_pars_fragment'] = "#ifdef USE_ENVMAP\n varying vec3 vWorldPosition;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n vec3 diffuseColor;\n vec3 specularColor;\n float specularShininess;\n float specularStrength;\n};\nvoid BlinnPhongMaterial_RE_DirectLight( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n reflectedLight.directDiffuse += dotNL * directLight.color * BRDF_Diffuse_Lambert( material.diffuseColor );\n reflectedLight.directSpecular += dotNL * directLight.color * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\n#define Material_RE_DirectLight BlinnPhongMaterial_RE_DirectLight\nvoid BlinnPhongMaterial_RE_IndirectDiffuseLight( const in vec3 indirectDiffuseColor, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += indirectDiffuseColor * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define Material_RE_IndirectDiffuseLight BlinnPhongMaterial_RE_IndirectDiffuseLight\n#define Material_LightProbeLOD( material ) (0)\n";
  13585. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_vertex.glsl
  13586. THREE.ShaderChunk[ 'lights_phong_pars_vertex'] = "#ifdef USE_ENVMAP\n varying vec3 vWorldPosition;\n#endif\n#if MAX_POINT_LIGHTS > 0\n uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];\n#endif\n";
  13587. // File:src/renderers/shaders/ShaderChunk/lights_phong_vertex.glsl
  13588. THREE.ShaderChunk[ 'lights_phong_vertex'] = "#ifdef USE_ENVMAP\n vWorldPosition = worldPosition.xyz;\n#endif\n";
  13589. // File:src/renderers/shaders/ShaderChunk/lights_physical_fragment.glsl
  13590. THREE.ShaderChunk[ 'lights_physical_fragment'] = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = roughnessFactor * 0.5 + 0.5;material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n";
  13591. // File:src/renderers/shaders/ShaderChunk/lights_physical_pars_fragment.glsl
  13592. THREE.ShaderChunk[ 'lights_physical_pars_fragment'] = "struct PhysicalMaterial {\n vec3 diffuseColor;\n float specularRoughness;\n vec3 specularColor;\n float clearCoatWeight;\n float clearCoatRoughness;\n};\nvoid PhysicalMaterial_RE_DirectLight( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n reflectedLight.directDiffuse += dotNL * directLight.color * BRDF_Diffuse_Lambert( material.diffuseColor );\n reflectedLight.directSpecular += dotNL * directLight.color * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n \n}\n#define Material_RE_DirectLight PhysicalMaterial_RE_DirectLight\nvoid PhysicalMaterial_RE_DiffuseIndirectLight( const in vec3 indirectDiffuseColor, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += indirectDiffuseColor * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define Material_RE_IndirectDiffuseLight PhysicalMaterial_RE_DiffuseIndirectLight\nvoid PhysicalMaterial_RE_SpecularIndirectLight( const in vec3 indirectSpecularColor, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectSpecular += indirectSpecularColor * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n}\n#define Material_LightProbeLOD( material ) (pow( ( material.specularRoughness - 0.5 ) * 2.0, 0.5 ) * 7.0)\n#define Material_RE_IndirectSpecularLight PhysicalMaterial_RE_SpecularIndirectLight\n";
  13593. // File:src/renderers/shaders/ShaderChunk/lights_template.glsl
  13594. THREE.ShaderChunk[ 'lights_template'] = "\nGeometricContext geometry = GeometricContext( -vViewPosition, normalize( normal ), normalize(vViewPosition ) );\n#if ( MAX_POINT_LIGHTS > 0 ) && defined( Material_RE_DirectLight )\n for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {\n IncidentLight directLight = getPointDirectLight( pointLights[ i ], geometry );\n Material_RE_DirectLight( directLight, geometry, material, reflectedLight );\n }\n#endif\n#if ( MAX_SPOT_LIGHTS > 0 ) && defined( Material_RE_DirectLight )\n for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {\n IncidentLight directLight = getSpotDirectLight( spotLights[ i ], geometry );\n Material_RE_DirectLight( directLight, geometry, material, reflectedLight );\n }\n#endif\n#if ( MAX_DIR_LIGHTS > 0 ) && defined( Material_RE_DirectLight )\n for ( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {\n IncidentLight directLight = getDirectionalDirectLight( directionalLights[ i ], geometry );\n Material_RE_DirectLight( directLight, geometry, material, reflectedLight );\n \n }\n#endif\n#if defined( Material_RE_IndirectDiffuseLight )\n {\n \n vec3 indirectDiffuseColor = ambientLightColor;\n#ifdef USE_LIGHTMAP\n indirectDiffuseColor += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n#if ( MAX_HEMI_LIGHTS > 0 )\n for ( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {\n indirectDiffuseColor += getHemisphereIndirectLightColor( hemisphereLights[ i ], geometry );\n }\n#endif\n Material_RE_IndirectDiffuseLight( indirectDiffuseColor, geometry, material, reflectedLight );\n }\n#endif\n#if defined( USE_ENVMAP ) && defined( Material_RE_IndirectSpecularLight )\n {\n vec3 indirectSpecularColor = getSpecularLightProbeIndirectLightColor( geometry, Material_LightProbeLOD( material ) );\n Material_RE_IndirectSpecularLight( indirectSpecularColor, geometry, material, reflectedLight );\n }\n#endif";
  13595. // File:src/renderers/shaders/ShaderChunk/linear_to_gamma_fragment.glsl
  13596. THREE.ShaderChunk[ 'linear_to_gamma_fragment'] = "\n outgoingLight = linearToOutput( outgoingLight );\n";
  13597. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl
  13598. THREE.ShaderChunk[ 'logdepthbuf_fragment'] = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  13599. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl
  13600. THREE.ShaderChunk[ 'logdepthbuf_pars_fragment'] = "#ifdef USE_LOGDEPTHBUF\n uniform float logDepthBufFC;\n #ifdef USE_LOGDEPTHBUF_EXT\n varying float vFragDepth;\n #endif\n#endif\n";
  13601. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl
  13602. THREE.ShaderChunk[ 'logdepthbuf_pars_vertex'] = "#ifdef USE_LOGDEPTHBUF\n #ifdef USE_LOGDEPTHBUF_EXT\n varying float vFragDepth;\n #endif\n uniform float logDepthBufFC;\n#endif";
  13603. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl
  13604. THREE.ShaderChunk[ 'logdepthbuf_vertex'] = "#ifdef USE_LOGDEPTHBUF\n gl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n #ifdef USE_LOGDEPTHBUF_EXT\n vFragDepth = 1.0 + gl_Position.w;\n #else\n gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n #endif\n#endif\n";
  13605. // File:src/renderers/shaders/ShaderChunk/map_fragment.glsl
  13606. THREE.ShaderChunk[ 'map_fragment'] = "#ifdef USE_MAP\n vec4 texelColor = texture2D( map, vUv );\n texelColor.xyz = inputToLinear( texelColor.xyz );\n diffuseColor *= texelColor;\n#endif\n";
  13607. // File:src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl
  13608. THREE.ShaderChunk[ 'map_pars_fragment'] = "#ifdef USE_MAP\n uniform sampler2D map;\n#endif";
  13609. // File:src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl
  13610. THREE.ShaderChunk[ 'map_particle_fragment'] = "#ifdef USE_MAP\n diffuseColor *= texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n#endif\n";
  13611. // File:src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl
  13612. THREE.ShaderChunk[ 'map_particle_pars_fragment'] = "#ifdef USE_MAP\n uniform vec4 offsetRepeat;\n uniform sampler2D map;\n#endif\n";
  13613. // File:src/renderers/shaders/ShaderChunk/metalnessmap_fragment.glsl
  13614. THREE.ShaderChunk[ 'metalnessmap_fragment'] = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n vec4 texelMetalness = texture2D( metalnessMap, vUv );\n metalnessFactor = texelMetalness.r;\n#endif\n";
  13615. // File:src/renderers/shaders/ShaderChunk/metalnessmap_pars_fragment.glsl
  13616. THREE.ShaderChunk[ 'metalnessmap_pars_fragment'] = "#ifdef USE_METALNESSMAP\n uniform sampler2D metalnessMap;\n#endif";
  13617. // File:src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl
  13618. THREE.ShaderChunk[ 'morphnormal_vertex'] = "#ifdef USE_MORPHNORMALS\n objectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n objectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n objectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n objectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n";
  13619. // File:src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl
  13620. THREE.ShaderChunk[ 'morphtarget_pars_vertex'] = "#ifdef USE_MORPHTARGETS\n #ifndef USE_MORPHNORMALS\n uniform float morphTargetInfluences[ 8 ];\n #else\n uniform float morphTargetInfluences[ 4 ];\n #endif\n#endif";
  13621. // File:src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl
  13622. THREE.ShaderChunk[ 'morphtarget_vertex'] = "#ifdef USE_MORPHTARGETS\n transformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n transformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n transformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n transformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n #ifndef USE_MORPHNORMALS\n transformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n transformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n transformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n transformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n #endif\n#endif\n";
  13623. // File:src/renderers/shaders/ShaderChunk/normal_phong_fragment.glsl
  13624. THREE.ShaderChunk[ 'normal_phong_fragment'] = "#ifndef FLAT_SHADED\n vec3 normal = normalize( vNormal );\n #ifdef DOUBLE_SIDED\n normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );\n #endif\n#else\n vec3 fdx = dFdx( vViewPosition );\n vec3 fdy = dFdy( vViewPosition );\n vec3 normal = normalize( cross( fdx, fdy ) );\n#endif\n#ifdef USE_NORMALMAP\n normal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n";
  13625. // File:src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl
  13626. THREE.ShaderChunk[ 'normalmap_pars_fragment'] = "#ifdef USE_NORMALMAP\n uniform sampler2D normalMap;\n uniform vec2 normalScale;\n vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n vec3 q0 = dFdx( eye_pos.xyz );\n vec3 q1 = dFdy( eye_pos.xyz );\n vec2 st0 = dFdx( vUv.st );\n vec2 st1 = dFdy( vUv.st );\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normalize( surf_norm );\n vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n mapN.xy = normalScale * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n }\n#endif\n";
  13627. // File:src/renderers/shaders/ShaderChunk/project_vertex.glsl
  13628. THREE.ShaderChunk[ 'project_vertex'] = "#ifdef USE_SKINNING\n vec4 mvPosition = modelViewMatrix * skinned;\n#else\n vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n#endif\ngl_Position = projectionMatrix * mvPosition;\n";
  13629. // File:src/renderers/shaders/ShaderChunk/roughnessmap_fragment.glsl
  13630. THREE.ShaderChunk[ 'roughnessmap_fragment'] = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n vec4 texelRoughness = texture2D( roughnessMap, vUv );\n roughnessFactor *= texelRoughness.r;\n#endif\n";
  13631. // File:src/renderers/shaders/ShaderChunk/roughnessmap_pars_fragment.glsl
  13632. THREE.ShaderChunk[ 'roughnessmap_pars_fragment'] = "#ifdef USE_ROUGHNESSMAP\n uniform sampler2D roughnessMap;\n#endif";
  13633. // File:src/renderers/shaders/ShaderChunk/shadowmap_fragment.glsl
  13634. THREE.ShaderChunk[ 'shadowmap_fragment'] = "#ifdef USE_SHADOWMAP\n for ( int i = 0; i < MAX_SHADOWS; i ++ ) {\n float texelSizeY = 1.0 / shadowMapSize[ i ].y;\n float shadow = 0.0;\n#if defined( POINT_LIGHT_SHADOWS )\n bool isPointLight = shadowDarkness[ i ] < 0.0;\n if ( isPointLight ) {\n float realShadowDarkness = abs( shadowDarkness[ i ] );\n vec3 lightToPosition = vShadowCoord[ i ].xyz;\n #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n vec3 bd3D = normalize( lightToPosition );\n float dp = length( lightToPosition );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D, texelSizeY ) ), shadowBias[ i ], shadow );\n #if defined( SHADOWMAP_TYPE_PCF )\n const float Dr = 1.25;\n #elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n const float Dr = 2.25;\n #endif\n float os = Dr * 2.0 * texelSizeY;\n const vec3 Gsd = vec3( - 1, 0, 1 );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zzz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zxz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xxz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xzz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zzx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zxx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xxx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xzx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zzy * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zxy * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xxy * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xzy * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zyz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xyz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zyx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xyx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.yzz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.yxz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.yxx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.yzx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n shadow *= realShadowDarkness * ( 1.0 / 21.0 );\n #else\n vec3 bd3D = normalize( lightToPosition );\n float dp = length( lightToPosition );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D, texelSizeY ) ), shadowBias[ i ], shadow );\n shadow *= realShadowDarkness;\n #endif\n } else {\n#endif\n float texelSizeX = 1.0 / shadowMapSize[ i ].x;\n vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;\n bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n bool inFrustum = all( inFrustumVec );\n bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n bool frustumTest = all( frustumTestVec );\n if ( frustumTest ) {\n #if defined( SHADOWMAP_TYPE_PCF )\n shadowCoord.z += shadowBias[ i ];\n const float ShadowDelta = 1.0 / 9.0;\n float xPixelOffset = texelSizeX;\n float yPixelOffset = texelSizeY;\n float dx0 = - 1.25 * xPixelOffset;\n float dy0 = - 1.25 * yPixelOffset;\n float dx1 = 1.25 * xPixelOffset;\n float dy1 = 1.25 * yPixelOffset;\n float fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n shadow *= shadowDarkness[ i ];\n #elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n shadowCoord.z += shadowBias[ i ];\n float xPixelOffset = texelSizeX;\n float yPixelOffset = texelSizeY;\n float dx0 = - 1.0 * xPixelOffset;\n float dy0 = - 1.0 * yPixelOffset;\n float dx1 = 1.0 * xPixelOffset;\n float dy1 = 1.0 * yPixelOffset;\n mat3 shadowKernel;\n mat3 depthKernel;\n depthKernel[ 0 ][ 0 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n depthKernel[ 0 ][ 1 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n depthKernel[ 0 ][ 2 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n depthKernel[ 1 ][ 0 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n depthKernel[ 1 ][ 1 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n depthKernel[ 1 ][ 2 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n depthKernel[ 2 ][ 0 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n depthKernel[ 2 ][ 1 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n depthKernel[ 2 ][ 2 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n vec3 shadowZ = vec3( shadowCoord.z );\n shadowKernel[ 0 ] = vec3( lessThan( depthKernel[ 0 ], shadowZ ) );\n shadowKernel[ 0 ] *= vec3( 0.25 );\n shadowKernel[ 1 ] = vec3( lessThan( depthKernel[ 1 ], shadowZ ) );\n shadowKernel[ 1 ] *= vec3( 0.25 );\n shadowKernel[ 2 ] = vec3( lessThan( depthKernel[ 2 ], shadowZ ) );\n shadowKernel[ 2 ] *= vec3( 0.25 );\n vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[ i ].xy );\n shadowKernel[ 0 ] = mix( shadowKernel[ 1 ], shadowKernel[ 0 ], fractionalCoord.x );\n shadowKernel[ 1 ] = mix( shadowKernel[ 2 ], shadowKernel[ 1 ], fractionalCoord.x );\n vec4 shadowValues;\n shadowValues.x = mix( shadowKernel[ 0 ][ 1 ], shadowKernel[ 0 ][ 0 ], fractionalCoord.y );\n shadowValues.y = mix( shadowKernel[ 0 ][ 2 ], shadowKernel[ 0 ][ 1 ], fractionalCoord.y );\n shadowValues.z = mix( shadowKernel[ 1 ][ 1 ], shadowKernel[ 1 ][ 0 ], fractionalCoord.y );\n shadowValues.w = mix( shadowKernel[ 1 ][ 2 ], shadowKernel[ 1 ][ 1 ], fractionalCoord.y );\n shadow = dot( shadowValues, vec4( 1.0 ) ) * shadowDarkness[ i ];\n #else\n shadowCoord.z += shadowBias[ i ];\n vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );\n float fDepth = unpackDepth( rgbaDepth );\n if ( fDepth < shadowCoord.z )\n shadow = shadowDarkness[ i ];\n #endif\n }\n#ifdef SHADOWMAP_DEBUG\n if ( inFrustum ) {\n if ( i == 0 ) {\n outgoingLight *= vec3( 1.0, 0.5, 0.0 );\n } else if ( i == 1 ) {\n outgoingLight *= vec3( 0.0, 1.0, 0.8 );\n } else {\n outgoingLight *= vec3( 0.0, 0.5, 1.0 );\n }\n }\n#endif\n#if defined( POINT_LIGHT_SHADOWS )\n }\n#endif\n shadowMask = shadowMask * vec3( 1.0 - shadow );\n }\n#endif\n";
  13635. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl
  13636. THREE.ShaderChunk[ 'shadowmap_pars_fragment'] = "#ifdef USE_SHADOWMAP\n uniform sampler2D shadowMap[ MAX_SHADOWS ];\n uniform vec2 shadowMapSize[ MAX_SHADOWS ];\n uniform float shadowDarkness[ MAX_SHADOWS ];\n uniform float shadowBias[ MAX_SHADOWS ];\n varying vec4 vShadowCoord[ MAX_SHADOWS ];\n float unpackDepth( const in vec4 rgba_depth ) {\n const vec4 bit_shift = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );\n float depth = dot( rgba_depth, bit_shift );\n return depth;\n }\n #if defined(POINT_LIGHT_SHADOWS)\n void adjustShadowValue1K( const float testDepth, const vec4 textureData, const float bias, inout float shadowValue ) {\n const vec4 bitSh = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );\n if ( testDepth >= dot( textureData, bitSh ) * 1000.0 + bias )\n shadowValue += 1.0;\n }\n vec2 cubeToUV( vec3 v, float texelSizeY ) {\n vec3 absV = abs( v );\n float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n absV *= scaleToCube;\n v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n vec2 planar = v.xy;\n float almostATexel = 1.5 * texelSizeY;\n float almostOne = 1.0 - almostATexel;\n if ( absV.z >= almostOne ) {\n if ( v.z > 0.0 )\n planar.x = 4.0 - v.x;\n } else if ( absV.x >= almostOne ) {\n float signX = sign( v.x );\n planar.x = v.z * signX + 2.0 * signX;\n } else if ( absV.y >= almostOne ) {\n float signY = sign( v.y );\n planar.x = v.x + 2.0 * signY + 2.0;\n planar.y = v.z * signY - 2.0;\n }\n return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n }\n #endif\n#endif\n";
  13637. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl
  13638. THREE.ShaderChunk[ 'shadowmap_pars_vertex'] = "#ifdef USE_SHADOWMAP\n uniform float shadowDarkness[ MAX_SHADOWS ];\n uniform mat4 shadowMatrix[ MAX_SHADOWS ];\n varying vec4 vShadowCoord[ MAX_SHADOWS ];\n#endif";
  13639. // File:src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl
  13640. THREE.ShaderChunk[ 'shadowmap_vertex'] = "#ifdef USE_SHADOWMAP\n for ( int i = 0; i < MAX_SHADOWS; i ++ ) {\n vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;\n }\n#endif";
  13641. // File:src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl
  13642. THREE.ShaderChunk[ 'skinbase_vertex'] = "#ifdef USE_SKINNING\n mat4 boneMatX = getBoneMatrix( skinIndex.x );\n mat4 boneMatY = getBoneMatrix( skinIndex.y );\n mat4 boneMatZ = getBoneMatrix( skinIndex.z );\n mat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
  13643. // File:src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl
  13644. THREE.ShaderChunk[ 'skinning_pars_vertex'] = "#ifdef USE_SKINNING\n uniform mat4 bindMatrix;\n uniform mat4 bindMatrixInverse;\n #ifdef BONE_TEXTURE\n uniform sampler2D boneTexture;\n uniform int boneTextureWidth;\n uniform int boneTextureHeight;\n mat4 getBoneMatrix( const in float i ) {\n float j = i * 4.0;\n float x = mod( j, float( boneTextureWidth ) );\n float y = floor( j / float( boneTextureWidth ) );\n float dx = 1.0 / float( boneTextureWidth );\n float dy = 1.0 / float( boneTextureHeight );\n y = dy * ( y + 0.5 );\n vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n mat4 bone = mat4( v1, v2, v3, v4 );\n return bone;\n }\n #else\n uniform mat4 boneGlobalMatrices[ MAX_BONES ];\n mat4 getBoneMatrix( const in float i ) {\n mat4 bone = boneGlobalMatrices[ int(i) ];\n return bone;\n }\n #endif\n#endif\n";
  13645. // File:src/renderers/shaders/ShaderChunk/skinning_vertex.glsl
  13646. THREE.ShaderChunk[ 'skinning_vertex'] = "#ifdef USE_SKINNING\n vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n vec4 skinned = vec4( 0.0 );\n skinned += boneMatX * skinVertex * skinWeight.x;\n skinned += boneMatY * skinVertex * skinWeight.y;\n skinned += boneMatZ * skinVertex * skinWeight.z;\n skinned += boneMatW * skinVertex * skinWeight.w;\n skinned = bindMatrixInverse * skinned;\n#endif\n";
  13647. // File:src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl
  13648. THREE.ShaderChunk[ 'skinnormal_vertex'] = "#ifdef USE_SKINNING\n mat4 skinMatrix = mat4( 0.0 );\n skinMatrix += skinWeight.x * boneMatX;\n skinMatrix += skinWeight.y * boneMatY;\n skinMatrix += skinWeight.z * boneMatZ;\n skinMatrix += skinWeight.w * boneMatW;\n skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n";
  13649. // File:src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl
  13650. THREE.ShaderChunk[ 'specularmap_fragment'] = "float specularStrength;\n#ifdef USE_SPECULARMAP\n vec4 texelSpecular = texture2D( specularMap, vUv );\n specularStrength = texelSpecular.r;\n#else\n specularStrength = 1.0;\n#endif";
  13651. // File:src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl
  13652. THREE.ShaderChunk[ 'specularmap_pars_fragment'] = "#ifdef USE_SPECULARMAP\n uniform sampler2D specularMap;\n#endif";
  13653. // File:src/renderers/shaders/ShaderChunk/uv2_pars_fragment.glsl
  13654. THREE.ShaderChunk[ 'uv2_pars_fragment'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n varying vec2 vUv2;\n#endif";
  13655. // File:src/renderers/shaders/ShaderChunk/uv2_pars_vertex.glsl
  13656. THREE.ShaderChunk[ 'uv2_pars_vertex'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n attribute vec2 uv2;\n varying vec2 vUv2;\n#endif";
  13657. // File:src/renderers/shaders/ShaderChunk/uv2_vertex.glsl
  13658. THREE.ShaderChunk[ 'uv2_vertex'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n vUv2 = uv2;\n#endif";
  13659. // File:src/renderers/shaders/ShaderChunk/uv_pars_fragment.glsl
  13660. THREE.ShaderChunk[ '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_REFLECTIVITYMAP ) || defined( USE_METALNESSMAP )\n varying vec2 vUv;\n#endif";
  13661. // File:src/renderers/shaders/ShaderChunk/uv_pars_vertex.glsl
  13662. THREE.ShaderChunk[ '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_REFLECTIVITYMAP ) || defined( USE_METALNESSMAP )\n varying vec2 vUv;\n uniform vec4 offsetRepeat;\n#endif\n";
  13663. // File:src/renderers/shaders/ShaderChunk/uv_vertex.glsl
  13664. THREE.ShaderChunk[ '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_REFLECTIVITYMAP ) || defined( USE_METALNESSMAP )\n vUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif";
  13665. // File:src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl
  13666. THREE.ShaderChunk[ 'worldpos_vertex'] = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n #ifdef USE_SKINNING\n vec4 worldPosition = modelMatrix * skinned;\n #else\n vec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n #endif\n#endif\n";
  13667. // File:src/renderers/shaders/UniformsUtils.js
  13668. /**
  13669. * Uniform Utilities
  13670. */
  13671. THREE.UniformsUtils = {
  13672. merge: function ( uniforms ) {
  13673. var merged = {};
  13674. for ( var u = 0; u < uniforms.length; u ++ ) {
  13675. var tmp = this.clone( uniforms[ u ] );
  13676. for ( var p in tmp ) {
  13677. merged[ p ] = tmp[ p ];
  13678. }
  13679. }
  13680. return merged;
  13681. },
  13682. clone: function ( uniforms_src ) {
  13683. var uniforms_dst = {};
  13684. for ( var u in uniforms_src ) {
  13685. uniforms_dst[ u ] = {};
  13686. for ( var p in uniforms_src[ u ] ) {
  13687. var parameter_src = uniforms_src[ u ][ p ];
  13688. if ( parameter_src instanceof THREE.Color ||
  13689. parameter_src instanceof THREE.Vector2 ||
  13690. parameter_src instanceof THREE.Vector3 ||
  13691. parameter_src instanceof THREE.Vector4 ||
  13692. parameter_src instanceof THREE.Matrix3 ||
  13693. parameter_src instanceof THREE.Matrix4 ||
  13694. parameter_src instanceof THREE.Texture ) {
  13695. uniforms_dst[ u ][ p ] = parameter_src.clone();
  13696. } else if ( Array.isArray( parameter_src ) ) {
  13697. uniforms_dst[ u ][ p ] = parameter_src.slice();
  13698. } else {
  13699. uniforms_dst[ u ][ p ] = parameter_src;
  13700. }
  13701. }
  13702. }
  13703. return uniforms_dst;
  13704. }
  13705. };
  13706. // File:src/renderers/shaders/UniformsLib.js
  13707. /**
  13708. * Uniforms library for shared webgl shaders
  13709. */
  13710. THREE.UniformsLib = {
  13711. common: {
  13712. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  13713. "opacity" : { type: "f", value: 1.0 },
  13714. "map" : { type: "t", value: null },
  13715. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  13716. "specularMap" : { type: "t", value: null },
  13717. "alphaMap" : { type: "t", value: null },
  13718. "envMap" : { type: "t", value: null },
  13719. "flipEnvMap" : { type: "f", value: - 1 },
  13720. "reflectivity" : { type: "f", value: 1.0 },
  13721. "refractionRatio" : { type: "f", value: 0.98 }
  13722. },
  13723. aomap: {
  13724. "aoMap" : { type: "t", value: null },
  13725. "aoMapIntensity" : { type: "f", value: 1 },
  13726. },
  13727. lightmap: {
  13728. "lightMap" : { type: "t", value: null },
  13729. "lightMapIntensity" : { type: "f", value: 1 },
  13730. },
  13731. emissivemap: {
  13732. "emissiveMap" : { type: "t", value: null },
  13733. },
  13734. bumpmap: {
  13735. "bumpMap" : { type: "t", value: null },
  13736. "bumpScale" : { type: "f", value: 1 }
  13737. },
  13738. normalmap: {
  13739. "normalMap" : { type: "t", value: null },
  13740. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  13741. },
  13742. displacementmap: {
  13743. "displacementMap" : { type: "t", value: null },
  13744. "displacementScale" : { type: "f", value: 1 },
  13745. "displacementBias" : { type: "f", value: 0 }
  13746. },
  13747. roughnessmap: {
  13748. "roughnessMap" : { type: "t", value: null }
  13749. },
  13750. reflectivitymap: {
  13751. "reflectivityMap" : { type: "t", value: null }
  13752. },
  13753. metalnessmap: {
  13754. "metalnessMap" : { type: "t", value: null }
  13755. },
  13756. fog : {
  13757. "fogDensity" : { type: "f", value: 0.00025 },
  13758. "fogNear" : { type: "f", value: 1 },
  13759. "fogFar" : { type: "f", value: 2000 },
  13760. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  13761. },
  13762. lights: {
  13763. "ambientLightColor" : { type: "fv", value: [] },
  13764. "directionalLights" : { type: "sa", value: [], properties: {
  13765. "direction": { type: "v3" },
  13766. "color": { type: "c" }
  13767. } },
  13768. "hemisphereLights" : { type: "sa", value: [], properties: {
  13769. "direction": { type: "v3" },
  13770. "skyColor": { type: "c" },
  13771. "groundColor": { type: "c" }
  13772. } },
  13773. "pointLights" : { type: "sa", value: [], properties: {
  13774. "color": { type: "c" },
  13775. "position": { type: "v3" },
  13776. "decay": { type: "f" },
  13777. "distance": { type: "f" }
  13778. } },
  13779. "spotLights" : { type: "sa", value: [], properties: {
  13780. "color": { type: "c" },
  13781. "position": { type: "v3" },
  13782. "direction": { type: "v3" },
  13783. "distance": { type: "f" },
  13784. "angleCos": { type: "f" },
  13785. "exponent": { type: "f" },
  13786. "decay": { type: "f" }
  13787. } }
  13788. },
  13789. points: {
  13790. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  13791. "opacity" : { type: "f", value: 1.0 },
  13792. "size" : { type: "f", value: 1.0 },
  13793. "scale" : { type: "f", value: 1.0 },
  13794. "map" : { type: "t", value: null },
  13795. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  13796. "fogDensity" : { type: "f", value: 0.00025 },
  13797. "fogNear" : { type: "f", value: 1 },
  13798. "fogFar" : { type: "f", value: 2000 },
  13799. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  13800. },
  13801. shadowmap: {
  13802. "shadowMap": { type: "tv", value: [] },
  13803. "shadowMapSize": { type: "v2v", value: [] },
  13804. "shadowBias" : { type: "fv1", value: [] },
  13805. "shadowDarkness": { type: "fv1", value: [] },
  13806. "shadowMatrix" : { type: "m4v", value: [] }
  13807. }
  13808. };
  13809. // File:src/renderers/shaders/ShaderLib.js
  13810. /**
  13811. * Webgl Shader Library for three.js
  13812. *
  13813. * @author alteredq / http://alteredqualia.com/
  13814. * @author mrdoob / http://mrdoob.com/
  13815. * @author mikael emtinger / http://gomo.se/
  13816. */
  13817. THREE.ShaderLib = {
  13818. 'basic': {
  13819. uniforms: THREE.UniformsUtils.merge( [
  13820. THREE.UniformsLib[ "common" ],
  13821. THREE.UniformsLib[ "aomap" ],
  13822. THREE.UniformsLib[ "fog" ],
  13823. THREE.UniformsLib[ "shadowmap" ]
  13824. ] ),
  13825. vertexShader: [
  13826. THREE.ShaderChunk[ "common" ],
  13827. THREE.ShaderChunk[ "uv_pars_vertex" ],
  13828. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  13829. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  13830. THREE.ShaderChunk[ "color_pars_vertex" ],
  13831. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  13832. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  13833. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  13834. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  13835. "void main() {",
  13836. THREE.ShaderChunk[ "uv_vertex" ],
  13837. THREE.ShaderChunk[ "uv2_vertex" ],
  13838. THREE.ShaderChunk[ "color_vertex" ],
  13839. THREE.ShaderChunk[ "skinbase_vertex" ],
  13840. " #ifdef USE_ENVMAP",
  13841. THREE.ShaderChunk[ "beginnormal_vertex" ],
  13842. THREE.ShaderChunk[ "morphnormal_vertex" ],
  13843. THREE.ShaderChunk[ "skinnormal_vertex" ],
  13844. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  13845. " #endif",
  13846. THREE.ShaderChunk[ "begin_vertex" ],
  13847. THREE.ShaderChunk[ "morphtarget_vertex" ],
  13848. THREE.ShaderChunk[ "skinning_vertex" ],
  13849. THREE.ShaderChunk[ "project_vertex" ],
  13850. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  13851. THREE.ShaderChunk[ "worldpos_vertex" ],
  13852. THREE.ShaderChunk[ "envmap_vertex" ],
  13853. THREE.ShaderChunk[ "shadowmap_vertex" ],
  13854. "}"
  13855. ].join( "\n" ),
  13856. fragmentShader: [
  13857. "uniform vec3 diffuse;",
  13858. "uniform float opacity;",
  13859. "#ifndef FLAT_SHADED",
  13860. " varying vec3 vNormal;",
  13861. "#endif",
  13862. THREE.ShaderChunk[ "common" ],
  13863. THREE.ShaderChunk[ "color_pars_fragment" ],
  13864. THREE.ShaderChunk[ "uv_pars_fragment" ],
  13865. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  13866. THREE.ShaderChunk[ "map_pars_fragment" ],
  13867. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  13868. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  13869. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  13870. THREE.ShaderChunk[ "fog_pars_fragment" ],
  13871. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  13872. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  13873. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  13874. "void main() {",
  13875. " vec4 diffuseColor = vec4( diffuse, opacity );",
  13876. " vec3 shadowMask = vec3( 1.0 );",
  13877. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  13878. THREE.ShaderChunk[ "map_fragment" ],
  13879. THREE.ShaderChunk[ "color_fragment" ],
  13880. THREE.ShaderChunk[ "alphamap_fragment" ],
  13881. THREE.ShaderChunk[ "alphatest_fragment" ],
  13882. THREE.ShaderChunk[ "specularmap_fragment" ],
  13883. " ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), diffuseColor.rgb, vec3( 0.0 ) );",
  13884. THREE.ShaderChunk[ "aomap_fragment" ],
  13885. THREE.ShaderChunk[ "shadowmap_fragment" ],
  13886. "reflectedLight.indirectDiffuse *= shadowMask;",
  13887. "vec3 outgoingLight = reflectedLight.indirectDiffuse;",
  13888. THREE.ShaderChunk[ "envmap_fragment" ],
  13889. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  13890. THREE.ShaderChunk[ "fog_fragment" ],
  13891. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  13892. "}"
  13893. ].join( "\n" )
  13894. },
  13895. 'lambert': {
  13896. uniforms: THREE.UniformsUtils.merge( [
  13897. THREE.UniformsLib[ "common" ],
  13898. THREE.UniformsLib[ "fog" ],
  13899. THREE.UniformsLib[ "lights" ],
  13900. THREE.UniformsLib[ "shadowmap" ],
  13901. {
  13902. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) }
  13903. }
  13904. ] ),
  13905. vertexShader: [
  13906. "#define LAMBERT",
  13907. "varying vec3 vLightFront;",
  13908. "#ifdef DOUBLE_SIDED",
  13909. " varying vec3 vLightBack;",
  13910. "#endif",
  13911. THREE.ShaderChunk[ "common" ],
  13912. THREE.ShaderChunk[ "uv_pars_vertex" ],
  13913. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  13914. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  13915. THREE.ShaderChunk[ "bsdfs" ],
  13916. THREE.ShaderChunk[ "lights_pars" ],
  13917. THREE.ShaderChunk[ "color_pars_vertex" ],
  13918. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  13919. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  13920. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  13921. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  13922. "void main() {",
  13923. THREE.ShaderChunk[ "uv_vertex" ],
  13924. THREE.ShaderChunk[ "uv2_vertex" ],
  13925. THREE.ShaderChunk[ "color_vertex" ],
  13926. THREE.ShaderChunk[ "beginnormal_vertex" ],
  13927. THREE.ShaderChunk[ "morphnormal_vertex" ],
  13928. THREE.ShaderChunk[ "skinbase_vertex" ],
  13929. THREE.ShaderChunk[ "skinnormal_vertex" ],
  13930. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  13931. THREE.ShaderChunk[ "begin_vertex" ],
  13932. THREE.ShaderChunk[ "morphtarget_vertex" ],
  13933. THREE.ShaderChunk[ "skinning_vertex" ],
  13934. THREE.ShaderChunk[ "project_vertex" ],
  13935. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  13936. THREE.ShaderChunk[ "worldpos_vertex" ],
  13937. THREE.ShaderChunk[ "envmap_vertex" ],
  13938. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  13939. THREE.ShaderChunk[ "shadowmap_vertex" ],
  13940. "}"
  13941. ].join( "\n" ),
  13942. fragmentShader: [
  13943. "uniform vec3 diffuse;",
  13944. "uniform vec3 emissive;",
  13945. "uniform float opacity;",
  13946. "uniform vec3 ambientLightColor;",
  13947. "varying vec3 vLightFront;",
  13948. "#ifdef DOUBLE_SIDED",
  13949. " varying vec3 vLightBack;",
  13950. "#endif",
  13951. THREE.ShaderChunk[ "common" ],
  13952. THREE.ShaderChunk[ "color_pars_fragment" ],
  13953. THREE.ShaderChunk[ "uv_pars_fragment" ],
  13954. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  13955. THREE.ShaderChunk[ "map_pars_fragment" ],
  13956. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  13957. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  13958. THREE.ShaderChunk[ "fog_pars_fragment" ],
  13959. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  13960. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  13961. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  13962. "void main() {",
  13963. " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
  13964. " vec4 diffuseColor = vec4( diffuse, opacity );",
  13965. " vec3 totalAmbientLight = ambientLightColor;",
  13966. " vec3 shadowMask = vec3( 1.0 );",
  13967. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  13968. THREE.ShaderChunk[ "map_fragment" ],
  13969. THREE.ShaderChunk[ "color_fragment" ],
  13970. THREE.ShaderChunk[ "alphamap_fragment" ],
  13971. THREE.ShaderChunk[ "alphatest_fragment" ],
  13972. THREE.ShaderChunk[ "specularmap_fragment" ],
  13973. THREE.ShaderChunk[ "shadowmap_fragment" ],
  13974. " #ifdef DOUBLE_SIDED",
  13975. " if ( gl_FrontFacing )",
  13976. " outgoingLight += diffuseColor.rgb * ( vLightFront * shadowMask ) + emissive;",
  13977. " else",
  13978. " outgoingLight += diffuseColor.rgb * ( vLightBack * shadowMask ) + emissive;",
  13979. " #else",
  13980. " outgoingLight += diffuseColor.rgb * ( vLightFront * shadowMask ) + emissive;",
  13981. " #endif",
  13982. THREE.ShaderChunk[ "envmap_fragment" ],
  13983. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  13984. THREE.ShaderChunk[ "fog_fragment" ],
  13985. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  13986. "}"
  13987. ].join( "\n" )
  13988. },
  13989. 'phong': {
  13990. uniforms: THREE.UniformsUtils.merge( [
  13991. THREE.UniformsLib[ "common" ],
  13992. THREE.UniformsLib[ "aomap" ],
  13993. THREE.UniformsLib[ "lightmap" ],
  13994. THREE.UniformsLib[ "emissivemap" ],
  13995. THREE.UniformsLib[ "bumpmap" ],
  13996. THREE.UniformsLib[ "normalmap" ],
  13997. THREE.UniformsLib[ "displacementmap" ],
  13998. THREE.UniformsLib[ "fog" ],
  13999. THREE.UniformsLib[ "lights" ],
  14000. THREE.UniformsLib[ "shadowmap" ],
  14001. {
  14002. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  14003. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  14004. "shininess": { type: "f", value: 30 }
  14005. }
  14006. ] ),
  14007. vertexShader: [
  14008. "#define PHONG",
  14009. "varying vec3 vViewPosition;",
  14010. "#ifndef FLAT_SHADED",
  14011. " varying vec3 vNormal;",
  14012. "#endif",
  14013. THREE.ShaderChunk[ "common" ],
  14014. THREE.ShaderChunk[ "uv_pars_vertex" ],
  14015. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  14016. THREE.ShaderChunk[ "displacementmap_pars_vertex" ],
  14017. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  14018. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  14019. THREE.ShaderChunk[ "color_pars_vertex" ],
  14020. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14021. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14022. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  14023. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14024. "void main() {",
  14025. THREE.ShaderChunk[ "uv_vertex" ],
  14026. THREE.ShaderChunk[ "uv2_vertex" ],
  14027. THREE.ShaderChunk[ "color_vertex" ],
  14028. THREE.ShaderChunk[ "beginnormal_vertex" ],
  14029. THREE.ShaderChunk[ "morphnormal_vertex" ],
  14030. THREE.ShaderChunk[ "skinbase_vertex" ],
  14031. THREE.ShaderChunk[ "skinnormal_vertex" ],
  14032. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  14033. "#ifndef FLAT_SHADED", // Normal computed with derivatives when FLAT_SHADED
  14034. " vNormal = normalize( transformedNormal );",
  14035. "#endif",
  14036. THREE.ShaderChunk[ "begin_vertex" ],
  14037. THREE.ShaderChunk[ "displacementmap_vertex" ],
  14038. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14039. THREE.ShaderChunk[ "skinning_vertex" ],
  14040. THREE.ShaderChunk[ "project_vertex" ],
  14041. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14042. " vViewPosition = - mvPosition.xyz;",
  14043. THREE.ShaderChunk[ "worldpos_vertex" ],
  14044. THREE.ShaderChunk[ "envmap_vertex" ],
  14045. THREE.ShaderChunk[ "lights_phong_vertex" ],
  14046. THREE.ShaderChunk[ "shadowmap_vertex" ],
  14047. "}"
  14048. ].join( "\n" ),
  14049. fragmentShader: [
  14050. "#define PHONG",
  14051. "uniform vec3 diffuse;",
  14052. "uniform vec3 emissive;",
  14053. "uniform vec3 specular;",
  14054. "uniform float shininess;",
  14055. "uniform float opacity;",
  14056. THREE.ShaderChunk[ "common" ],
  14057. THREE.ShaderChunk[ "color_pars_fragment" ],
  14058. THREE.ShaderChunk[ "uv_pars_fragment" ],
  14059. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  14060. THREE.ShaderChunk[ "map_pars_fragment" ],
  14061. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  14062. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  14063. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  14064. THREE.ShaderChunk[ "emissivemap_pars_fragment" ],
  14065. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  14066. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14067. THREE.ShaderChunk[ "bsdfs" ],
  14068. THREE.ShaderChunk[ "lights_pars" ],
  14069. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  14070. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14071. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  14072. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  14073. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  14074. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14075. "void main() {",
  14076. " vec4 diffuseColor = vec4( diffuse, opacity );",
  14077. " ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );",
  14078. " vec3 totalEmissiveLight = emissive;",
  14079. " vec3 shadowMask = vec3( 1.0 );",
  14080. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14081. THREE.ShaderChunk[ "map_fragment" ],
  14082. THREE.ShaderChunk[ "color_fragment" ],
  14083. THREE.ShaderChunk[ "alphamap_fragment" ],
  14084. THREE.ShaderChunk[ "alphatest_fragment" ],
  14085. THREE.ShaderChunk[ "specularmap_fragment" ],
  14086. THREE.ShaderChunk[ "normal_phong_fragment" ],
  14087. THREE.ShaderChunk[ "emissivemap_fragment" ],
  14088. // accumulation
  14089. THREE.ShaderChunk[ "lights_phong_fragment" ],
  14090. THREE.ShaderChunk[ "lights_template" ],
  14091. THREE.ShaderChunk[ "lightmap_fragment" ],
  14092. // modulation
  14093. THREE.ShaderChunk[ "aomap_fragment" ],
  14094. THREE.ShaderChunk[ "shadowmap_fragment" ],
  14095. "reflectedLight.directDiffuse *= shadowMask;",
  14096. "reflectedLight.directSpecular *= shadowMask;",
  14097. "vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveLight;",
  14098. THREE.ShaderChunk[ "envmap_fragment" ],
  14099. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  14100. THREE.ShaderChunk[ "fog_fragment" ],
  14101. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  14102. "}"
  14103. ].join( "\n" )
  14104. },
  14105. 'physical': {
  14106. uniforms: THREE.UniformsUtils.merge( [
  14107. THREE.UniformsLib[ "common" ],
  14108. THREE.UniformsLib[ "aomap" ],
  14109. THREE.UniformsLib[ "lightmap" ],
  14110. THREE.UniformsLib[ "emissivemap" ],
  14111. THREE.UniformsLib[ "bumpmap" ],
  14112. THREE.UniformsLib[ "normalmap" ],
  14113. THREE.UniformsLib[ "displacementmap" ],
  14114. THREE.UniformsLib[ "roughnessmap" ],
  14115. THREE.UniformsLib[ "reflectivitymap" ],
  14116. THREE.UniformsLib[ "metalnessmap" ],
  14117. THREE.UniformsLib[ "fog" ],
  14118. THREE.UniformsLib[ "lights" ],
  14119. THREE.UniformsLib[ "shadowmap" ],
  14120. {
  14121. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  14122. "roughness": { type: "f", value: 0.5 },
  14123. "metalness": { type: "f", value: 0 },
  14124. "envMapIntensity" : { type: "f", value: 1 } // temporary
  14125. }
  14126. ] ),
  14127. vertexShader: [
  14128. "#define PHYSICAL",
  14129. "varying vec3 vViewPosition;",
  14130. "#ifndef FLAT_SHADED",
  14131. " varying vec3 vNormal;",
  14132. "#endif",
  14133. THREE.ShaderChunk[ "common" ],
  14134. THREE.ShaderChunk[ "uv_pars_vertex" ],
  14135. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  14136. THREE.ShaderChunk[ "displacementmap_pars_vertex" ],
  14137. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  14138. THREE.ShaderChunk[ "lights_phong_pars_vertex" ], // use phong chunk for now
  14139. THREE.ShaderChunk[ "color_pars_vertex" ],
  14140. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14141. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14142. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  14143. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  14144. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14145. "void main() {", // PHYSICAL
  14146. THREE.ShaderChunk[ "uv_vertex" ],
  14147. THREE.ShaderChunk[ "uv2_vertex" ],
  14148. THREE.ShaderChunk[ "color_vertex" ],
  14149. THREE.ShaderChunk[ "beginnormal_vertex" ],
  14150. THREE.ShaderChunk[ "morphnormal_vertex" ],
  14151. THREE.ShaderChunk[ "skinbase_vertex" ],
  14152. THREE.ShaderChunk[ "skinnormal_vertex" ],
  14153. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  14154. "#ifndef FLAT_SHADED", // Normal computed with derivatives when FLAT_SHADED
  14155. " vNormal = normalize( transformedNormal );",
  14156. "#endif",
  14157. THREE.ShaderChunk[ "begin_vertex" ],
  14158. THREE.ShaderChunk[ "displacementmap_vertex" ],
  14159. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14160. THREE.ShaderChunk[ "skinning_vertex" ],
  14161. THREE.ShaderChunk[ "project_vertex" ],
  14162. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14163. " vViewPosition = - mvPosition.xyz;",
  14164. THREE.ShaderChunk[ "worldpos_vertex" ],
  14165. THREE.ShaderChunk[ "envmap_vertex" ],
  14166. THREE.ShaderChunk[ "lights_phong_vertex" ], // use phong chunk for now
  14167. THREE.ShaderChunk[ "shadowmap_vertex" ],
  14168. "}"
  14169. ].join( "\n" ),
  14170. fragmentShader: [
  14171. "#define PHYSICAL",
  14172. "uniform vec3 diffuse;",
  14173. "uniform vec3 emissive;",
  14174. "uniform float roughness;",
  14175. "uniform float metalness;",
  14176. "uniform float opacity;",
  14177. "uniform float envMapIntensity;", // temporary
  14178. "varying vec3 vViewPosition;",
  14179. "#ifndef FLAT_SHADED",
  14180. " varying vec3 vNormal;",
  14181. "#endif",
  14182. THREE.ShaderChunk[ "common" ],
  14183. THREE.ShaderChunk[ "color_pars_fragment" ],
  14184. THREE.ShaderChunk[ "uv_pars_fragment" ],
  14185. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  14186. THREE.ShaderChunk[ "map_pars_fragment" ],
  14187. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  14188. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  14189. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  14190. THREE.ShaderChunk[ "emissivemap_pars_fragment" ],
  14191. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  14192. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14193. THREE.ShaderChunk[ "bsdfs" ],
  14194. THREE.ShaderChunk[ "lights_pars" ],
  14195. THREE.ShaderChunk[ "lights_physical_pars_fragment" ],
  14196. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14197. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  14198. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  14199. THREE.ShaderChunk[ "roughnessmap_pars_fragment" ],
  14200. //THREE.ShaderChunk[ "reflectivitymap_pars_fragment" ],
  14201. THREE.ShaderChunk[ "metalnessmap_pars_fragment" ],
  14202. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14203. "void main() {",
  14204. " vec4 diffuseColor = vec4( diffuse, opacity );",
  14205. " ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );",
  14206. " vec3 totalEmissiveLight = emissive;",
  14207. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14208. THREE.ShaderChunk[ "map_fragment" ],
  14209. THREE.ShaderChunk[ "color_fragment" ],
  14210. THREE.ShaderChunk[ "alphamap_fragment" ],
  14211. THREE.ShaderChunk[ "alphatest_fragment" ],
  14212. THREE.ShaderChunk[ "specularmap_fragment" ],
  14213. THREE.ShaderChunk[ "roughnessmap_fragment" ],
  14214. //THREE.ShaderChunk[ "reflectivitymap_fragment" ],
  14215. THREE.ShaderChunk[ "metalnessmap_fragment" ],
  14216. THREE.ShaderChunk[ "normal_phong_fragment" ], // use phong chunk for now
  14217. THREE.ShaderChunk[ "emissivemap_fragment" ],
  14218. // accumulation
  14219. THREE.ShaderChunk[ "lights_physical_fragment" ],
  14220. THREE.ShaderChunk[ "lights_template" ],
  14221. THREE.ShaderChunk[ "lightmap_fragment" ],
  14222. // modulation
  14223. THREE.ShaderChunk[ "aomap_fragment" ],
  14224. "vec3 shadowMask = vec3( 1.0 );",
  14225. THREE.ShaderChunk[ "shadowmap_fragment" ],
  14226. "reflectedLight.directDiffuse *= shadowMask;",
  14227. "reflectedLight.directSpecular *= shadowMask;",
  14228. "vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveLight;",
  14229. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  14230. THREE.ShaderChunk[ "fog_fragment" ],
  14231. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  14232. "}"
  14233. ].join( "\n" )
  14234. },
  14235. 'points': {
  14236. uniforms: THREE.UniformsUtils.merge( [
  14237. THREE.UniformsLib[ "points" ],
  14238. THREE.UniformsLib[ "shadowmap" ]
  14239. ] ),
  14240. vertexShader: [
  14241. "uniform float size;",
  14242. "uniform float scale;",
  14243. THREE.ShaderChunk[ "common" ],
  14244. THREE.ShaderChunk[ "color_pars_vertex" ],
  14245. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  14246. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14247. "void main() {",
  14248. THREE.ShaderChunk[ "color_vertex" ],
  14249. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  14250. " #ifdef USE_SIZEATTENUATION",
  14251. " gl_PointSize = size * ( scale / -mvPosition.z );",
  14252. " #else",
  14253. " gl_PointSize = size;",
  14254. " #endif",
  14255. " gl_Position = projectionMatrix * mvPosition;",
  14256. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14257. THREE.ShaderChunk[ "worldpos_vertex" ],
  14258. THREE.ShaderChunk[ "shadowmap_vertex" ],
  14259. "}"
  14260. ].join( "\n" ),
  14261. fragmentShader: [
  14262. "uniform vec3 psColor;",
  14263. "uniform float opacity;",
  14264. THREE.ShaderChunk[ "common" ],
  14265. THREE.ShaderChunk[ "color_pars_fragment" ],
  14266. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  14267. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14268. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14269. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14270. "void main() {",
  14271. " vec3 outgoingLight = vec3( 0.0 );",
  14272. " vec4 diffuseColor = vec4( psColor, opacity );",
  14273. " vec3 shadowMask = vec3( 1.0 );",
  14274. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14275. THREE.ShaderChunk[ "map_particle_fragment" ],
  14276. THREE.ShaderChunk[ "color_fragment" ],
  14277. THREE.ShaderChunk[ "alphatest_fragment" ],
  14278. THREE.ShaderChunk[ "shadowmap_fragment" ],
  14279. " outgoingLight = diffuseColor.rgb * shadowMask;",
  14280. THREE.ShaderChunk[ "fog_fragment" ],
  14281. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  14282. "}"
  14283. ].join( "\n" )
  14284. },
  14285. 'dashed': {
  14286. uniforms: THREE.UniformsUtils.merge( [
  14287. THREE.UniformsLib[ "common" ],
  14288. THREE.UniformsLib[ "fog" ],
  14289. {
  14290. "scale" : { type: "f", value: 1 },
  14291. "dashSize" : { type: "f", value: 1 },
  14292. "totalSize": { type: "f", value: 2 }
  14293. }
  14294. ] ),
  14295. vertexShader: [
  14296. "uniform float scale;",
  14297. "attribute float lineDistance;",
  14298. "varying float vLineDistance;",
  14299. THREE.ShaderChunk[ "common" ],
  14300. THREE.ShaderChunk[ "color_pars_vertex" ],
  14301. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14302. "void main() {",
  14303. THREE.ShaderChunk[ "color_vertex" ],
  14304. " vLineDistance = scale * lineDistance;",
  14305. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  14306. " gl_Position = projectionMatrix * mvPosition;",
  14307. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14308. "}"
  14309. ].join( "\n" ),
  14310. fragmentShader: [
  14311. "uniform vec3 diffuse;",
  14312. "uniform float opacity;",
  14313. "uniform float dashSize;",
  14314. "uniform float totalSize;",
  14315. "varying float vLineDistance;",
  14316. THREE.ShaderChunk[ "common" ],
  14317. THREE.ShaderChunk[ "color_pars_fragment" ],
  14318. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14319. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14320. "void main() {",
  14321. " if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  14322. " discard;",
  14323. " }",
  14324. " vec3 outgoingLight = vec3( 0.0 );",
  14325. " vec4 diffuseColor = vec4( diffuse, opacity );",
  14326. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14327. THREE.ShaderChunk[ "color_fragment" ],
  14328. " outgoingLight = diffuseColor.rgb;", // simple shader
  14329. THREE.ShaderChunk[ "fog_fragment" ],
  14330. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  14331. "}"
  14332. ].join( "\n" )
  14333. },
  14334. 'depth': {
  14335. uniforms: {
  14336. "mNear": { type: "f", value: 1.0 },
  14337. "mFar" : { type: "f", value: 2000.0 },
  14338. "opacity" : { type: "f", value: 1.0 }
  14339. },
  14340. vertexShader: [
  14341. THREE.ShaderChunk[ "common" ],
  14342. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14343. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14344. "void main() {",
  14345. THREE.ShaderChunk[ "begin_vertex" ],
  14346. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14347. THREE.ShaderChunk[ "project_vertex" ],
  14348. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14349. "}"
  14350. ].join( "\n" ),
  14351. fragmentShader: [
  14352. "uniform float mNear;",
  14353. "uniform float mFar;",
  14354. "uniform float opacity;",
  14355. THREE.ShaderChunk[ "common" ],
  14356. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14357. "void main() {",
  14358. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14359. " #ifdef USE_LOGDEPTHBUF_EXT",
  14360. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  14361. " #else",
  14362. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  14363. " #endif",
  14364. " float color = 1.0 - smoothstep( mNear, mFar, depth );",
  14365. " gl_FragColor = vec4( vec3( color ), opacity );",
  14366. "}"
  14367. ].join( "\n" )
  14368. },
  14369. 'normal': {
  14370. uniforms: {
  14371. "opacity" : { type: "f", value: 1.0 }
  14372. },
  14373. vertexShader: [
  14374. "varying vec3 vNormal;",
  14375. THREE.ShaderChunk[ "common" ],
  14376. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14377. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14378. "void main() {",
  14379. " vNormal = normalize( normalMatrix * normal );",
  14380. THREE.ShaderChunk[ "begin_vertex" ],
  14381. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14382. THREE.ShaderChunk[ "project_vertex" ],
  14383. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14384. "}"
  14385. ].join( "\n" ),
  14386. fragmentShader: [
  14387. "uniform float opacity;",
  14388. "varying vec3 vNormal;",
  14389. THREE.ShaderChunk[ "common" ],
  14390. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14391. "void main() {",
  14392. " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  14393. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14394. "}"
  14395. ].join( "\n" )
  14396. },
  14397. /* -------------------------------------------------------------------------
  14398. // Cube map shader
  14399. ------------------------------------------------------------------------- */
  14400. 'cube': {
  14401. uniforms: { "tCube": { type: "t", value: null },
  14402. "tFlip": { type: "f", value: - 1 } },
  14403. vertexShader: [
  14404. "varying vec3 vWorldPosition;",
  14405. THREE.ShaderChunk[ "common" ],
  14406. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14407. "void main() {",
  14408. " vWorldPosition = transformDirection( position, modelMatrix );",
  14409. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  14410. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14411. "}"
  14412. ].join( "\n" ),
  14413. fragmentShader: [
  14414. "uniform samplerCube tCube;",
  14415. "uniform float tFlip;",
  14416. "varying vec3 vWorldPosition;",
  14417. THREE.ShaderChunk[ "common" ],
  14418. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14419. "void main() {",
  14420. " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  14421. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14422. "}"
  14423. ].join( "\n" )
  14424. },
  14425. /* -------------------------------------------------------------------------
  14426. // Cube map shader
  14427. ------------------------------------------------------------------------- */
  14428. 'equirect': {
  14429. uniforms: { "tEquirect": { type: "t", value: null },
  14430. "tFlip": { type: "f", value: - 1 } },
  14431. vertexShader: [
  14432. "varying vec3 vWorldPosition;",
  14433. THREE.ShaderChunk[ "common" ],
  14434. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14435. "void main() {",
  14436. " vWorldPosition = transformDirection( position, modelMatrix );",
  14437. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  14438. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14439. "}"
  14440. ].join( "\n" ),
  14441. fragmentShader: [
  14442. "uniform sampler2D tEquirect;",
  14443. "uniform float tFlip;",
  14444. "varying vec3 vWorldPosition;",
  14445. THREE.ShaderChunk[ "common" ],
  14446. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14447. "void main() {",
  14448. // " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  14449. "vec3 direction = normalize( vWorldPosition );",
  14450. "vec2 sampleUV;",
  14451. "sampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );",
  14452. "sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;",
  14453. "gl_FragColor = texture2D( tEquirect, sampleUV );",
  14454. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14455. "}"
  14456. ].join( "\n" )
  14457. },
  14458. /* Depth encoding into RGBA texture
  14459. *
  14460. * based on SpiderGL shadow map example
  14461. * http://spidergl.org/example.php?id=6
  14462. *
  14463. * originally from
  14464. * http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  14465. *
  14466. * see also
  14467. * http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  14468. */
  14469. 'depthRGBA': {
  14470. uniforms: {},
  14471. vertexShader: [
  14472. THREE.ShaderChunk[ "common" ],
  14473. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14474. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14475. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14476. "void main() {",
  14477. THREE.ShaderChunk[ "skinbase_vertex" ],
  14478. THREE.ShaderChunk[ "begin_vertex" ],
  14479. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14480. THREE.ShaderChunk[ "skinning_vertex" ],
  14481. THREE.ShaderChunk[ "project_vertex" ],
  14482. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14483. "}"
  14484. ].join( "\n" ),
  14485. fragmentShader: [
  14486. THREE.ShaderChunk[ "common" ],
  14487. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14488. "vec4 pack_depth( const in float depth ) {",
  14489. " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  14490. " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  14491. " vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );", // " vec4 res = fract( depth * bit_shift );",
  14492. " res -= res.xxyz * bit_mask;",
  14493. " return res;",
  14494. "}",
  14495. "void main() {",
  14496. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14497. " #ifdef USE_LOGDEPTHBUF_EXT",
  14498. " gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );",
  14499. " #else",
  14500. " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  14501. " #endif",
  14502. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  14503. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  14504. //"gl_FragData[ 0 ] = pack_depth( z );",
  14505. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  14506. "}"
  14507. ].join( "\n" )
  14508. },
  14509. 'distanceRGBA': {
  14510. uniforms: {
  14511. "lightPos": { type: "v3", value: new THREE.Vector3( 0, 0, 0 ) }
  14512. },
  14513. vertexShader: [
  14514. "varying vec4 vWorldPosition;",
  14515. THREE.ShaderChunk[ "common" ],
  14516. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14517. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14518. "void main() {",
  14519. THREE.ShaderChunk[ "skinbase_vertex" ],
  14520. THREE.ShaderChunk[ "begin_vertex" ],
  14521. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14522. THREE.ShaderChunk[ "skinning_vertex" ],
  14523. THREE.ShaderChunk[ "project_vertex" ],
  14524. THREE.ShaderChunk[ "worldpos_vertex" ],
  14525. "vWorldPosition = worldPosition;",
  14526. "}"
  14527. ].join( "\n" ),
  14528. fragmentShader: [
  14529. "uniform vec3 lightPos;",
  14530. "varying vec4 vWorldPosition;",
  14531. THREE.ShaderChunk[ "common" ],
  14532. "vec4 pack1K ( float depth ) {",
  14533. " depth /= 1000.0;",
  14534. " const vec4 bitSh = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  14535. " const vec4 bitMsk = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  14536. " vec4 res = fract( depth * bitSh );",
  14537. " res -= res.xxyz * bitMsk;",
  14538. " return res; ",
  14539. "}",
  14540. "float unpack1K ( vec4 color ) {",
  14541. " const vec4 bitSh = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );",
  14542. " return dot( color, bitSh ) * 1000.0;",
  14543. "}",
  14544. "void main () {",
  14545. " gl_FragColor = pack1K( length( vWorldPosition.xyz - lightPos.xyz ) );",
  14546. "}"
  14547. ].join( "\n" )
  14548. }
  14549. };
  14550. // File:src/renderers/WebGLRenderer.js
  14551. /**
  14552. * @author supereggbert / http://www.paulbrunt.co.uk/
  14553. * @author mrdoob / http://mrdoob.com/
  14554. * @author alteredq / http://alteredqualia.com/
  14555. * @author szimek / https://github.com/szimek/
  14556. */
  14557. THREE.WebGLRenderer = function ( parameters ) {
  14558. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  14559. parameters = parameters || {};
  14560. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  14561. _context = parameters.context !== undefined ? parameters.context : null,
  14562. _width = _canvas.width,
  14563. _height = _canvas.height,
  14564. pixelRatio = 1,
  14565. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14566. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14567. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14568. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14569. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14570. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14571. _clearColor = new THREE.Color( 0x000000 ),
  14572. _clearAlpha = 0;
  14573. var lights = [];
  14574. var opaqueObjects = [];
  14575. var opaqueObjectsLastIndex = - 1;
  14576. var transparentObjects = [];
  14577. var transparentObjectsLastIndex = - 1;
  14578. var morphInfluences = new Float32Array( 8 );
  14579. var sprites = [];
  14580. var lensFlares = [];
  14581. // public properties
  14582. this.domElement = _canvas;
  14583. this.context = null;
  14584. // clearing
  14585. this.autoClear = true;
  14586. this.autoClearColor = true;
  14587. this.autoClearDepth = true;
  14588. this.autoClearStencil = true;
  14589. // scene graph
  14590. this.sortObjects = true;
  14591. // physically based shading
  14592. this.gammaFactor = 2.0; // for backwards compatibility
  14593. this.gammaInput = false;
  14594. this.gammaOutput = false;
  14595. // morphs
  14596. this.maxMorphTargets = 8;
  14597. this.maxMorphNormals = 4;
  14598. // flags
  14599. this.autoScaleCubemaps = true;
  14600. // internal properties
  14601. var _this = this,
  14602. // internal state cache
  14603. _currentProgram = null,
  14604. _currentFramebuffer = null,
  14605. _currentMaterialId = - 1,
  14606. _currentGeometryProgram = '',
  14607. _currentCamera = null,
  14608. _usedTextureUnits = 0,
  14609. _viewportX = 0,
  14610. _viewportY = 0,
  14611. _viewportWidth = _canvas.width,
  14612. _viewportHeight = _canvas.height,
  14613. _currentWidth = 0,
  14614. _currentHeight = 0,
  14615. // frustum
  14616. _frustum = new THREE.Frustum(),
  14617. // camera matrices cache
  14618. _projScreenMatrix = new THREE.Matrix4(),
  14619. _vector3 = new THREE.Vector3(),
  14620. // light arrays cache
  14621. _lights = {
  14622. hash: '',
  14623. ambient: [ 0, 0, 0 ],
  14624. directional: [],
  14625. point: [],
  14626. spot: [],
  14627. hemi: [],
  14628. shadows: 0,
  14629. shadowsPointLight: 0
  14630. },
  14631. // info
  14632. _infoMemory = {
  14633. geometries: 0,
  14634. textures: 0
  14635. },
  14636. _infoRender = {
  14637. calls: 0,
  14638. vertices: 0,
  14639. faces: 0,
  14640. points: 0
  14641. };
  14642. this.info = {
  14643. render: _infoRender,
  14644. memory: _infoMemory,
  14645. programs: null
  14646. };
  14647. // initialize
  14648. var _gl;
  14649. try {
  14650. var attributes = {
  14651. alpha: _alpha,
  14652. depth: _depth,
  14653. stencil: _stencil,
  14654. antialias: _antialias,
  14655. premultipliedAlpha: _premultipliedAlpha,
  14656. preserveDrawingBuffer: _preserveDrawingBuffer
  14657. };
  14658. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  14659. if ( _gl === null ) {
  14660. if ( _canvas.getContext( 'webgl' ) !== null ) {
  14661. throw 'Error creating WebGL context with your selected attributes.';
  14662. } else {
  14663. throw 'Error creating WebGL context.';
  14664. }
  14665. }
  14666. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  14667. } catch ( error ) {
  14668. console.error( 'THREE.WebGLRenderer: ' + error );
  14669. }
  14670. var extensions = new THREE.WebGLExtensions( _gl );
  14671. extensions.get( 'OES_texture_float' );
  14672. extensions.get( 'OES_texture_float_linear' );
  14673. extensions.get( 'OES_texture_half_float' );
  14674. extensions.get( 'OES_texture_half_float_linear' );
  14675. extensions.get( 'OES_standard_derivatives' );
  14676. extensions.get( 'ANGLE_instanced_arrays' );
  14677. if ( extensions.get( 'OES_element_index_uint' ) ) {
  14678. THREE.BufferGeometry.MaxIndex = 4294967296;
  14679. }
  14680. var capabilities = new THREE.WebGLCapabilities( _gl, extensions, parameters );
  14681. var state = new THREE.WebGLState( _gl, extensions, paramThreeToGL );
  14682. var properties = new THREE.WebGLProperties();
  14683. var objects = new THREE.WebGLObjects( _gl, properties, this.info );
  14684. var programCache = new THREE.WebGLPrograms( this, capabilities );
  14685. this.info.programs = programCache.programs;
  14686. var bufferRenderer = new THREE.WebGLBufferRenderer( _gl, extensions, _infoRender );
  14687. var indexedBufferRenderer = new THREE.WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  14688. //
  14689. function glClearColor( r, g, b, a ) {
  14690. if ( _premultipliedAlpha === true ) {
  14691. r *= a; g *= a; b *= a;
  14692. }
  14693. _gl.clearColor( r, g, b, a );
  14694. }
  14695. function setDefaultGLState() {
  14696. state.init();
  14697. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  14698. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14699. }
  14700. function resetGLState() {
  14701. _currentProgram = null;
  14702. _currentCamera = null;
  14703. _currentGeometryProgram = '';
  14704. _currentMaterialId = - 1;
  14705. state.reset();
  14706. }
  14707. setDefaultGLState();
  14708. this.context = _gl;
  14709. this.capabilities = capabilities;
  14710. this.extensions = extensions;
  14711. this.state = state;
  14712. // shadow map
  14713. var shadowMap = new THREE.WebGLShadowMap( this, lights, objects );
  14714. this.shadowMap = shadowMap;
  14715. // Plugins
  14716. var spritePlugin = new THREE.SpritePlugin( this, sprites );
  14717. var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares );
  14718. // API
  14719. this.getContext = function () {
  14720. return _gl;
  14721. };
  14722. this.getContextAttributes = function () {
  14723. return _gl.getContextAttributes();
  14724. };
  14725. this.forceContextLoss = function () {
  14726. extensions.get( 'WEBGL_lose_context' ).loseContext();
  14727. };
  14728. this.getMaxAnisotropy = ( function () {
  14729. var value;
  14730. return function getMaxAnisotropy() {
  14731. if ( value !== undefined ) return value;
  14732. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14733. if ( extension !== null ) {
  14734. value = _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  14735. } else {
  14736. value = 0;
  14737. }
  14738. return value;
  14739. }
  14740. } )();
  14741. this.getPrecision = function () {
  14742. return capabilities.precision;
  14743. };
  14744. this.getPixelRatio = function () {
  14745. return pixelRatio;
  14746. };
  14747. this.setPixelRatio = function ( value ) {
  14748. if ( value !== undefined ) pixelRatio = value;
  14749. };
  14750. this.getSize = function () {
  14751. return {
  14752. width: _width,
  14753. height: _height
  14754. };
  14755. };
  14756. this.setSize = function ( width, height, updateStyle ) {
  14757. _width = width;
  14758. _height = height;
  14759. _canvas.width = width * pixelRatio;
  14760. _canvas.height = height * pixelRatio;
  14761. if ( updateStyle !== false ) {
  14762. _canvas.style.width = width + 'px';
  14763. _canvas.style.height = height + 'px';
  14764. }
  14765. this.setViewport( 0, 0, width, height );
  14766. };
  14767. this.setViewport = function ( x, y, width, height ) {
  14768. _viewportX = x * pixelRatio;
  14769. _viewportY = y * pixelRatio;
  14770. _viewportWidth = width * pixelRatio;
  14771. _viewportHeight = height * pixelRatio;
  14772. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  14773. };
  14774. this.getViewport = function ( dimensions ) {
  14775. dimensions.x = _viewportX / pixelRatio;
  14776. dimensions.y = _viewportY / pixelRatio;
  14777. dimensions.z = _viewportWidth / pixelRatio;
  14778. dimensions.w = _viewportHeight / pixelRatio;
  14779. };
  14780. this.setScissor = function ( x, y, width, height ) {
  14781. _gl.scissor(
  14782. x * pixelRatio,
  14783. y * pixelRatio,
  14784. width * pixelRatio,
  14785. height * pixelRatio
  14786. );
  14787. };
  14788. this.enableScissorTest = function ( boolean ) {
  14789. state.setScissorTest( boolean );
  14790. };
  14791. // Clearing
  14792. this.getClearColor = function () {
  14793. return _clearColor;
  14794. };
  14795. this.setClearColor = function ( color, alpha ) {
  14796. _clearColor.set( color );
  14797. _clearAlpha = alpha !== undefined ? alpha : 1;
  14798. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14799. };
  14800. this.getClearAlpha = function () {
  14801. return _clearAlpha;
  14802. };
  14803. this.setClearAlpha = function ( alpha ) {
  14804. _clearAlpha = alpha;
  14805. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14806. };
  14807. this.clear = function ( color, depth, stencil ) {
  14808. var bits = 0;
  14809. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  14810. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  14811. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  14812. _gl.clear( bits );
  14813. };
  14814. this.clearColor = function () {
  14815. _gl.clear( _gl.COLOR_BUFFER_BIT );
  14816. };
  14817. this.clearDepth = function () {
  14818. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  14819. };
  14820. this.clearStencil = function () {
  14821. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  14822. };
  14823. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  14824. this.setRenderTarget( renderTarget );
  14825. this.clear( color, depth, stencil );
  14826. };
  14827. // Reset
  14828. this.resetGLState = resetGLState;
  14829. this.dispose = function() {
  14830. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  14831. };
  14832. // Events
  14833. function onContextLost( event ) {
  14834. event.preventDefault();
  14835. resetGLState();
  14836. setDefaultGLState();
  14837. properties.clear();
  14838. };
  14839. function onTextureDispose( event ) {
  14840. var texture = event.target;
  14841. texture.removeEventListener( 'dispose', onTextureDispose );
  14842. deallocateTexture( texture );
  14843. _infoMemory.textures --;
  14844. }
  14845. function onRenderTargetDispose( event ) {
  14846. var renderTarget = event.target;
  14847. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  14848. deallocateRenderTarget( renderTarget );
  14849. _infoMemory.textures --;
  14850. }
  14851. function onMaterialDispose( event ) {
  14852. var material = event.target;
  14853. material.removeEventListener( 'dispose', onMaterialDispose );
  14854. deallocateMaterial( material );
  14855. }
  14856. // Buffer deallocation
  14857. function deallocateTexture( texture ) {
  14858. var textureProperties = properties.get( texture );
  14859. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  14860. // cube texture
  14861. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  14862. } else {
  14863. // 2D texture
  14864. if ( textureProperties.__webglInit === undefined ) return;
  14865. _gl.deleteTexture( textureProperties.__webglTexture );
  14866. }
  14867. // remove all webgl properties
  14868. properties.delete( texture );
  14869. }
  14870. function deallocateRenderTarget( renderTarget ) {
  14871. var renderTargetProperties = properties.get( renderTarget );
  14872. var textureProperties = properties.get( renderTarget.texture );
  14873. if ( ! renderTarget || textureProperties.__webglTexture === undefined ) return;
  14874. _gl.deleteTexture( textureProperties.__webglTexture );
  14875. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  14876. for ( var i = 0; i < 6; i ++ ) {
  14877. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  14878. _gl.deleteRenderbuffer( renderTargetProperties.__webglRenderbuffer[ i ] );
  14879. }
  14880. } else {
  14881. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  14882. _gl.deleteRenderbuffer( renderTargetProperties.__webglRenderbuffer );
  14883. }
  14884. properties.delete( renderTarget.texture );
  14885. properties.delete( renderTarget );
  14886. }
  14887. function deallocateMaterial( material ) {
  14888. releaseMaterialProgramReference( material );
  14889. properties.delete( material );
  14890. }
  14891. function releaseMaterialProgramReference( material ) {
  14892. var programInfo = properties.get( material ).program;
  14893. material.program = undefined;
  14894. if ( programInfo !== undefined ) {
  14895. programCache.releaseProgram( programInfo );
  14896. }
  14897. }
  14898. // Buffer rendering
  14899. this.renderBufferImmediate = function ( object, program, material ) {
  14900. state.initAttributes();
  14901. var buffers = properties.get( object );
  14902. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  14903. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  14904. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  14905. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  14906. var attributes = program.getAttributes();
  14907. if ( object.hasPositions ) {
  14908. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  14909. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  14910. state.enableAttribute( attributes.position );
  14911. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  14912. }
  14913. if ( object.hasNormals ) {
  14914. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  14915. if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshPhysicalMaterial' && material.shading === THREE.FlatShading ) {
  14916. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  14917. var array = object.normalArray;
  14918. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  14919. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  14920. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  14921. array[ i + 0 ] = nx;
  14922. array[ i + 1 ] = ny;
  14923. array[ i + 2 ] = nz;
  14924. array[ i + 3 ] = nx;
  14925. array[ i + 4 ] = ny;
  14926. array[ i + 5 ] = nz;
  14927. array[ i + 6 ] = nx;
  14928. array[ i + 7 ] = ny;
  14929. array[ i + 8 ] = nz;
  14930. }
  14931. }
  14932. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  14933. state.enableAttribute( attributes.normal );
  14934. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  14935. }
  14936. if ( object.hasUvs && material.map ) {
  14937. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  14938. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  14939. state.enableAttribute( attributes.uv );
  14940. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  14941. }
  14942. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  14943. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  14944. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  14945. state.enableAttribute( attributes.color );
  14946. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  14947. }
  14948. state.disableUnusedAttributes();
  14949. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  14950. object.count = 0;
  14951. };
  14952. this.renderBufferDirect = function ( camera, lights, fog, geometry, material, object, group ) {
  14953. setMaterial( material );
  14954. var program = setProgram( camera, lights, fog, material, object );
  14955. var updateBuffers = false;
  14956. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  14957. if ( geometryProgram !== _currentGeometryProgram ) {
  14958. _currentGeometryProgram = geometryProgram;
  14959. updateBuffers = true;
  14960. }
  14961. // morph targets
  14962. var morphTargetInfluences = object.morphTargetInfluences;
  14963. if ( morphTargetInfluences !== undefined ) {
  14964. var activeInfluences = [];
  14965. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  14966. var influence = morphTargetInfluences[ i ];
  14967. activeInfluences.push( [ influence, i ] );
  14968. }
  14969. activeInfluences.sort( numericalSort );
  14970. if ( activeInfluences.length > 8 ) {
  14971. activeInfluences.length = 8;
  14972. }
  14973. var morphAttributes = geometry.morphAttributes;
  14974. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  14975. var influence = activeInfluences[ i ];
  14976. morphInfluences[ i ] = influence[ 0 ];
  14977. if ( influence[ 0 ] !== 0 ) {
  14978. var index = influence[ 1 ];
  14979. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  14980. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  14981. } else {
  14982. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  14983. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  14984. }
  14985. }
  14986. var uniforms = program.getUniforms();
  14987. if ( uniforms.morphTargetInfluences !== null ) {
  14988. _gl.uniform1fv( uniforms.morphTargetInfluences, morphInfluences );
  14989. }
  14990. updateBuffers = true;
  14991. }
  14992. //
  14993. var index = geometry.index;
  14994. var position = geometry.attributes.position;
  14995. if ( material.wireframe === true ) {
  14996. index = objects.getWireframeAttribute( geometry );
  14997. }
  14998. var renderer;
  14999. if ( index !== null ) {
  15000. renderer = indexedBufferRenderer;
  15001. renderer.setIndex( index );
  15002. } else {
  15003. renderer = bufferRenderer;
  15004. }
  15005. if ( updateBuffers ) {
  15006. setupVertexAttributes( material, program, geometry );
  15007. if ( index !== null ) {
  15008. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  15009. }
  15010. }
  15011. //
  15012. var dataStart = 0;
  15013. var dataCount = Infinity;
  15014. if ( index !== null ) {
  15015. dataCount = index.count
  15016. } else if ( position !== undefined ) {
  15017. dataCount = position.count;
  15018. }
  15019. var rangeStart = geometry.drawRange.start;
  15020. var rangeCount = geometry.drawRange.count;
  15021. var groupStart = group !== null ? group.start : 0;
  15022. var groupCount = group !== null ? group.count : Infinity;
  15023. var drawStart = Math.max( dataStart, rangeStart, groupStart );
  15024. var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  15025. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  15026. //
  15027. if ( object instanceof THREE.Mesh ) {
  15028. if ( material.wireframe === true ) {
  15029. state.setLineWidth( material.wireframeLinewidth * pixelRatio );
  15030. renderer.setMode( _gl.LINES );
  15031. } else {
  15032. renderer.setMode( _gl.TRIANGLES );
  15033. }
  15034. if ( geometry instanceof THREE.InstancedBufferGeometry && geometry.maxInstancedCount > 0 ) {
  15035. renderer.renderInstances( geometry );
  15036. } else {
  15037. renderer.render( drawStart, drawCount );
  15038. }
  15039. } else if ( object instanceof THREE.Line ) {
  15040. var lineWidth = material.linewidth;
  15041. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  15042. state.setLineWidth( lineWidth * pixelRatio );
  15043. if ( object instanceof THREE.LineSegments ) {
  15044. renderer.setMode( _gl.LINES );
  15045. } else {
  15046. renderer.setMode( _gl.LINE_STRIP );
  15047. }
  15048. renderer.render( drawStart, drawCount );
  15049. } else if ( object instanceof THREE.Points ) {
  15050. renderer.setMode( _gl.POINTS );
  15051. renderer.render( drawStart, drawCount );
  15052. }
  15053. };
  15054. function setupVertexAttributes( material, program, geometry, startIndex ) {
  15055. var extension;
  15056. if ( geometry instanceof THREE.InstancedBufferGeometry ) {
  15057. extension = extensions.get( 'ANGLE_instanced_arrays' );
  15058. if ( extension === null ) {
  15059. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  15060. return;
  15061. }
  15062. }
  15063. if ( startIndex === undefined ) startIndex = 0;
  15064. state.initAttributes();
  15065. var geometryAttributes = geometry.attributes;
  15066. var programAttributes = program.getAttributes();
  15067. var materialDefaultAttributeValues = material.defaultAttributeValues;
  15068. for ( var name in programAttributes ) {
  15069. var programAttribute = programAttributes[ name ];
  15070. if ( programAttribute >= 0 ) {
  15071. var geometryAttribute = geometryAttributes[ name ];
  15072. if ( geometryAttribute !== undefined ) {
  15073. var size = geometryAttribute.itemSize;
  15074. var buffer = objects.getAttributeBuffer( geometryAttribute );
  15075. if ( geometryAttribute instanceof THREE.InterleavedBufferAttribute ) {
  15076. var data = geometryAttribute.data;
  15077. var stride = data.stride;
  15078. var offset = geometryAttribute.offset;
  15079. if ( data instanceof THREE.InstancedInterleavedBuffer ) {
  15080. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  15081. if ( geometry.maxInstancedCount === undefined ) {
  15082. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  15083. }
  15084. } else {
  15085. state.enableAttribute( programAttribute );
  15086. }
  15087. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  15088. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT );
  15089. } else {
  15090. if ( geometryAttribute instanceof THREE.InstancedBufferAttribute ) {
  15091. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  15092. if ( geometry.maxInstancedCount === undefined ) {
  15093. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  15094. }
  15095. } else {
  15096. state.enableAttribute( programAttribute );
  15097. }
  15098. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  15099. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, 0, startIndex * size * 4 ); // 4 bytes per Float32
  15100. }
  15101. } else if ( materialDefaultAttributeValues !== undefined ) {
  15102. var value = materialDefaultAttributeValues[ name ];
  15103. if ( value !== undefined ) {
  15104. switch ( value.length ) {
  15105. case 2:
  15106. _gl.vertexAttrib2fv( programAttribute, value );
  15107. break;
  15108. case 3:
  15109. _gl.vertexAttrib3fv( programAttribute, value );
  15110. break;
  15111. case 4:
  15112. _gl.vertexAttrib4fv( programAttribute, value );
  15113. break;
  15114. default:
  15115. _gl.vertexAttrib1fv( programAttribute, value );
  15116. }
  15117. }
  15118. }
  15119. }
  15120. }
  15121. state.disableUnusedAttributes();
  15122. }
  15123. // Sorting
  15124. function numericalSort ( a, b ) {
  15125. return b[ 0 ] - a[ 0 ];
  15126. }
  15127. function painterSortStable ( a, b ) {
  15128. if ( a.object.renderOrder !== b.object.renderOrder ) {
  15129. return a.object.renderOrder - b.object.renderOrder;
  15130. } else if ( a.material.id !== b.material.id ) {
  15131. return a.material.id - b.material.id;
  15132. } else if ( a.z !== b.z ) {
  15133. return a.z - b.z;
  15134. } else {
  15135. return a.id - b.id;
  15136. }
  15137. }
  15138. function reversePainterSortStable ( a, b ) {
  15139. if ( a.object.renderOrder !== b.object.renderOrder ) {
  15140. return a.object.renderOrder - b.object.renderOrder;
  15141. } if ( a.z !== b.z ) {
  15142. return b.z - a.z;
  15143. } else {
  15144. return a.id - b.id;
  15145. }
  15146. }
  15147. // Rendering
  15148. this.render = function ( scene, camera, renderTarget, forceClear ) {
  15149. if ( camera instanceof THREE.Camera === false ) {
  15150. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  15151. return;
  15152. }
  15153. var fog = scene.fog;
  15154. // reset caching for this frame
  15155. _currentGeometryProgram = '';
  15156. _currentMaterialId = - 1;
  15157. _currentCamera = null;
  15158. // update scene graph
  15159. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  15160. // update camera matrices and frustum
  15161. if ( camera.parent === null ) camera.updateMatrixWorld();
  15162. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  15163. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  15164. _frustum.setFromMatrix( _projScreenMatrix );
  15165. lights.length = 0;
  15166. opaqueObjectsLastIndex = - 1;
  15167. transparentObjectsLastIndex = - 1;
  15168. sprites.length = 0;
  15169. lensFlares.length = 0;
  15170. projectObject( scene, camera );
  15171. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  15172. transparentObjects.length = transparentObjectsLastIndex + 1;
  15173. if ( _this.sortObjects === true ) {
  15174. opaqueObjects.sort( painterSortStable );
  15175. transparentObjects.sort( reversePainterSortStable );
  15176. }
  15177. setupLights( lights, camera );
  15178. //
  15179. shadowMap.render( scene, camera );
  15180. //
  15181. _infoRender.calls = 0;
  15182. _infoRender.vertices = 0;
  15183. _infoRender.faces = 0;
  15184. _infoRender.points = 0;
  15185. this.setRenderTarget( renderTarget );
  15186. if ( this.autoClear || forceClear ) {
  15187. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  15188. }
  15189. //
  15190. if ( scene.overrideMaterial ) {
  15191. var overrideMaterial = scene.overrideMaterial;
  15192. renderObjects( opaqueObjects, camera, lights, fog, overrideMaterial );
  15193. renderObjects( transparentObjects, camera, lights, fog, overrideMaterial );
  15194. } else {
  15195. // opaque pass (front-to-back order)
  15196. state.setBlending( THREE.NoBlending );
  15197. renderObjects( opaqueObjects, camera, lights, fog );
  15198. // transparent pass (back-to-front order)
  15199. renderObjects( transparentObjects, camera, lights, fog );
  15200. }
  15201. // custom render plugins (post pass)
  15202. spritePlugin.render( scene, camera );
  15203. lensFlarePlugin.render( scene, camera, _currentWidth, _currentHeight );
  15204. // Generate mipmap if we're using any kind of mipmap filtering
  15205. if ( renderTarget ) {
  15206. var texture = renderTarget.texture;
  15207. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  15208. texture.minFilter !== THREE.NearestFilter &&
  15209. texture.minFilter !== THREE.LinearFilter ) {
  15210. updateRenderTargetMipmap( renderTarget );
  15211. }
  15212. }
  15213. // Ensure depth buffer writing is enabled so it can be cleared on next render
  15214. state.setDepthTest( true );
  15215. state.setDepthWrite( true );
  15216. state.setColorWrite( true );
  15217. // _gl.finish();
  15218. };
  15219. function pushRenderItem( object, geometry, material, z, group ) {
  15220. var array, index;
  15221. // allocate the next position in the appropriate array
  15222. if ( material.transparent ) {
  15223. array = transparentObjects;
  15224. index = ++ transparentObjectsLastIndex;
  15225. } else {
  15226. array = opaqueObjects;
  15227. index = ++ opaqueObjectsLastIndex;
  15228. }
  15229. // recycle existing render item or grow the array
  15230. var renderItem = array[ index ];
  15231. if ( renderItem !== undefined ) {
  15232. renderItem.id = object.id;
  15233. renderItem.object = object;
  15234. renderItem.geometry = geometry;
  15235. renderItem.material = material;
  15236. renderItem.z = _vector3.z;
  15237. renderItem.group = group;
  15238. } else {
  15239. renderItem = {
  15240. id: object.id,
  15241. object: object,
  15242. geometry: geometry,
  15243. material: material,
  15244. z: _vector3.z,
  15245. group: group
  15246. };
  15247. // assert( index === array.length );
  15248. array.push( renderItem );
  15249. }
  15250. }
  15251. function projectObject( object, camera ) {
  15252. if ( object.visible === false ) return;
  15253. if ( object.layers.test( camera.layers ) ) {
  15254. if ( object instanceof THREE.Light ) {
  15255. lights.push( object );
  15256. } else if ( object instanceof THREE.Sprite ) {
  15257. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  15258. sprites.push( object );
  15259. }
  15260. } else if ( object instanceof THREE.LensFlare ) {
  15261. lensFlares.push( object );
  15262. } else if ( object instanceof THREE.ImmediateRenderObject ) {
  15263. if ( _this.sortObjects === true ) {
  15264. _vector3.setFromMatrixPosition( object.matrixWorld );
  15265. _vector3.applyProjection( _projScreenMatrix );
  15266. }
  15267. pushRenderItem( object, null, object.material, _vector3.z, null );
  15268. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) {
  15269. if ( object instanceof THREE.SkinnedMesh ) {
  15270. object.skeleton.update();
  15271. }
  15272. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  15273. var material = object.material;
  15274. if ( material.visible === true ) {
  15275. if ( _this.sortObjects === true ) {
  15276. _vector3.setFromMatrixPosition( object.matrixWorld );
  15277. _vector3.applyProjection( _projScreenMatrix );
  15278. }
  15279. var geometry = objects.update( object );
  15280. if ( material instanceof THREE.MeshFaceMaterial ) {
  15281. var groups = geometry.groups;
  15282. var materials = material.materials;
  15283. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  15284. var group = groups[ i ];
  15285. var groupMaterial = materials[ group.materialIndex ];
  15286. if ( groupMaterial.visible === true ) {
  15287. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  15288. }
  15289. }
  15290. } else {
  15291. pushRenderItem( object, geometry, material, _vector3.z, null );
  15292. }
  15293. }
  15294. }
  15295. }
  15296. }
  15297. var children = object.children;
  15298. for ( var i = 0, l = children.length; i < l; i ++ ) {
  15299. projectObject( children[ i ], camera );
  15300. }
  15301. }
  15302. function renderObjects( renderList, camera, lights, fog, overrideMaterial ) {
  15303. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  15304. var renderItem = renderList[ i ];
  15305. var object = renderItem.object;
  15306. var geometry = renderItem.geometry;
  15307. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  15308. var group = renderItem.group;
  15309. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  15310. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  15311. if ( object instanceof THREE.ImmediateRenderObject ) {
  15312. setMaterial( material );
  15313. var program = setProgram( camera, lights, fog, material, object );
  15314. _currentGeometryProgram = '';
  15315. object.render( function ( object ) {
  15316. _this.renderBufferImmediate( object, program, material );
  15317. } );
  15318. } else {
  15319. _this.renderBufferDirect( camera, lights, fog, geometry, material, object, group );
  15320. }
  15321. }
  15322. }
  15323. function initMaterial( material, lights, fog, object ) {
  15324. var materialProperties = properties.get( material );
  15325. var parameters = programCache.getParameters( material, _lights, fog, object );
  15326. var code = programCache.getProgramCode( material, parameters );
  15327. var program = materialProperties.program;
  15328. var programChange = true;
  15329. if ( program === undefined ) {
  15330. // new material
  15331. material.addEventListener( 'dispose', onMaterialDispose );
  15332. } else if ( program.code !== code ) {
  15333. // changed glsl or parameters
  15334. releaseMaterialProgramReference( material );
  15335. } else if ( parameters.shaderID !== undefined ) {
  15336. // same glsl and uniform list
  15337. return;
  15338. } else {
  15339. // only rebuild uniform list
  15340. programChange = false;
  15341. }
  15342. if ( programChange ) {
  15343. if ( parameters.shaderID ) {
  15344. var shader = THREE.ShaderLib[ parameters.shaderID ];
  15345. materialProperties.__webglShader = {
  15346. name: material.type,
  15347. uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
  15348. vertexShader: shader.vertexShader,
  15349. fragmentShader: shader.fragmentShader
  15350. };
  15351. } else {
  15352. materialProperties.__webglShader = {
  15353. name: material.type,
  15354. uniforms: material.uniforms,
  15355. vertexShader: material.vertexShader,
  15356. fragmentShader: material.fragmentShader
  15357. };
  15358. }
  15359. material.__webglShader = materialProperties.__webglShader;
  15360. program = programCache.acquireProgram( material, parameters, code );
  15361. materialProperties.program = program;
  15362. material.program = program;
  15363. }
  15364. var attributes = program.getAttributes();
  15365. if ( material.morphTargets ) {
  15366. material.numSupportedMorphTargets = 0;
  15367. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  15368. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  15369. material.numSupportedMorphTargets ++;
  15370. }
  15371. }
  15372. }
  15373. if ( material.morphNormals ) {
  15374. material.numSupportedMorphNormals = 0;
  15375. for ( i = 0; i < _this.maxMorphNormals; i ++ ) {
  15376. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  15377. material.numSupportedMorphNormals ++;
  15378. }
  15379. }
  15380. }
  15381. materialProperties.uniformsList = [];
  15382. var uniforms = materialProperties.__webglShader.uniforms,
  15383. uniformLocations = materialProperties.program.getUniforms();
  15384. for ( var u in uniforms ) {
  15385. var location = uniformLocations[ u ];
  15386. if ( location ) {
  15387. materialProperties.uniformsList.push( [ materialProperties.__webglShader.uniforms[ u ], location ] );
  15388. }
  15389. }
  15390. if ( material instanceof THREE.MeshPhongMaterial ||
  15391. material instanceof THREE.MeshLambertMaterial ||
  15392. material instanceof THREE.MeshPhysicalMaterial ||
  15393. material.lights ) {
  15394. // store the light setup it was created for
  15395. materialProperties.lightsHash = _lights.hash;
  15396. // wire up the material to this renderer's lighting state
  15397. uniforms.ambientLightColor.value = _lights.ambient;
  15398. uniforms.directionalLights.value = _lights.directional;
  15399. uniforms.pointLights.value = _lights.point;
  15400. uniforms.spotLights.value = _lights.spot;
  15401. uniforms.hemisphereLights.value = _lights.hemi;
  15402. }
  15403. }
  15404. function setMaterial( material ) {
  15405. setMaterialFaces( material );
  15406. if ( material.transparent === true ) {
  15407. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha );
  15408. } else {
  15409. state.setBlending( THREE.NoBlending );
  15410. }
  15411. state.setDepthFunc( material.depthFunc );
  15412. state.setDepthTest( material.depthTest );
  15413. state.setDepthWrite( material.depthWrite );
  15414. state.setColorWrite( material.colorWrite );
  15415. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  15416. }
  15417. function setMaterialFaces( material ) {
  15418. material.side !== THREE.DoubleSide ? state.enable( _gl.CULL_FACE ) : state.disable( _gl.CULL_FACE );
  15419. state.setFlipSided( material.side === THREE.BackSide );
  15420. }
  15421. function setProgram( camera, lights, fog, material, object ) {
  15422. _usedTextureUnits = 0;
  15423. var materialProperties = properties.get( material );
  15424. if ( materialProperties.program === undefined ) {
  15425. material.needsUpdate = true;
  15426. }
  15427. if ( materialProperties.lightsHash !== undefined &&
  15428. materialProperties.lightsHash !== _lights.hash ) {
  15429. material.needsUpdate = true;
  15430. }
  15431. if ( material.needsUpdate ) {
  15432. initMaterial( material, lights, fog, object );
  15433. material.needsUpdate = false;
  15434. }
  15435. var refreshProgram = false;
  15436. var refreshMaterial = false;
  15437. var refreshLights = false;
  15438. var program = materialProperties.program,
  15439. p_uniforms = program.getUniforms(),
  15440. m_uniforms = materialProperties.__webglShader.uniforms;
  15441. if ( program.id !== _currentProgram ) {
  15442. _gl.useProgram( program.program );
  15443. _currentProgram = program.id;
  15444. refreshProgram = true;
  15445. refreshMaterial = true;
  15446. refreshLights = true;
  15447. }
  15448. if ( material.id !== _currentMaterialId ) {
  15449. _currentMaterialId = material.id;
  15450. refreshMaterial = true;
  15451. }
  15452. if ( refreshProgram || camera !== _currentCamera ) {
  15453. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  15454. if ( capabilities.logarithmicDepthBuffer ) {
  15455. _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  15456. }
  15457. if ( camera !== _currentCamera ) {
  15458. _currentCamera = camera;
  15459. // lighting uniforms depend on the camera so enforce an update
  15460. // now, in case this material supports lights - or later, when
  15461. // the next material that does gets activated:
  15462. refreshMaterial = true; // set to true on material change
  15463. refreshLights = true; // remains set until update done
  15464. }
  15465. // load material specific uniforms
  15466. // (shader material also gets them for the sake of genericity)
  15467. if ( material instanceof THREE.ShaderMaterial ||
  15468. material instanceof THREE.MeshPhongMaterial ||
  15469. material instanceof THREE.MeshPhysicalMaterial ||
  15470. material.envMap ) {
  15471. if ( p_uniforms.cameraPosition !== undefined ) {
  15472. _vector3.setFromMatrixPosition( camera.matrixWorld );
  15473. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  15474. }
  15475. }
  15476. if ( material instanceof THREE.MeshPhongMaterial ||
  15477. material instanceof THREE.MeshLambertMaterial ||
  15478. material instanceof THREE.MeshBasicMaterial ||
  15479. material instanceof THREE.MeshPhysicalMaterial ||
  15480. material instanceof THREE.ShaderMaterial ||
  15481. material.skinning ) {
  15482. if ( p_uniforms.viewMatrix !== undefined ) {
  15483. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  15484. }
  15485. }
  15486. }
  15487. // skinning uniforms must be set even if material didn't change
  15488. // auto-setting of texture unit for bone texture must go before other textures
  15489. // not sure why, but otherwise weird things happen
  15490. if ( material.skinning ) {
  15491. if ( object.bindMatrix && p_uniforms.bindMatrix !== undefined ) {
  15492. _gl.uniformMatrix4fv( p_uniforms.bindMatrix, false, object.bindMatrix.elements );
  15493. }
  15494. if ( object.bindMatrixInverse && p_uniforms.bindMatrixInverse !== undefined ) {
  15495. _gl.uniformMatrix4fv( p_uniforms.bindMatrixInverse, false, object.bindMatrixInverse.elements );
  15496. }
  15497. if ( capabilities.floatVertexTextures && object.skeleton && object.skeleton.useVertexTexture ) {
  15498. if ( p_uniforms.boneTexture !== undefined ) {
  15499. var textureUnit = getTextureUnit();
  15500. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  15501. _this.setTexture( object.skeleton.boneTexture, textureUnit );
  15502. }
  15503. if ( p_uniforms.boneTextureWidth !== undefined ) {
  15504. _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
  15505. }
  15506. if ( p_uniforms.boneTextureHeight !== undefined ) {
  15507. _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
  15508. }
  15509. } else if ( object.skeleton && object.skeleton.boneMatrices ) {
  15510. if ( p_uniforms.boneGlobalMatrices !== undefined ) {
  15511. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
  15512. }
  15513. }
  15514. }
  15515. if ( refreshMaterial ) {
  15516. if ( material instanceof THREE.MeshPhongMaterial ||
  15517. material instanceof THREE.MeshLambertMaterial ||
  15518. material instanceof THREE.MeshPhysicalMaterial ||
  15519. material.lights ) {
  15520. // the current material requires lighting info
  15521. // note: all lighting uniforms are always set correctly
  15522. // they simply reference the renderer's state for their
  15523. // values
  15524. //
  15525. // use the current material's .needsUpdate flags to set
  15526. // the GL state when required
  15527. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  15528. }
  15529. // refresh uniforms common to several materials
  15530. if ( fog && material.fog ) {
  15531. refreshUniformsFog( m_uniforms, fog );
  15532. }
  15533. if ( material instanceof THREE.MeshBasicMaterial ||
  15534. material instanceof THREE.MeshLambertMaterial ||
  15535. material instanceof THREE.MeshPhongMaterial ||
  15536. material instanceof THREE.MeshPhysicalMaterial ) {
  15537. refreshUniformsCommon( m_uniforms, material );
  15538. }
  15539. // refresh single material specific uniforms
  15540. if ( material instanceof THREE.LineBasicMaterial ) {
  15541. refreshUniformsLine( m_uniforms, material );
  15542. } else if ( material instanceof THREE.LineDashedMaterial ) {
  15543. refreshUniformsLine( m_uniforms, material );
  15544. refreshUniformsDash( m_uniforms, material );
  15545. } else if ( material instanceof THREE.PointsMaterial ) {
  15546. refreshUniformsPoints( m_uniforms, material );
  15547. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  15548. refreshUniformsPhong( m_uniforms, material );
  15549. } else if ( material instanceof THREE.MeshPhysicalMaterial ) {
  15550. refreshUniformsPhysical( m_uniforms, material );
  15551. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  15552. m_uniforms.mNear.value = camera.near;
  15553. m_uniforms.mFar.value = camera.far;
  15554. m_uniforms.opacity.value = material.opacity;
  15555. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  15556. m_uniforms.opacity.value = material.opacity;
  15557. }
  15558. if ( shadowMap.enabled ) {
  15559. if ( object.receiveShadow && ! material._shadowPass ) {
  15560. refreshUniformsShadow( m_uniforms, lights, camera );
  15561. }
  15562. }
  15563. // load common uniforms
  15564. loadUniformsGeneric( materialProperties.uniformsList );
  15565. }
  15566. loadUniformsMatrices( p_uniforms, object );
  15567. if ( p_uniforms.modelMatrix !== undefined ) {
  15568. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  15569. }
  15570. return program;
  15571. }
  15572. // Uniforms (refresh uniforms objects)
  15573. function refreshUniformsCommon ( uniforms, material ) {
  15574. uniforms.opacity.value = material.opacity;
  15575. uniforms.diffuse.value = material.color;
  15576. if ( material.emissive ) {
  15577. uniforms.emissive.value = material.emissive;
  15578. }
  15579. uniforms.map.value = material.map;
  15580. uniforms.specularMap.value = material.specularMap;
  15581. uniforms.alphaMap.value = material.alphaMap;
  15582. if ( material.aoMap ) {
  15583. uniforms.aoMap.value = material.aoMap;
  15584. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15585. }
  15586. // uv repeat and offset setting priorities
  15587. // 1. color map
  15588. // 2. specular map
  15589. // 3. normal map
  15590. // 4. bump map
  15591. // 5. alpha map
  15592. // 6. emissive map
  15593. var uvScaleMap;
  15594. if ( material.map ) {
  15595. uvScaleMap = material.map;
  15596. } else if ( material.specularMap ) {
  15597. uvScaleMap = material.specularMap;
  15598. } else if ( material.displacementMap ) {
  15599. uvScaleMap = material.displacementMap;
  15600. } else if ( material.normalMap ) {
  15601. uvScaleMap = material.normalMap;
  15602. } else if ( material.bumpMap ) {
  15603. uvScaleMap = material.bumpMap;
  15604. } else if ( material.alphaMap ) {
  15605. uvScaleMap = material.alphaMap;
  15606. } else if ( material.emissiveMap ) {
  15607. uvScaleMap = material.emissiveMap;
  15608. }
  15609. if ( uvScaleMap !== undefined ) {
  15610. if ( uvScaleMap instanceof THREE.WebGLRenderTarget ) uvScaleMap = uvScaleMap.texture;
  15611. var offset = uvScaleMap.offset;
  15612. var repeat = uvScaleMap.repeat;
  15613. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  15614. }
  15615. uniforms.envMap.value = material.envMap;
  15616. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
  15617. uniforms.reflectivity.value = material.reflectivity;
  15618. uniforms.refractionRatio.value = material.refractionRatio;
  15619. }
  15620. function refreshUniformsLine ( uniforms, material ) {
  15621. uniforms.diffuse.value = material.color;
  15622. uniforms.opacity.value = material.opacity;
  15623. }
  15624. function refreshUniformsDash ( uniforms, material ) {
  15625. uniforms.dashSize.value = material.dashSize;
  15626. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15627. uniforms.scale.value = material.scale;
  15628. }
  15629. function refreshUniformsPoints ( uniforms, material ) {
  15630. uniforms.psColor.value = material.color;
  15631. uniforms.opacity.value = material.opacity;
  15632. uniforms.size.value = material.size * pixelRatio;
  15633. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  15634. uniforms.map.value = material.map;
  15635. if ( material.map !== null ) {
  15636. var offset = material.map.offset;
  15637. var repeat = material.map.repeat;
  15638. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  15639. }
  15640. }
  15641. function refreshUniformsFog ( uniforms, fog ) {
  15642. uniforms.fogColor.value = fog.color;
  15643. if ( fog instanceof THREE.Fog ) {
  15644. uniforms.fogNear.value = fog.near;
  15645. uniforms.fogFar.value = fog.far;
  15646. } else if ( fog instanceof THREE.FogExp2 ) {
  15647. uniforms.fogDensity.value = fog.density;
  15648. }
  15649. }
  15650. function refreshUniformsPhong ( uniforms, material ) {
  15651. uniforms.specular.value = material.specular;
  15652. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15653. if ( material.lightMap ) {
  15654. uniforms.lightMap.value = material.lightMap;
  15655. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15656. }
  15657. if ( material.emissiveMap ) {
  15658. uniforms.emissiveMap.value = material.emissiveMap;
  15659. }
  15660. if ( material.bumpMap ) {
  15661. uniforms.bumpMap.value = material.bumpMap;
  15662. uniforms.bumpScale.value = material.bumpScale;
  15663. }
  15664. if ( material.normalMap ) {
  15665. uniforms.normalMap.value = material.normalMap;
  15666. uniforms.normalScale.value.copy( material.normalScale );
  15667. }
  15668. if ( material.displacementMap ) {
  15669. uniforms.displacementMap.value = material.displacementMap;
  15670. uniforms.displacementScale.value = material.displacementScale;
  15671. uniforms.displacementBias.value = material.displacementBias;
  15672. }
  15673. }
  15674. function refreshUniformsPhysical ( uniforms, material ) {
  15675. uniforms.roughness.value = material.roughness;
  15676. //uniforms.reflectivity.value = material.reflectivity; // part of uniforms common
  15677. uniforms.metalness.value = material.metalness;
  15678. if ( material.roughnessMap ) {
  15679. uniforms.roughnessMap.value = material.roughnessMap;
  15680. }
  15681. if ( material.reflectivityMap ) {
  15682. uniforms.reflectivityMap.value = material.reflectivityMap;
  15683. }
  15684. if ( material.metalnessMap ) {
  15685. uniforms.metalnessMap.value = material.metalnessMap;
  15686. }
  15687. if ( material.lightMap ) {
  15688. uniforms.lightMap.value = material.lightMap;
  15689. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15690. }
  15691. if ( material.emissiveMap ) {
  15692. uniforms.emissiveMap.value = material.emissiveMap;
  15693. }
  15694. if ( material.bumpMap ) {
  15695. uniforms.bumpMap.value = material.bumpMap;
  15696. uniforms.bumpScale.value = material.bumpScale;
  15697. }
  15698. if ( material.normalMap ) {
  15699. uniforms.normalMap.value = material.normalMap;
  15700. uniforms.normalScale.value.copy( material.normalScale );
  15701. }
  15702. if ( material.displacementMap ) {
  15703. uniforms.displacementMap.value = material.displacementMap;
  15704. uniforms.displacementScale.value = material.displacementScale;
  15705. uniforms.displacementBias.value = material.displacementBias;
  15706. }
  15707. if ( material.envMap ) {
  15708. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15709. uniforms.envMapIntensity.value = material.envMapIntensity;
  15710. }
  15711. }
  15712. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15713. function markUniformsLightsNeedsUpdate ( uniforms, value ) {
  15714. uniforms.ambientLightColor.needsUpdate = value;
  15715. uniforms.directionalLights.needsUpdate = value;
  15716. uniforms.pointLights.needsUpdate = value;
  15717. uniforms.spotLights.needsUpdate = value;
  15718. uniforms.hemisphereLights.needsUpdate = value;
  15719. }
  15720. function refreshUniformsShadow ( uniforms, lights, camera ) {
  15721. if ( uniforms.shadowMatrix ) {
  15722. var j = 0;
  15723. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  15724. var light = lights[ i ];
  15725. if ( light.castShadow === true ) {
  15726. if ( light instanceof THREE.PointLight || light instanceof THREE.SpotLight || light instanceof THREE.DirectionalLight ) {
  15727. var shadow = light.shadow;
  15728. if ( light instanceof THREE.PointLight ) {
  15729. // for point lights we set the shadow matrix to be a translation-only matrix
  15730. // equal to inverse of the light's position
  15731. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  15732. shadow.matrix.identity().setPosition( _vector3 );
  15733. // for point lights we set the sign of the shadowDarkness uniform to be negative
  15734. uniforms.shadowDarkness.value[ j ] = - shadow.darkness;
  15735. } else {
  15736. uniforms.shadowDarkness.value[ j ] = shadow.darkness;
  15737. }
  15738. uniforms.shadowMatrix.value[ j ] = shadow.matrix;
  15739. uniforms.shadowMap.value[ j ] = shadow.map;
  15740. uniforms.shadowMapSize.value[ j ] = shadow.mapSize;
  15741. uniforms.shadowBias.value[ j ] = shadow.bias;
  15742. j ++;
  15743. }
  15744. }
  15745. }
  15746. }
  15747. }
  15748. // Uniforms (load to GPU)
  15749. function loadUniformsMatrices ( uniforms, object ) {
  15750. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object.modelViewMatrix.elements );
  15751. if ( uniforms.normalMatrix ) {
  15752. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object.normalMatrix.elements );
  15753. }
  15754. }
  15755. function getTextureUnit() {
  15756. var textureUnit = _usedTextureUnits;
  15757. if ( textureUnit >= capabilities.maxTextures ) {
  15758. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  15759. }
  15760. _usedTextureUnits += 1;
  15761. return textureUnit;
  15762. }
  15763. function loadUniformsGeneric ( uniforms ) {
  15764. var texture, textureUnit;
  15765. for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {
  15766. var uniform = uniforms[ j ][ 0 ];
  15767. // needsUpdate property is not added to all uniforms.
  15768. if ( uniform.needsUpdate === false ) continue;
  15769. var type = uniform.type;
  15770. var value = uniform.value;
  15771. var location = uniforms[ j ][ 1 ];
  15772. switch ( type ) {
  15773. case '1i':
  15774. _gl.uniform1i( location, value );
  15775. break;
  15776. case '1f':
  15777. _gl.uniform1f( location, value );
  15778. break;
  15779. case '2f':
  15780. _gl.uniform2f( location, value[ 0 ], value[ 1 ] );
  15781. break;
  15782. case '3f':
  15783. _gl.uniform3f( location, value[ 0 ], value[ 1 ], value[ 2 ] );
  15784. break;
  15785. case '4f':
  15786. _gl.uniform4f( location, value[ 0 ], value[ 1 ], value[ 2 ], value[ 3 ] );
  15787. break;
  15788. case '1iv':
  15789. _gl.uniform1iv( location, value );
  15790. break;
  15791. case '3iv':
  15792. _gl.uniform3iv( location, value );
  15793. break;
  15794. case '1fv':
  15795. _gl.uniform1fv( location, value );
  15796. break;
  15797. case '2fv':
  15798. _gl.uniform2fv( location, value );
  15799. break;
  15800. case '3fv':
  15801. _gl.uniform3fv( location, value );
  15802. break;
  15803. case '4fv':
  15804. _gl.uniform4fv( location, value );
  15805. break;
  15806. case 'Matrix3fv':
  15807. _gl.uniformMatrix3fv( location, false, value );
  15808. break;
  15809. case 'Matrix4fv':
  15810. _gl.uniformMatrix4fv( location, false, value );
  15811. break;
  15812. //
  15813. case 'i':
  15814. // single integer
  15815. _gl.uniform1i( location, value );
  15816. break;
  15817. case 'f':
  15818. // single float
  15819. _gl.uniform1f( location, value );
  15820. break;
  15821. case 'v2':
  15822. // single THREE.Vector2
  15823. _gl.uniform2f( location, value.x, value.y );
  15824. break;
  15825. case 'v3':
  15826. // single THREE.Vector3
  15827. _gl.uniform3f( location, value.x, value.y, value.z );
  15828. break;
  15829. case 'v4':
  15830. // single THREE.Vector4
  15831. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  15832. break;
  15833. case 'c':
  15834. // single THREE.Color
  15835. _gl.uniform3f( location, value.r, value.g, value.b );
  15836. break;
  15837. case 's':
  15838. // TODO: Optimize this.
  15839. for( var propertyName in uniform.properties ) {
  15840. var property = uniform.properties[ propertyName ];
  15841. var locationProperty = location[ propertyName ];
  15842. var valueProperty = value[ propertyName ];
  15843. switch( property.type ) {
  15844. case 'f':
  15845. _gl.uniform1f( locationProperty, valueProperty );
  15846. break;
  15847. case 'v2':
  15848. _gl.uniform2f( locationProperty, valueProperty.x, valueProperty.y );
  15849. break;
  15850. case 'v3':
  15851. _gl.uniform3f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z );
  15852. break;
  15853. case 'v4':
  15854. _gl.uniform4f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z, valueProperty.w );
  15855. break;
  15856. case 'c':
  15857. _gl.uniform3f( locationProperty, valueProperty.r, valueProperty.g, valueProperty.b );
  15858. break;
  15859. };
  15860. }
  15861. break;
  15862. case 'sa':
  15863. // TODO: Optimize this.
  15864. for( var i = 0; i < value.length; i ++ ) {
  15865. for( var propertyName in uniform.properties ) {
  15866. var property = uniform.properties[ propertyName ];
  15867. var locationProperty = location[ i ][ propertyName ];
  15868. var valueProperty = value[i][ propertyName ];
  15869. switch( property.type ) {
  15870. case 'f':
  15871. _gl.uniform1f( locationProperty, valueProperty );
  15872. break;
  15873. case 'v2':
  15874. _gl.uniform2f( locationProperty, valueProperty.x, valueProperty.y );
  15875. break;
  15876. case 'v3':
  15877. _gl.uniform3f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z );
  15878. break;
  15879. case 'v4':
  15880. _gl.uniform4f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z, valueProperty.w );
  15881. break;
  15882. case 'c':
  15883. _gl.uniform3f( locationProperty, valueProperty.r, valueProperty.g, valueProperty.b );
  15884. break;
  15885. };
  15886. }
  15887. }
  15888. break;
  15889. case 'iv1':
  15890. // flat array of integers (JS or typed array)
  15891. _gl.uniform1iv( location, value );
  15892. break;
  15893. case 'iv':
  15894. // flat array of integers with 3 x N size (JS or typed array)
  15895. _gl.uniform3iv( location, value );
  15896. break;
  15897. case 'fv1':
  15898. // flat array of floats (JS or typed array)
  15899. _gl.uniform1fv( location, value );
  15900. break;
  15901. case 'fv':
  15902. // flat array of floats with 3 x N size (JS or typed array)
  15903. _gl.uniform3fv( location, value );
  15904. break;
  15905. case 'v2v':
  15906. // array of THREE.Vector2
  15907. if ( uniform._array === undefined ) {
  15908. uniform._array = new Float32Array( 2 * value.length );
  15909. }
  15910. for ( var i = 0, i2 = 0, il = value.length; i < il; i ++, i2 += 2 ) {
  15911. uniform._array[ i2 + 0 ] = value[ i ].x;
  15912. uniform._array[ i2 + 1 ] = value[ i ].y;
  15913. }
  15914. _gl.uniform2fv( location, uniform._array );
  15915. break;
  15916. case 'v3v':
  15917. // array of THREE.Vector3
  15918. if ( uniform._array === undefined ) {
  15919. uniform._array = new Float32Array( 3 * value.length );
  15920. }
  15921. for ( var i = 0, i3 = 0, il = value.length; i < il; i ++, i3 += 3 ) {
  15922. uniform._array[ i3 + 0 ] = value[ i ].x;
  15923. uniform._array[ i3 + 1 ] = value[ i ].y;
  15924. uniform._array[ i3 + 2 ] = value[ i ].z;
  15925. }
  15926. _gl.uniform3fv( location, uniform._array );
  15927. break;
  15928. case 'v4v':
  15929. // array of THREE.Vector4
  15930. if ( uniform._array === undefined ) {
  15931. uniform._array = new Float32Array( 4 * value.length );
  15932. }
  15933. for ( var i = 0, i4 = 0, il = value.length; i < il; i ++, i4 += 4 ) {
  15934. uniform._array[ i4 + 0 ] = value[ i ].x;
  15935. uniform._array[ i4 + 1 ] = value[ i ].y;
  15936. uniform._array[ i4 + 2 ] = value[ i ].z;
  15937. uniform._array[ i4 + 3 ] = value[ i ].w;
  15938. }
  15939. _gl.uniform4fv( location, uniform._array );
  15940. break;
  15941. case 'm3':
  15942. // single THREE.Matrix3
  15943. _gl.uniformMatrix3fv( location, false, value.elements );
  15944. break;
  15945. case 'm3v':
  15946. // array of THREE.Matrix3
  15947. if ( uniform._array === undefined ) {
  15948. uniform._array = new Float32Array( 9 * value.length );
  15949. }
  15950. for ( var i = 0, il = value.length; i < il; i ++ ) {
  15951. value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
  15952. }
  15953. _gl.uniformMatrix3fv( location, false, uniform._array );
  15954. break;
  15955. case 'm4':
  15956. // single THREE.Matrix4
  15957. _gl.uniformMatrix4fv( location, false, value.elements );
  15958. break;
  15959. case 'm4v':
  15960. // array of THREE.Matrix4
  15961. if ( uniform._array === undefined ) {
  15962. uniform._array = new Float32Array( 16 * value.length );
  15963. }
  15964. for ( var i = 0, il = value.length; i < il; i ++ ) {
  15965. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  15966. }
  15967. _gl.uniformMatrix4fv( location, false, uniform._array );
  15968. break;
  15969. case 't':
  15970. // single THREE.Texture (2d or cube)
  15971. texture = value;
  15972. textureUnit = getTextureUnit();
  15973. _gl.uniform1i( location, textureUnit );
  15974. if ( ! texture ) continue;
  15975. if ( texture instanceof THREE.CubeTexture ||
  15976. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  15977. // CompressedTexture can have Array in image :/
  15978. setCubeTexture( texture, textureUnit );
  15979. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  15980. setCubeTextureDynamic( texture.texture, textureUnit );
  15981. } else if ( texture instanceof THREE.WebGLRenderTarget ) {
  15982. _this.setTexture( texture.texture, textureUnit );
  15983. } else {
  15984. _this.setTexture( texture, textureUnit );
  15985. }
  15986. break;
  15987. case 'tv':
  15988. // array of THREE.Texture (2d or cube)
  15989. if ( uniform._array === undefined ) {
  15990. uniform._array = [];
  15991. }
  15992. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  15993. uniform._array[ i ] = getTextureUnit();
  15994. }
  15995. _gl.uniform1iv( location, uniform._array );
  15996. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  15997. texture = uniform.value[ i ];
  15998. textureUnit = uniform._array[ i ];
  15999. if ( ! texture ) continue;
  16000. if ( texture instanceof THREE.CubeTexture ||
  16001. ( texture.image instanceof Array && texture.image.length === 6 ) ) {
  16002. // CompressedTexture can have Array in image :/
  16003. setCubeTexture( texture, textureUnit );
  16004. } else if ( texture instanceof THREE.WebGLRenderTarget ) {
  16005. _this.setTexture( texture.texture, textureUnit );
  16006. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  16007. setCubeTextureDynamic( texture.texture, textureUnit );
  16008. } else {
  16009. _this.setTexture( texture, textureUnit );
  16010. }
  16011. }
  16012. break;
  16013. default:
  16014. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  16015. }
  16016. }
  16017. }
  16018. function setupLights ( lights, camera ) {
  16019. var l, ll, light,
  16020. r = 0, g = 0, b = 0,
  16021. color,
  16022. intensity,
  16023. distance,
  16024. viewMatrix = camera.matrixWorldInverse,
  16025. directionalLength = 0,
  16026. pointLength = 0,
  16027. spotLength = 0,
  16028. hemiLength = 0;
  16029. _lights.shadows = 0;
  16030. _lights.shadowsPointLight = 0;
  16031. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  16032. light = lights[ l ];
  16033. color = light.color;
  16034. intensity = light.intensity;
  16035. distance = light.distance;
  16036. if ( light instanceof THREE.AmbientLight ) {
  16037. r += color.r;
  16038. g += color.g;
  16039. b += color.b;
  16040. } else if ( light instanceof THREE.DirectionalLight ) {
  16041. if( ! light.__webglUniforms ) {
  16042. light.__webglUniforms = {
  16043. direction: new THREE.Vector3(),
  16044. color: new THREE.Color()
  16045. }
  16046. }
  16047. var uniforms = light.__webglUniforms;
  16048. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  16049. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  16050. uniforms.direction.sub( _vector3 );
  16051. uniforms.direction.transformDirection( viewMatrix );
  16052. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  16053. _lights.directional[ directionalLength ++ ] = uniforms;
  16054. if ( light.castShadow ) _lights.shadows ++;
  16055. } else if ( light instanceof THREE.PointLight ) {
  16056. if( ! light.__webglUniforms ) {
  16057. light.__webglUniforms = {
  16058. position: new THREE.Vector3(),
  16059. color: new THREE.Color(),
  16060. distance: 0,
  16061. decay: 0
  16062. }
  16063. }
  16064. var uniforms = light.__webglUniforms;
  16065. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  16066. uniforms.position.applyMatrix4( viewMatrix );
  16067. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  16068. uniforms.distance = light.distance;
  16069. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  16070. _lights.point[ pointLength ++ ] = uniforms;
  16071. if ( light.castShadow ) {
  16072. _lights.shadows ++;
  16073. _lights.shadowsPointLight ++;
  16074. }
  16075. } else if ( light instanceof THREE.SpotLight ) {
  16076. if( ! light.__webglUniforms ) {
  16077. light.__webglUniforms = {
  16078. position: new THREE.Vector3(),
  16079. direction: new THREE.Vector3(),
  16080. color: new THREE.Color(),
  16081. distance: 0,
  16082. decay: 0,
  16083. angleCos: 0
  16084. }
  16085. }
  16086. var uniforms = light.__webglUniforms;
  16087. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  16088. uniforms.position.applyMatrix4( viewMatrix );
  16089. uniforms.color.copy( color ).multiplyScalar( intensity );
  16090. uniforms.distance = distance;
  16091. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  16092. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  16093. uniforms.direction.sub( _vector3 );
  16094. uniforms.direction.transformDirection( viewMatrix );
  16095. uniforms.angleCos = Math.cos( light.angle );
  16096. uniforms.exponent = light.exponent;
  16097. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  16098. _lights.spot[ spotLength ++ ] = uniforms;
  16099. if ( light.castShadow ) _lights.shadows ++;
  16100. } else if ( light instanceof THREE.HemisphereLight ) {
  16101. if( ! light.__webglUniforms ) {
  16102. light.__webglUniforms = {
  16103. direction: new THREE.Vector3(),
  16104. skyColor: new THREE.Color(),
  16105. groundColor: new THREE.Color()
  16106. }
  16107. }
  16108. var uniforms = light.__webglUniforms;
  16109. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  16110. uniforms.direction.transformDirection( viewMatrix );
  16111. uniforms.direction.normalize();
  16112. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  16113. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  16114. _lights.hemi[ hemiLength ++ ] = uniforms;
  16115. }
  16116. }
  16117. _lights.ambient[ 0 ] = r;
  16118. _lights.ambient[ 1 ] = g;
  16119. _lights.ambient[ 2 ] = b;
  16120. _lights.directional.length = directionalLength;
  16121. _lights.point.length = pointLength;
  16122. _lights.spot.length = spotLength;
  16123. _lights.hemi.length = hemiLength;
  16124. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength;
  16125. }
  16126. // GL state setting
  16127. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  16128. if ( cullFace === THREE.CullFaceNone ) {
  16129. state.disable( _gl.CULL_FACE );
  16130. } else {
  16131. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  16132. _gl.frontFace( _gl.CW );
  16133. } else {
  16134. _gl.frontFace( _gl.CCW );
  16135. }
  16136. if ( cullFace === THREE.CullFaceBack ) {
  16137. _gl.cullFace( _gl.BACK );
  16138. } else if ( cullFace === THREE.CullFaceFront ) {
  16139. _gl.cullFace( _gl.FRONT );
  16140. } else {
  16141. _gl.cullFace( _gl.FRONT_AND_BACK );
  16142. }
  16143. state.enable( _gl.CULL_FACE );
  16144. }
  16145. };
  16146. // Textures
  16147. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  16148. var extension;
  16149. if ( isImagePowerOfTwo ) {
  16150. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  16151. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  16152. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  16153. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  16154. } else {
  16155. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  16156. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  16157. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) {
  16158. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  16159. }
  16160. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  16161. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  16162. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {
  16163. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  16164. }
  16165. }
  16166. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  16167. if ( extension ) {
  16168. if ( texture.type === THREE.FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  16169. if ( texture.type === THREE.HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  16170. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  16171. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) );
  16172. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  16173. }
  16174. }
  16175. }
  16176. function uploadTexture( textureProperties, texture, slot ) {
  16177. if ( textureProperties.__webglInit === undefined ) {
  16178. textureProperties.__webglInit = true;
  16179. texture.addEventListener( 'dispose', onTextureDispose );
  16180. textureProperties.__webglTexture = _gl.createTexture();
  16181. _infoMemory.textures ++;
  16182. }
  16183. state.activeTexture( _gl.TEXTURE0 + slot );
  16184. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  16185. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  16186. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  16187. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  16188. texture.image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  16189. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false ) {
  16190. texture.image = makePowerOfTwo( texture.image );
  16191. }
  16192. var image = texture.image,
  16193. isImagePowerOfTwo = isPowerOfTwo( image ),
  16194. glFormat = paramThreeToGL( texture.format ),
  16195. glType = paramThreeToGL( texture.type );
  16196. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  16197. var mipmap, mipmaps = texture.mipmaps;
  16198. if ( texture instanceof THREE.DataTexture ) {
  16199. // use manually created mipmaps if available
  16200. // if there are no manual mipmaps
  16201. // set 0 level mipmap and then use GL to generate other mipmap levels
  16202. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  16203. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16204. mipmap = mipmaps[ i ];
  16205. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16206. }
  16207. texture.generateMipmaps = false;
  16208. } else {
  16209. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  16210. }
  16211. } else if ( texture instanceof THREE.CompressedTexture ) {
  16212. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16213. mipmap = mipmaps[ i ];
  16214. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  16215. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  16216. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  16217. } else {
  16218. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  16219. }
  16220. } else {
  16221. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16222. }
  16223. }
  16224. } else {
  16225. // regular Texture (image, video, canvas)
  16226. // use manually created mipmaps if available
  16227. // if there are no manual mipmaps
  16228. // set 0 level mipmap and then use GL to generate other mipmap levels
  16229. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  16230. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16231. mipmap = mipmaps[ i ];
  16232. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  16233. }
  16234. texture.generateMipmaps = false;
  16235. } else {
  16236. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  16237. }
  16238. }
  16239. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  16240. textureProperties.__version = texture.version;
  16241. if ( texture.onUpdate ) texture.onUpdate( texture );
  16242. }
  16243. this.setTexture = function ( texture, slot ) {
  16244. var textureProperties = properties.get( texture );
  16245. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  16246. var image = texture.image;
  16247. if ( image === undefined ) {
  16248. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  16249. return;
  16250. }
  16251. if ( image.complete === false ) {
  16252. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  16253. return;
  16254. }
  16255. uploadTexture( textureProperties, texture, slot );
  16256. return;
  16257. }
  16258. state.activeTexture( _gl.TEXTURE0 + slot );
  16259. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  16260. };
  16261. function clampToMaxSize ( image, maxSize ) {
  16262. if ( image.width > maxSize || image.height > maxSize ) {
  16263. // Warning: Scaling through the canvas will only work with images that use
  16264. // premultiplied alpha.
  16265. var scale = maxSize / Math.max( image.width, image.height );
  16266. var canvas = document.createElement( 'canvas' );
  16267. canvas.width = Math.floor( image.width * scale );
  16268. canvas.height = Math.floor( image.height * scale );
  16269. var context = canvas.getContext( '2d' );
  16270. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  16271. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  16272. return canvas;
  16273. }
  16274. return image;
  16275. }
  16276. function isPowerOfTwo( image ) {
  16277. return THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height );
  16278. }
  16279. function textureNeedsPowerOfTwo( texture ) {
  16280. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) return true;
  16281. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) return true;
  16282. return false;
  16283. }
  16284. function makePowerOfTwo( image ) {
  16285. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  16286. var canvas = document.createElement( 'canvas' );
  16287. canvas.width = THREE.Math.nearestPowerOfTwo( image.width );
  16288. canvas.height = THREE.Math.nearestPowerOfTwo( image.height );
  16289. var context = canvas.getContext( '2d' );
  16290. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  16291. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  16292. return canvas;
  16293. }
  16294. return image;
  16295. }
  16296. function setCubeTexture ( texture, slot ) {
  16297. var textureProperties = properties.get( texture );
  16298. if ( texture.image.length === 6 ) {
  16299. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  16300. if ( ! textureProperties.__image__webglTextureCube ) {
  16301. texture.addEventListener( 'dispose', onTextureDispose );
  16302. textureProperties.__image__webglTextureCube = _gl.createTexture();
  16303. _infoMemory.textures ++;
  16304. }
  16305. state.activeTexture( _gl.TEXTURE0 + slot );
  16306. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  16307. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  16308. var isCompressed = texture instanceof THREE.CompressedTexture;
  16309. var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture;
  16310. var cubeImage = [];
  16311. for ( var i = 0; i < 6; i ++ ) {
  16312. if ( _this.autoScaleCubemaps && ! isCompressed && ! isDataTexture ) {
  16313. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  16314. } else {
  16315. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  16316. }
  16317. }
  16318. var image = cubeImage[ 0 ],
  16319. isImagePowerOfTwo = isPowerOfTwo( image ),
  16320. glFormat = paramThreeToGL( texture.format ),
  16321. glType = paramThreeToGL( texture.type );
  16322. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  16323. for ( var i = 0; i < 6; i ++ ) {
  16324. if ( ! isCompressed ) {
  16325. if ( isDataTexture ) {
  16326. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  16327. } else {
  16328. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  16329. }
  16330. } else {
  16331. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  16332. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  16333. mipmap = mipmaps[ j ];
  16334. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  16335. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  16336. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  16337. } else {
  16338. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()" );
  16339. }
  16340. } else {
  16341. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16342. }
  16343. }
  16344. }
  16345. }
  16346. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  16347. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  16348. }
  16349. textureProperties.__version = texture.version;
  16350. if ( texture.onUpdate ) texture.onUpdate( texture );
  16351. } else {
  16352. state.activeTexture( _gl.TEXTURE0 + slot );
  16353. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  16354. }
  16355. }
  16356. }
  16357. function setCubeTextureDynamic ( texture, slot ) {
  16358. state.activeTexture( _gl.TEXTURE0 + slot );
  16359. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  16360. }
  16361. // Render targets
  16362. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  16363. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16364. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  16365. }
  16366. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  16367. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  16368. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  16369. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  16370. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  16371. /* For some reason this is not working. Defaulting to RGBA4.
  16372. } else if ( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  16373. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  16374. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  16375. */
  16376. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  16377. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  16378. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  16379. } else {
  16380. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  16381. }
  16382. }
  16383. this.setRenderTarget = function ( renderTarget ) {
  16384. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  16385. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  16386. var renderTargetProperties = properties.get( renderTarget );
  16387. var textureProperties = properties.get( renderTarget.texture );
  16388. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  16389. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  16390. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  16391. textureProperties.__webglTexture = _gl.createTexture();
  16392. _infoMemory.textures ++;
  16393. // Setup texture, create render and frame buffers
  16394. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget ),
  16395. glFormat = paramThreeToGL( renderTarget.texture.format ),
  16396. glType = paramThreeToGL( renderTarget.texture.type );
  16397. if ( isCube ) {
  16398. renderTargetProperties.__webglFramebuffer = [];
  16399. renderTargetProperties.__webglRenderbuffer = [];
  16400. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  16401. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  16402. for ( var i = 0; i < 6; i ++ ) {
  16403. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  16404. renderTargetProperties.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  16405. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  16406. setupFrameBuffer( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  16407. setupRenderBuffer( renderTargetProperties.__webglRenderbuffer[ i ], renderTarget );
  16408. }
  16409. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  16410. } else {
  16411. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  16412. if ( renderTarget.shareDepthFrom ) {
  16413. renderTargetProperties.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  16414. } else {
  16415. renderTargetProperties.__webglRenderbuffer = _gl.createRenderbuffer();
  16416. }
  16417. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  16418. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  16419. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  16420. setupFrameBuffer( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  16421. if ( renderTarget.shareDepthFrom ) {
  16422. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  16423. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTargetProperties.__webglRenderbuffer );
  16424. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  16425. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTargetProperties.__webglRenderbuffer );
  16426. }
  16427. } else {
  16428. setupRenderBuffer( renderTargetProperties.__webglRenderbuffer, renderTarget );
  16429. }
  16430. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  16431. }
  16432. // Release everything
  16433. if ( isCube ) {
  16434. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  16435. } else {
  16436. state.bindTexture( _gl.TEXTURE_2D, null );
  16437. }
  16438. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  16439. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  16440. }
  16441. var framebuffer, width, height, vx, vy;
  16442. if ( renderTarget ) {
  16443. var renderTargetProperties = properties.get( renderTarget );
  16444. if ( isCube ) {
  16445. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  16446. } else {
  16447. framebuffer = renderTargetProperties.__webglFramebuffer;
  16448. }
  16449. width = renderTarget.width;
  16450. height = renderTarget.height;
  16451. vx = 0;
  16452. vy = 0;
  16453. } else {
  16454. framebuffer = null;
  16455. width = _viewportWidth;
  16456. height = _viewportHeight;
  16457. vx = _viewportX;
  16458. vy = _viewportY;
  16459. }
  16460. if ( framebuffer !== _currentFramebuffer ) {
  16461. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16462. _gl.viewport( vx, vy, width, height );
  16463. _currentFramebuffer = framebuffer;
  16464. }
  16465. if ( isCube ) {
  16466. var textureProperties = properties.get( renderTarget.texture );
  16467. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, 0 );
  16468. }
  16469. _currentWidth = width;
  16470. _currentHeight = height;
  16471. };
  16472. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  16473. if ( renderTarget instanceof THREE.WebGLRenderTarget === false ) {
  16474. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  16475. return;
  16476. }
  16477. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  16478. if ( framebuffer ) {
  16479. var restore = false;
  16480. if ( framebuffer !== _currentFramebuffer ) {
  16481. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16482. restore = true;
  16483. }
  16484. try {
  16485. var texture = renderTarget.texture;
  16486. if ( texture.format !== THREE.RGBAFormat
  16487. && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  16488. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  16489. return;
  16490. }
  16491. if ( texture.type !== THREE.UnsignedByteType
  16492. && paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE )
  16493. && ! ( texture.type === THREE.FloatType && extensions.get( 'WEBGL_color_buffer_float' ) )
  16494. && ! ( texture.type === THREE.HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  16495. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  16496. return;
  16497. }
  16498. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  16499. _gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer );
  16500. } else {
  16501. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  16502. }
  16503. } finally {
  16504. if ( restore ) {
  16505. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  16506. }
  16507. }
  16508. }
  16509. };
  16510. function updateRenderTargetMipmap( renderTarget ) {
  16511. var target = renderTarget instanceof THREE.WebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  16512. var texture = properties.get( renderTarget.texture ).__webglTexture;
  16513. state.bindTexture( target, texture );
  16514. _gl.generateMipmap( target );
  16515. state.bindTexture( target, null );
  16516. }
  16517. // Fallback filters for non-power-of-2 textures
  16518. function filterFallback ( f ) {
  16519. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  16520. return _gl.NEAREST;
  16521. }
  16522. return _gl.LINEAR;
  16523. }
  16524. // Map three.js constants to WebGL constants
  16525. function paramThreeToGL ( p ) {
  16526. var extension;
  16527. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  16528. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  16529. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  16530. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  16531. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  16532. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  16533. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  16534. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  16535. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  16536. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  16537. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  16538. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  16539. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  16540. if ( p === THREE.ByteType ) return _gl.BYTE;
  16541. if ( p === THREE.ShortType ) return _gl.SHORT;
  16542. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  16543. if ( p === THREE.IntType ) return _gl.INT;
  16544. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  16545. if ( p === THREE.FloatType ) return _gl.FLOAT;
  16546. extension = extensions.get( 'OES_texture_half_float' );
  16547. if ( extension !== null ) {
  16548. if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;
  16549. }
  16550. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  16551. if ( p === THREE.RGBFormat ) return _gl.RGB;
  16552. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  16553. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  16554. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  16555. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  16556. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  16557. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  16558. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  16559. if ( p === THREE.OneFactor ) return _gl.ONE;
  16560. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  16561. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  16562. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  16563. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  16564. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  16565. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  16566. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  16567. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  16568. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  16569. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  16570. if ( extension !== null ) {
  16571. if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  16572. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  16573. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  16574. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  16575. }
  16576. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  16577. if ( extension !== null ) {
  16578. if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  16579. if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  16580. if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  16581. if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  16582. }
  16583. extension = extensions.get( 'EXT_blend_minmax' );
  16584. if ( extension !== null ) {
  16585. if ( p === THREE.MinEquation ) return extension.MIN_EXT;
  16586. if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
  16587. }
  16588. return 0;
  16589. }
  16590. };
  16591. // File:src/renderers/WebGLRenderTarget.js
  16592. /**
  16593. * @author szimek / https://github.com/szimek/
  16594. * @author alteredq / http://alteredqualia.com/
  16595. */
  16596. THREE.WebGLRenderTarget = function ( width, height, options ) {
  16597. this.uuid = THREE.Math.generateUUID();
  16598. this.width = width;
  16599. this.height = height;
  16600. options = options || {};
  16601. if ( options.minFilter === undefined ) options.minFilter = THREE.LinearFilter;
  16602. this.texture = new THREE.Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy );
  16603. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  16604. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  16605. this.shareDepthFrom = options.shareDepthFrom !== undefined ? options.shareDepthFrom : null;
  16606. };
  16607. THREE.WebGLRenderTarget.prototype = {
  16608. constructor: THREE.WebGLRenderTarget,
  16609. setSize: function ( width, height ) {
  16610. if ( this.width !== width || this.height !== height ) {
  16611. this.width = width;
  16612. this.height = height;
  16613. this.dispose();
  16614. }
  16615. },
  16616. clone: function () {
  16617. return new this.constructor().copy( this );
  16618. },
  16619. copy: function ( source ) {
  16620. this.width = source.width;
  16621. this.height = source.height;
  16622. this.texture = source.texture.clone();
  16623. this.depthBuffer = source.depthBuffer;
  16624. this.stencilBuffer = source.stencilBuffer;
  16625. this.shareDepthFrom = source.shareDepthFrom;
  16626. return this;
  16627. },
  16628. dispose: function () {
  16629. this.dispatchEvent( { type: 'dispose' } );
  16630. }
  16631. };
  16632. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  16633. // File:src/renderers/WebGLRenderTargetCube.js
  16634. /**
  16635. * @author alteredq / http://alteredqualia.com
  16636. */
  16637. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  16638. THREE.WebGLRenderTarget.call( this, width, height, options );
  16639. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  16640. };
  16641. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  16642. THREE.WebGLRenderTargetCube.prototype.constructor = THREE.WebGLRenderTargetCube;
  16643. // File:src/renderers/webgl/WebGLBufferRenderer.js
  16644. /**
  16645. * @author mrdoob / http://mrdoob.com/
  16646. */
  16647. THREE.WebGLBufferRenderer = function ( _gl, extensions, _infoRender ) {
  16648. var mode;
  16649. function setMode( value ) {
  16650. mode = value;
  16651. }
  16652. function render( start, count ) {
  16653. _gl.drawArrays( mode, start, count );
  16654. _infoRender.calls ++;
  16655. _infoRender.vertices += count;
  16656. if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3;
  16657. }
  16658. function renderInstances( geometry ) {
  16659. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  16660. if ( extension === null ) {
  16661. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  16662. return;
  16663. }
  16664. var position = geometry.attributes.position;
  16665. if ( position instanceof THREE.InterleavedBufferAttribute ) {
  16666. extension.drawArraysInstancedANGLE( mode, 0, position.data.count, geometry.maxInstancedCount );
  16667. } else {
  16668. extension.drawArraysInstancedANGLE( mode, 0, position.count, geometry.maxInstancedCount );
  16669. }
  16670. }
  16671. this.setMode = setMode;
  16672. this.render = render;
  16673. this.renderInstances = renderInstances;
  16674. };
  16675. // File:src/renderers/webgl/WebGLIndexedBufferRenderer.js
  16676. /**
  16677. * @author mrdoob / http://mrdoob.com/
  16678. */
  16679. THREE.WebGLIndexedBufferRenderer = function ( _gl, extensions, _infoRender ) {
  16680. var mode;
  16681. function setMode( value ) {
  16682. mode = value;
  16683. }
  16684. var type, size;
  16685. function setIndex( index ) {
  16686. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  16687. type = _gl.UNSIGNED_INT;
  16688. size = 4;
  16689. } else {
  16690. type = _gl.UNSIGNED_SHORT;
  16691. size = 2;
  16692. }
  16693. }
  16694. function render( start, count ) {
  16695. _gl.drawElements( mode, count, type, start * size );
  16696. _infoRender.calls ++;
  16697. _infoRender.vertices += count;
  16698. if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3;
  16699. }
  16700. function renderInstances( geometry ) {
  16701. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  16702. if ( extension === null ) {
  16703. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  16704. return;
  16705. }
  16706. var index = geometry.index;
  16707. extension.drawElementsInstancedANGLE( mode, index.array.length, type, 0, geometry.maxInstancedCount );
  16708. }
  16709. this.setMode = setMode;
  16710. this.setIndex = setIndex;
  16711. this.render = render;
  16712. this.renderInstances = renderInstances;
  16713. };
  16714. // File:src/renderers/webgl/WebGLExtensions.js
  16715. /**
  16716. * @author mrdoob / http://mrdoob.com/
  16717. */
  16718. THREE.WebGLExtensions = function ( gl ) {
  16719. var extensions = {};
  16720. this.get = function ( name ) {
  16721. if ( extensions[ name ] !== undefined ) {
  16722. return extensions[ name ];
  16723. }
  16724. var extension;
  16725. switch ( name ) {
  16726. case 'EXT_texture_filter_anisotropic':
  16727. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  16728. break;
  16729. case 'WEBGL_compressed_texture_s3tc':
  16730. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  16731. break;
  16732. case 'WEBGL_compressed_texture_pvrtc':
  16733. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  16734. break;
  16735. default:
  16736. extension = gl.getExtension( name );
  16737. }
  16738. if ( extension === null ) {
  16739. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  16740. }
  16741. extensions[ name ] = extension;
  16742. return extension;
  16743. };
  16744. };
  16745. // File:src/renderers/webgl/WebGLCapabilities.js
  16746. THREE.WebGLCapabilities = function ( gl, extensions, parameters ) {
  16747. function getMaxPrecision( precision ) {
  16748. if ( precision === 'highp' ) {
  16749. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  16750. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  16751. return 'highp';
  16752. }
  16753. precision = 'mediump';
  16754. }
  16755. if ( precision === 'mediump' ) {
  16756. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  16757. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  16758. return 'mediump';
  16759. }
  16760. }
  16761. return 'lowp';
  16762. }
  16763. this.getMaxPrecision = getMaxPrecision;
  16764. this.precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  16765. this.logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false;
  16766. this.maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  16767. this.maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  16768. this.maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  16769. this.maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  16770. this.maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  16771. this.maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  16772. this.maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  16773. this.maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  16774. this.vertexTextures = this.maxVertexTextures > 0;
  16775. this.floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  16776. this.floatVertexTextures = this.vertexTextures && this.floatFragmentTextures;
  16777. var _maxPrecision = getMaxPrecision( this.precision );
  16778. if ( _maxPrecision !== this.precision ) {
  16779. console.warn( 'THREE.WebGLRenderer:', this.precision, 'not supported, using', _maxPrecision, 'instead.' );
  16780. this.precision = _maxPrecision;
  16781. }
  16782. if ( this.logarithmicDepthBuffer ) {
  16783. this.logarithmicDepthBuffer = !! extensions.get( 'EXT_frag_depth' );
  16784. }
  16785. };
  16786. // File:src/renderers/webgl/WebGLGeometries.js
  16787. /**
  16788. * @author mrdoob / http://mrdoob.com/
  16789. */
  16790. THREE.WebGLGeometries = function ( gl, properties, info ) {
  16791. var geometries = {};
  16792. function get( object ) {
  16793. var geometry = object.geometry;
  16794. if ( geometries[ geometry.id ] !== undefined ) {
  16795. return geometries[ geometry.id ];
  16796. }
  16797. geometry.addEventListener( 'dispose', onGeometryDispose );
  16798. var buffergeometry;
  16799. if ( geometry instanceof THREE.BufferGeometry ) {
  16800. buffergeometry = geometry;
  16801. } else if ( geometry instanceof THREE.Geometry ) {
  16802. if ( geometry._bufferGeometry === undefined ) {
  16803. geometry._bufferGeometry = new THREE.BufferGeometry().setFromObject( object );
  16804. }
  16805. buffergeometry = geometry._bufferGeometry;
  16806. }
  16807. geometries[ geometry.id ] = buffergeometry;
  16808. info.memory.geometries ++;
  16809. return buffergeometry;
  16810. }
  16811. function onGeometryDispose( event ) {
  16812. var geometry = event.target;
  16813. var buffergeometry = geometries[ geometry.id ];
  16814. if ( buffergeometry.index !== null ) {
  16815. deleteAttribute( buffergeometry.index );
  16816. }
  16817. deleteAttributes( buffergeometry.attributes );
  16818. geometry.removeEventListener( 'dispose', onGeometryDispose );
  16819. delete geometries[ geometry.id ];
  16820. var property = properties.get( geometry );
  16821. if ( property.wireframe ) deleteAttribute( property.wireframe );
  16822. info.memory.geometries --;
  16823. }
  16824. function getAttributeBuffer( attribute ) {
  16825. if ( attribute instanceof THREE.InterleavedBufferAttribute ) {
  16826. return properties.get( attribute.data ).__webglBuffer;
  16827. }
  16828. return properties.get( attribute ).__webglBuffer;
  16829. }
  16830. function deleteAttribute( attribute ) {
  16831. var buffer = getAttributeBuffer( attribute );
  16832. if ( buffer !== undefined ) {
  16833. gl.deleteBuffer( buffer );
  16834. removeAttributeBuffer( attribute );
  16835. }
  16836. }
  16837. function deleteAttributes( attributes ) {
  16838. for ( var name in attributes ) {
  16839. deleteAttribute( attributes[ name ] );
  16840. }
  16841. }
  16842. function removeAttributeBuffer( attribute ) {
  16843. if ( attribute instanceof THREE.InterleavedBufferAttribute ) {
  16844. properties.delete( attribute.data );
  16845. } else {
  16846. properties.delete( attribute );
  16847. }
  16848. }
  16849. this.get = get;
  16850. };
  16851. // File:src/renderers/webgl/WebGLObjects.js
  16852. /**
  16853. * @author mrdoob / http://mrdoob.com/
  16854. */
  16855. THREE.WebGLObjects = function ( gl, properties, info ) {
  16856. var geometries = new THREE.WebGLGeometries( gl, properties, info );
  16857. //
  16858. function update( object ) {
  16859. // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter.
  16860. var geometry = geometries.get( object );
  16861. if ( object.geometry instanceof THREE.Geometry ) {
  16862. geometry.updateFromObject( object );
  16863. }
  16864. var index = geometry.index;
  16865. var attributes = geometry.attributes;
  16866. if ( index !== null ) {
  16867. updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER );
  16868. }
  16869. for ( var name in attributes ) {
  16870. updateAttribute( attributes[ name ], gl.ARRAY_BUFFER );
  16871. }
  16872. // morph targets
  16873. var morphAttributes = geometry.morphAttributes;
  16874. for ( var name in morphAttributes ) {
  16875. var array = morphAttributes[ name ];
  16876. for ( var i = 0, l = array.length; i < l; i ++ ) {
  16877. updateAttribute( array[ i ], gl.ARRAY_BUFFER );
  16878. }
  16879. }
  16880. return geometry;
  16881. }
  16882. function updateAttribute( attribute, bufferType ) {
  16883. var data = ( attribute instanceof THREE.InterleavedBufferAttribute ) ? attribute.data : attribute;
  16884. var attributeProperties = properties.get( data );
  16885. if ( attributeProperties.__webglBuffer === undefined ) {
  16886. createBuffer( attributeProperties, data, bufferType );
  16887. } else if ( attributeProperties.version !== data.version ) {
  16888. updateBuffer( attributeProperties, data, bufferType );
  16889. }
  16890. }
  16891. function createBuffer( attributeProperties, data, bufferType ) {
  16892. attributeProperties.__webglBuffer = gl.createBuffer();
  16893. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  16894. var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  16895. gl.bufferData( bufferType, data.array, usage );
  16896. attributeProperties.version = data.version;
  16897. }
  16898. function updateBuffer( attributeProperties, data, bufferType ) {
  16899. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  16900. if ( data.dynamic === false || data.updateRange.count === - 1 ) {
  16901. // Not using update ranges
  16902. gl.bufferSubData( bufferType, 0, data.array );
  16903. } else if ( data.updateRange.count === 0 ) {
  16904. 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.' );
  16905. } else {
  16906. gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT,
  16907. data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) );
  16908. data.updateRange.count = 0; // reset range
  16909. }
  16910. attributeProperties.version = data.version;
  16911. }
  16912. function getAttributeBuffer( attribute ) {
  16913. if ( attribute instanceof THREE.InterleavedBufferAttribute ) {
  16914. return properties.get( attribute.data ).__webglBuffer;
  16915. }
  16916. return properties.get( attribute ).__webglBuffer;
  16917. }
  16918. function getWireframeAttribute( geometry ) {
  16919. var property = properties.get( geometry );
  16920. if ( property.wireframe !== undefined ) {
  16921. return property.wireframe;
  16922. }
  16923. var indices = [];
  16924. var index = geometry.index;
  16925. var attributes = geometry.attributes;
  16926. var position = attributes.position;
  16927. // console.time( 'wireframe' );
  16928. if ( index !== null ) {
  16929. var edges = {};
  16930. var array = index.array;
  16931. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  16932. var a = array[ i + 0 ];
  16933. var b = array[ i + 1 ];
  16934. var c = array[ i + 2 ];
  16935. if ( checkEdge( edges, a, b ) ) indices.push( a, b );
  16936. if ( checkEdge( edges, b, c ) ) indices.push( b, c );
  16937. if ( checkEdge( edges, c, a ) ) indices.push( c, a );
  16938. }
  16939. } else {
  16940. var array = attributes.position.array;
  16941. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  16942. var a = i + 0;
  16943. var b = i + 1;
  16944. var c = i + 2;
  16945. indices.push( a, b, b, c, c, a );
  16946. }
  16947. }
  16948. // console.timeEnd( 'wireframe' );
  16949. var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array;
  16950. var attribute = new THREE.BufferAttribute( new TypeArray( indices ), 1 );
  16951. updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  16952. property.wireframe = attribute;
  16953. return attribute;
  16954. }
  16955. function checkEdge( edges, a, b ) {
  16956. if ( a > b ) {
  16957. var tmp = a;
  16958. a = b;
  16959. b = tmp;
  16960. }
  16961. var list = edges[ a ];
  16962. if ( list === undefined ) {
  16963. edges[ a ] = [ b ];
  16964. return true;
  16965. } else if ( list.indexOf( b ) === -1 ) {
  16966. list.push( b );
  16967. return true;
  16968. }
  16969. return false;
  16970. }
  16971. this.getAttributeBuffer = getAttributeBuffer;
  16972. this.getWireframeAttribute = getWireframeAttribute;
  16973. this.update = update;
  16974. };
  16975. // File:src/renderers/webgl/WebGLProgram.js
  16976. THREE.WebGLProgram = ( function () {
  16977. var programIdCount = 0;
  16978. // TODO: Combine the regex
  16979. var structRe = /^([\w\d_]+)\.([\w\d_]+)$/;
  16980. var arrayStructRe = /^([\w\d_]+)\[(\d+)\]\.([\w\d_]+)$/;
  16981. var arrayRe = /^([\w\d_]+)\[0\]$/;
  16982. function generateExtensions( extensions, parameters, rendererExtensions ) {
  16983. extensions = extensions || {};
  16984. var chunks = [
  16985. ( extensions.derivatives || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  16986. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  16987. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  16988. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : '',
  16989. ];
  16990. return chunks.filter( filterEmptyLine ).join( '\n' );
  16991. }
  16992. function generateDefines( defines ) {
  16993. var chunks = [];
  16994. for ( var name in defines ) {
  16995. var value = defines[ name ];
  16996. if ( value === false ) continue;
  16997. chunks.push( '#define ' + name + ' ' + value );
  16998. }
  16999. return chunks.join( '\n' );
  17000. }
  17001. function fetchUniformLocations( gl, program, identifiers ) {
  17002. var uniforms = {};
  17003. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  17004. for ( var i = 0; i < n; i ++ ) {
  17005. var info = gl.getActiveUniform( program, i );
  17006. var name = info.name;
  17007. var location = gl.getUniformLocation( program, name );
  17008. //console.log("THREE.WebGLProgram: ACTIVE UNIFORM:", name);
  17009. var matches = structRe.exec(name);
  17010. if( matches ) {
  17011. var structName = matches[1];
  17012. var structProperty = matches[2];
  17013. var uniformsStruct = uniforms[ structName ];
  17014. if( ! uniformsStruct ) {
  17015. uniformsStruct = uniforms[ structName ] = {};
  17016. }
  17017. uniformsStruct[ structProperty ] = location;
  17018. continue;
  17019. }
  17020. matches = arrayStructRe.exec(name);
  17021. if( matches ) {
  17022. var arrayName = matches[1];
  17023. var arrayIndex = matches[2];
  17024. var arrayProperty = matches[3];
  17025. var uniformsArray = uniforms[ arrayName ];
  17026. if( ! uniformsArray ) {
  17027. uniformsArray = uniforms[ arrayName ] = [];
  17028. }
  17029. var uniformsArrayIndex = uniformsArray[ arrayIndex ];
  17030. if( ! uniformsArrayIndex ) {
  17031. uniformsArrayIndex = uniformsArray[ arrayIndex ] = {};
  17032. }
  17033. uniformsArrayIndex[ arrayProperty ] = location;
  17034. continue;
  17035. }
  17036. matches = arrayRe.exec(name)
  17037. if( matches ) {
  17038. var arrayName = matches[1];
  17039. uniforms[ arrayName ] = location;
  17040. continue;
  17041. }
  17042. uniforms[ name ] = location;
  17043. }
  17044. return uniforms;
  17045. }
  17046. function fetchAttributeLocations( gl, program, identifiers ) {
  17047. var attributes = {};
  17048. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  17049. for ( var i = 0; i < n; i ++ ) {
  17050. var info = gl.getActiveAttrib( program, i );
  17051. var name = info.name;
  17052. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  17053. attributes[ name ] = gl.getAttribLocation( program, name );
  17054. }
  17055. return attributes;
  17056. }
  17057. function filterEmptyLine( string ) {
  17058. return string !== '';
  17059. }
  17060. return function WebGLProgram( renderer, code, material, parameters ) {
  17061. var gl = renderer.context;
  17062. var extensions = material.extensions;
  17063. var defines = material.defines;
  17064. var vertexShader = material.__webglShader.vertexShader;
  17065. var fragmentShader = material.__webglShader.fragmentShader;
  17066. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  17067. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  17068. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  17069. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  17070. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  17071. }
  17072. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  17073. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  17074. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  17075. if ( parameters.envMap ) {
  17076. switch ( material.envMap.mapping ) {
  17077. case THREE.CubeReflectionMapping:
  17078. case THREE.CubeRefractionMapping:
  17079. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  17080. break;
  17081. case THREE.EquirectangularReflectionMapping:
  17082. case THREE.EquirectangularRefractionMapping:
  17083. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  17084. break;
  17085. case THREE.SphericalReflectionMapping:
  17086. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  17087. break;
  17088. }
  17089. switch ( material.envMap.mapping ) {
  17090. case THREE.CubeRefractionMapping:
  17091. case THREE.EquirectangularRefractionMapping:
  17092. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  17093. break;
  17094. }
  17095. switch ( material.combine ) {
  17096. case THREE.MultiplyOperation:
  17097. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  17098. break;
  17099. case THREE.MixOperation:
  17100. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  17101. break;
  17102. case THREE.AddOperation:
  17103. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  17104. break;
  17105. }
  17106. }
  17107. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  17108. // console.log( 'building new program ' );
  17109. //
  17110. var customExtensions = generateExtensions( extensions, parameters, renderer.extensions );
  17111. var customDefines = generateDefines( defines );
  17112. //
  17113. var program = gl.createProgram();
  17114. var prefixVertex, prefixFragment;
  17115. if ( material instanceof THREE.RawShaderMaterial ) {
  17116. prefixVertex = '';
  17117. prefixFragment = '';
  17118. } else {
  17119. prefixVertex = [
  17120. 'precision ' + parameters.precision + ' float;',
  17121. 'precision ' + parameters.precision + ' int;',
  17122. '#define SHADER_NAME ' + material.__webglShader.name,
  17123. customDefines,
  17124. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  17125. renderer.gammaInput ? '#define GAMMA_INPUT' : '',
  17126. renderer.gammaOutput ? '#define GAMMA_OUTPUT' : '',
  17127. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  17128. '#define MAX_DIR_LIGHTS ' + parameters.maxDirLights,
  17129. '#define MAX_POINT_LIGHTS ' + parameters.maxPointLights,
  17130. '#define MAX_SPOT_LIGHTS ' + parameters.maxSpotLights,
  17131. '#define MAX_HEMI_LIGHTS ' + parameters.maxHemiLights,
  17132. '#define MAX_SHADOWS ' + parameters.maxShadows,
  17133. '#define MAX_BONES ' + parameters.maxBones,
  17134. parameters.map ? '#define USE_MAP' : '',
  17135. parameters.envMap ? '#define USE_ENVMAP' : '',
  17136. parameters.envMap ? '#define ' + envMapModeDefine : '',
  17137. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  17138. parameters.aoMap ? '#define USE_AOMAP' : '',
  17139. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  17140. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  17141. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  17142. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  17143. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  17144. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  17145. parameters.reflectivityMap ? '#define USE_REFLECTIVITYMAP' : '',
  17146. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  17147. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  17148. parameters.vertexColors ? '#define USE_COLOR' : '',
  17149. parameters.flatShading ? '#define FLAT_SHADED' : '',
  17150. parameters.skinning ? '#define USE_SKINNING' : '',
  17151. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  17152. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  17153. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  17154. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  17155. parameters.flipSided ? '#define FLIP_SIDED' : '',
  17156. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  17157. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  17158. parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '',
  17159. parameters.pointLightShadows > 0 ? '#define POINT_LIGHT_SHADOWS' : '',
  17160. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  17161. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  17162. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  17163. 'uniform mat4 modelMatrix;',
  17164. 'uniform mat4 modelViewMatrix;',
  17165. 'uniform mat4 projectionMatrix;',
  17166. 'uniform mat4 viewMatrix;',
  17167. 'uniform mat3 normalMatrix;',
  17168. 'uniform vec3 cameraPosition;',
  17169. 'attribute vec3 position;',
  17170. 'attribute vec3 normal;',
  17171. 'attribute vec2 uv;',
  17172. '#ifdef USE_COLOR',
  17173. ' attribute vec3 color;',
  17174. '#endif',
  17175. '#ifdef USE_MORPHTARGETS',
  17176. ' attribute vec3 morphTarget0;',
  17177. ' attribute vec3 morphTarget1;',
  17178. ' attribute vec3 morphTarget2;',
  17179. ' attribute vec3 morphTarget3;',
  17180. ' #ifdef USE_MORPHNORMALS',
  17181. ' attribute vec3 morphNormal0;',
  17182. ' attribute vec3 morphNormal1;',
  17183. ' attribute vec3 morphNormal2;',
  17184. ' attribute vec3 morphNormal3;',
  17185. ' #else',
  17186. ' attribute vec3 morphTarget4;',
  17187. ' attribute vec3 morphTarget5;',
  17188. ' attribute vec3 morphTarget6;',
  17189. ' attribute vec3 morphTarget7;',
  17190. ' #endif',
  17191. '#endif',
  17192. '#ifdef USE_SKINNING',
  17193. ' attribute vec4 skinIndex;',
  17194. ' attribute vec4 skinWeight;',
  17195. '#endif',
  17196. '\n'
  17197. ].filter( filterEmptyLine ).join( '\n' );
  17198. prefixFragment = [
  17199. customExtensions,
  17200. 'precision ' + parameters.precision + ' float;',
  17201. 'precision ' + parameters.precision + ' int;',
  17202. '#define SHADER_NAME ' + material.__webglShader.name,
  17203. customDefines,
  17204. '#define MAX_DIR_LIGHTS ' + parameters.maxDirLights,
  17205. '#define MAX_POINT_LIGHTS ' + parameters.maxPointLights,
  17206. '#define MAX_SPOT_LIGHTS ' + parameters.maxSpotLights,
  17207. '#define MAX_HEMI_LIGHTS ' + parameters.maxHemiLights,
  17208. '#define MAX_SHADOWS ' + parameters.maxShadows,
  17209. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  17210. renderer.gammaInput ? '#define GAMMA_INPUT' : '',
  17211. renderer.gammaOutput ? '#define GAMMA_OUTPUT' : '',
  17212. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  17213. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  17214. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  17215. parameters.map ? '#define USE_MAP' : '',
  17216. parameters.envMap ? '#define USE_ENVMAP' : '',
  17217. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  17218. parameters.envMap ? '#define ' + envMapModeDefine : '',
  17219. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  17220. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  17221. parameters.aoMap ? '#define USE_AOMAP' : '',
  17222. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  17223. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  17224. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  17225. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  17226. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  17227. parameters.reflectivityMap ? '#define USE_REFLECTIVITYMAP' : '',
  17228. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  17229. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  17230. parameters.vertexColors ? '#define USE_COLOR' : '',
  17231. parameters.flatShading ? '#define FLAT_SHADED' : '',
  17232. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  17233. parameters.flipSided ? '#define FLIP_SIDED' : '',
  17234. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  17235. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  17236. parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '',
  17237. parameters.pointLightShadows > 0 ? '#define POINT_LIGHT_SHADOWS' : '',
  17238. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  17239. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  17240. parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_CUBE_LOD_EXT' : '',
  17241. 'uniform mat4 viewMatrix;',
  17242. 'uniform vec3 cameraPosition;',
  17243. '\n'
  17244. ].filter( filterEmptyLine ).join( '\n' );
  17245. }
  17246. var vertexGlsl = prefixVertex + vertexShader;
  17247. var fragmentGlsl = prefixFragment + fragmentShader;
  17248. var glVertexShader = THREE.WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  17249. var glFragmentShader = THREE.WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  17250. gl.attachShader( program, glVertexShader );
  17251. gl.attachShader( program, glFragmentShader );
  17252. // Force a particular attribute to index 0.
  17253. if ( material.index0AttributeName !== undefined ) {
  17254. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  17255. } else if ( parameters.morphTargets === true ) {
  17256. // programs with morphTargets displace position out of attribute 0
  17257. gl.bindAttribLocation( program, 0, 'position' );
  17258. }
  17259. gl.linkProgram( program );
  17260. var programLog = gl.getProgramInfoLog( program );
  17261. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  17262. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  17263. var runnable = true;
  17264. var haveDiagnostics = true;
  17265. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  17266. runnable = false;
  17267. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  17268. } else if ( programLog !== '' ) {
  17269. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  17270. } else if ( vertexLog === '' || fragmentLog === '' ) {
  17271. haveDiagnostics = false;
  17272. }
  17273. if ( haveDiagnostics ) {
  17274. this.diagnostics = {
  17275. runnable: runnable,
  17276. material: material,
  17277. programLog: programLog,
  17278. vertexShader: {
  17279. log: vertexLog,
  17280. prefix: prefixVertex
  17281. },
  17282. fragmentShader: {
  17283. log: fragmentLog,
  17284. prefix: prefixFragment
  17285. }
  17286. };
  17287. }
  17288. // clean up
  17289. gl.deleteShader( glVertexShader );
  17290. gl.deleteShader( glFragmentShader );
  17291. // set up caching for uniform locations
  17292. var cachedUniforms;
  17293. this.getUniforms = function() {
  17294. if ( cachedUniforms === undefined ) {
  17295. cachedUniforms = fetchUniformLocations( gl, program );
  17296. }
  17297. return cachedUniforms;
  17298. };
  17299. // set up caching for attribute locations
  17300. var cachedAttributes;
  17301. this.getAttributes = function() {
  17302. if ( cachedAttributes === undefined ) {
  17303. cachedAttributes = fetchAttributeLocations( gl, program );
  17304. }
  17305. return cachedAttributes;
  17306. };
  17307. // free resource
  17308. this.destroy = function() {
  17309. gl.deleteProgram( program );
  17310. this.program = undefined;
  17311. };
  17312. // DEPRECATED
  17313. Object.defineProperties( this, {
  17314. uniforms: {
  17315. get: function() {
  17316. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  17317. return this.getUniforms();
  17318. }
  17319. },
  17320. attributes: {
  17321. get: function() {
  17322. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  17323. return this.getAttributes();
  17324. }
  17325. }
  17326. } );
  17327. //
  17328. this.id = programIdCount ++;
  17329. this.code = code;
  17330. this.usedTimes = 1;
  17331. this.program = program;
  17332. this.vertexShader = glVertexShader;
  17333. this.fragmentShader = glFragmentShader;
  17334. return this;
  17335. };
  17336. } )();
  17337. // File:src/renderers/webgl/WebGLPrograms.js
  17338. THREE.WebGLPrograms = function ( renderer, capabilities ) {
  17339. var programs = [];
  17340. var shaderIDs = {
  17341. MeshDepthMaterial: 'depth',
  17342. MeshNormalMaterial: 'normal',
  17343. MeshBasicMaterial: 'basic',
  17344. MeshLambertMaterial: 'lambert',
  17345. MeshPhongMaterial: 'phong',
  17346. MeshPhysicalMaterial: 'physical',
  17347. LineBasicMaterial: 'basic',
  17348. LineDashedMaterial: 'dashed',
  17349. PointsMaterial: 'points'
  17350. };
  17351. var parameterNames = [
  17352. "precision", "supportsVertexTextures", "map", "envMap", "envMapMode",
  17353. "lightMap", "aoMap", "emissiveMap", "bumpMap", "normalMap", "displacementMap", "specularMap",
  17354. "roughnessMap", "reflectivityMap", "metalnessMap",
  17355. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  17356. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  17357. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  17358. "maxMorphTargets", "maxMorphNormals", "maxDirLights", "maxPointLights",
  17359. "maxSpotLights", "maxHemiLights", "maxShadows", "shadowMapEnabled", "pointLightShadows",
  17360. "shadowMapType", "shadowMapDebug", "alphaTest", "doubleSided",
  17361. "flipSided"
  17362. ];
  17363. function allocateBones ( object ) {
  17364. if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  17365. return 1024;
  17366. } else {
  17367. // default for when object is not specified
  17368. // ( for example when prebuilding shader to be used with multiple objects )
  17369. //
  17370. // - leave some extra space for other uniforms
  17371. // - limit here is ANGLE's 254 max uniform vectors
  17372. // (up to 54 should be safe)
  17373. var nVertexUniforms = capabilities.maxVertexUniforms;
  17374. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  17375. var maxBones = nVertexMatrices;
  17376. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  17377. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  17378. if ( maxBones < object.skeleton.bones.length ) {
  17379. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  17380. }
  17381. }
  17382. return maxBones;
  17383. }
  17384. }
  17385. this.getParameters = function ( material, lights, fog, object ) {
  17386. var shaderID = shaderIDs[ material.type ];
  17387. // heuristics to create shader parameters according to lights in the scene
  17388. // (not to blow over maxLights budget)
  17389. var maxBones = allocateBones( object );
  17390. var precision = renderer.getPrecision();
  17391. if ( material.precision !== null ) {
  17392. precision = capabilities.getMaxPrecision( material.precision );
  17393. if ( precision !== material.precision ) {
  17394. console.warn( 'THREE.WebGLRenderer.initMaterial:', material.precision, 'not supported, using', precision, 'instead.' );
  17395. }
  17396. }
  17397. var parameters = {
  17398. shaderID: shaderID,
  17399. precision: precision,
  17400. supportsVertexTextures: capabilities.vertexTextures,
  17401. map: !! material.map,
  17402. envMap: !! material.envMap,
  17403. envMapMode: material.envMap && material.envMap.mapping,
  17404. lightMap: !! material.lightMap,
  17405. aoMap: !! material.aoMap,
  17406. emissiveMap: !! material.emissiveMap,
  17407. bumpMap: !! material.bumpMap,
  17408. normalMap: !! material.normalMap,
  17409. displacementMap: !! material.displacementMap,
  17410. roughnessMap: !! material.roughnessMap,
  17411. reflectivityMap: !! material.reflectivityMap,
  17412. metalnessMap: !! material.metalnessMap,
  17413. specularMap: !! material.specularMap,
  17414. alphaMap: !! material.alphaMap,
  17415. combine: material.combine,
  17416. vertexColors: material.vertexColors,
  17417. fog: fog,
  17418. useFog: material.fog,
  17419. fogExp: fog instanceof THREE.FogExp2,
  17420. flatShading: material.shading === THREE.FlatShading,
  17421. sizeAttenuation: material.sizeAttenuation,
  17422. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  17423. skinning: material.skinning,
  17424. maxBones: maxBones,
  17425. useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  17426. morphTargets: material.morphTargets,
  17427. morphNormals: material.morphNormals,
  17428. maxMorphTargets: renderer.maxMorphTargets,
  17429. maxMorphNormals: renderer.maxMorphNormals,
  17430. maxDirLights: lights.directional.length,
  17431. maxPointLights: lights.point.length,
  17432. maxSpotLights: lights.spot.length,
  17433. maxHemiLights: lights.hemi.length,
  17434. maxShadows: lights.shadows,
  17435. pointLightShadows: lights.shadowsPointLight,
  17436. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows > 0,
  17437. shadowMapType: renderer.shadowMap.type,
  17438. shadowMapDebug: renderer.shadowMap.debug,
  17439. alphaTest: material.alphaTest,
  17440. doubleSided: material.side === THREE.DoubleSide,
  17441. flipSided: material.side === THREE.BackSide
  17442. };
  17443. return parameters;
  17444. };
  17445. this.getProgramCode = function ( material, parameters ) {
  17446. var chunks = [];
  17447. if ( parameters.shaderID ) {
  17448. chunks.push( parameters.shaderID );
  17449. } else {
  17450. chunks.push( material.fragmentShader );
  17451. chunks.push( material.vertexShader );
  17452. }
  17453. if ( material.defines !== undefined ) {
  17454. for ( var name in material.defines ) {
  17455. chunks.push( name );
  17456. chunks.push( material.defines[ name ] );
  17457. }
  17458. }
  17459. for ( var i = 0; i < parameterNames.length; i ++ ) {
  17460. var parameterName = parameterNames[ i ];
  17461. chunks.push( parameterName );
  17462. chunks.push( parameters[ parameterName ] );
  17463. }
  17464. return chunks.join();
  17465. };
  17466. this.acquireProgram = function ( material, parameters, code ) {
  17467. var program;
  17468. // Check if code has been already compiled
  17469. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  17470. var programInfo = programs[ p ];
  17471. if ( programInfo.code === code ) {
  17472. program = programInfo;
  17473. ++ program.usedTimes;
  17474. break;
  17475. }
  17476. }
  17477. if ( program === undefined ) {
  17478. program = new THREE.WebGLProgram( renderer, code, material, parameters );
  17479. programs.push( program );
  17480. }
  17481. return program;
  17482. };
  17483. this.releaseProgram = function( program ) {
  17484. if ( -- program.usedTimes === 0 ) {
  17485. // Remove from unordered set
  17486. var i = programs.indexOf( program );
  17487. programs[ i ] = programs[ programs.length - 1 ];
  17488. programs.pop();
  17489. // Free WebGL resources
  17490. program.destroy();
  17491. }
  17492. };
  17493. // Exposed for resource monitoring & error feedback via renderer.info:
  17494. this.programs = programs;
  17495. };
  17496. // File:src/renderers/webgl/WebGLProperties.js
  17497. /**
  17498. * @author fordacious / fordacious.github.io
  17499. */
  17500. THREE.WebGLProperties = function () {
  17501. var properties = {};
  17502. this.get = function ( object ) {
  17503. var uuid = object.uuid;
  17504. var map = properties[ uuid ];
  17505. if ( map === undefined ) {
  17506. map = {};
  17507. properties[ uuid ] = map;
  17508. }
  17509. return map;
  17510. };
  17511. this.delete = function ( object ) {
  17512. delete properties[ object.uuid ];
  17513. };
  17514. this.clear = function () {
  17515. properties = {};
  17516. };
  17517. };
  17518. // File:src/renderers/webgl/WebGLShader.js
  17519. THREE.WebGLShader = ( function () {
  17520. function addLineNumbers( string ) {
  17521. var lines = string.split( '\n' );
  17522. for ( var i = 0; i < lines.length; i ++ ) {
  17523. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  17524. }
  17525. return lines.join( '\n' );
  17526. }
  17527. return function WebGLShader( gl, type, string ) {
  17528. var shader = gl.createShader( type );
  17529. gl.shaderSource( shader, string );
  17530. gl.compileShader( shader );
  17531. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  17532. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  17533. }
  17534. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  17535. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  17536. }
  17537. // --enable-privileged-webgl-extension
  17538. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  17539. return shader;
  17540. };
  17541. } )();
  17542. // File:src/renderers/webgl/WebGLShadowMap.js
  17543. /**
  17544. * @author alteredq / http://alteredqualia.com/
  17545. * @author mrdoob / http://mrdoob.com/
  17546. */
  17547. THREE.WebGLShadowMap = function ( _renderer, _lights, _objects ) {
  17548. var _gl = _renderer.context,
  17549. _state = _renderer.state,
  17550. _frustum = new THREE.Frustum(),
  17551. _projScreenMatrix = new THREE.Matrix4(),
  17552. _min = new THREE.Vector3(),
  17553. _max = new THREE.Vector3(),
  17554. _lookTarget = new THREE.Vector3(),
  17555. _lightPositionWorld = new THREE.Vector3(),
  17556. _renderList = [],
  17557. _MorphingFlag = 1,
  17558. _SkinningFlag = 2,
  17559. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  17560. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  17561. _distanceMaterials = new Array( _NumberOfMaterialVariants );
  17562. var cubeDirections = [
  17563. new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( - 1, 0, 0 ), new THREE.Vector3( 0, 0, 1 ),
  17564. new THREE.Vector3( 0, 0, - 1 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, - 1, 0 )
  17565. ];
  17566. var cubeUps = [
  17567. new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 0 ),
  17568. new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 0, 0, - 1 )
  17569. ];
  17570. var cube2DViewPorts = [
  17571. new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4(),
  17572. new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4()
  17573. ];
  17574. var _vector4 = new THREE.Vector4();
  17575. // init
  17576. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  17577. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  17578. var distanceShader = THREE.ShaderLib[ "distanceRGBA" ];
  17579. var distanceUniforms = THREE.UniformsUtils.clone( distanceShader.uniforms );
  17580. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  17581. var useMorphing = ( i & _MorphingFlag ) !== 0;
  17582. var useSkinning = ( i & _SkinningFlag ) !== 0;
  17583. var depthMaterial = new THREE.ShaderMaterial( {
  17584. uniforms: depthUniforms,
  17585. vertexShader: depthShader.vertexShader,
  17586. fragmentShader: depthShader.fragmentShader,
  17587. morphTargets: useMorphing,
  17588. skinning: useSkinning
  17589. } );
  17590. depthMaterial._shadowPass = true;
  17591. _depthMaterials[ i ] = depthMaterial;
  17592. var distanceMaterial = new THREE.ShaderMaterial( {
  17593. uniforms: distanceUniforms,
  17594. vertexShader: distanceShader.vertexShader,
  17595. fragmentShader: distanceShader.fragmentShader,
  17596. morphTargets: useMorphing,
  17597. skinning: useSkinning
  17598. } );
  17599. distanceMaterial._shadowPass = true;
  17600. _distanceMaterials[ i ] = distanceMaterial;
  17601. }
  17602. //
  17603. var scope = this;
  17604. this.enabled = false;
  17605. this.autoUpdate = true;
  17606. this.needsUpdate = false;
  17607. this.type = THREE.PCFShadowMap;
  17608. this.cullFace = THREE.CullFaceFront;
  17609. this.render = function ( scene, camera ) {
  17610. var faceCount, isPointLight;
  17611. if ( scope.enabled === false ) return;
  17612. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  17613. // Set GL state for depth map.
  17614. _gl.clearColor( 1, 1, 1, 1 );
  17615. _state.disable( _gl.BLEND );
  17616. _state.enable( _gl.CULL_FACE );
  17617. _gl.frontFace( _gl.CCW );
  17618. _gl.cullFace( scope.cullFace === THREE.CullFaceFront ? _gl.FRONT : _gl.BACK );
  17619. _state.setDepthTest( true );
  17620. // save the existing viewport so it can be restored later
  17621. _renderer.getViewport( _vector4 );
  17622. // render depth map
  17623. for ( var i = 0, il = _lights.length; i < il; i ++ ) {
  17624. var light = _lights[ i ];
  17625. if ( light.castShadow === true ) {
  17626. var shadow = light.shadow;
  17627. var shadowCamera = shadow.camera;
  17628. var shadowMapSize = shadow.mapSize;
  17629. if ( light instanceof THREE.PointLight ) {
  17630. faceCount = 6;
  17631. isPointLight = true;
  17632. var vpWidth = shadowMapSize.x / 4.0;
  17633. var vpHeight = shadowMapSize.y / 2.0;
  17634. // These viewports map a cube-map onto a 2D texture with the
  17635. // following orientation:
  17636. //
  17637. // xzXZ
  17638. // y Y
  17639. //
  17640. // X - Positive x direction
  17641. // x - Negative x direction
  17642. // Y - Positive y direction
  17643. // y - Negative y direction
  17644. // Z - Positive z direction
  17645. // z - Negative z direction
  17646. // positive X
  17647. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  17648. // negative X
  17649. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  17650. // positive Z
  17651. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  17652. // negative Z
  17653. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  17654. // positive Y
  17655. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  17656. // negative Y
  17657. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  17658. } else {
  17659. faceCount = 1;
  17660. isPointLight = false;
  17661. }
  17662. if ( shadow.map === null ) {
  17663. var shadowFilter = THREE.LinearFilter;
  17664. if ( scope.type === THREE.PCFSoftShadowMap ) {
  17665. shadowFilter = THREE.NearestFilter;
  17666. }
  17667. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  17668. shadow.map = new THREE.WebGLRenderTarget( shadowMapSize.x, shadowMapSize.y, pars );
  17669. shadow.matrix = new THREE.Matrix4();
  17670. //
  17671. if ( light instanceof THREE.SpotLight ) {
  17672. shadowCamera.aspect = shadowMapSize.x / shadowMapSize.y;
  17673. }
  17674. shadowCamera.updateProjectionMatrix();
  17675. }
  17676. var shadowMap = shadow.map;
  17677. var shadowMatrix = shadow.matrix;
  17678. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  17679. shadowCamera.position.copy( _lightPositionWorld );
  17680. _renderer.setRenderTarget( shadowMap );
  17681. _renderer.clear();
  17682. // render shadow map for each cube face (if omni-directional) or
  17683. // run a single pass if not
  17684. for ( var face = 0; face < faceCount; face ++ ) {
  17685. if ( isPointLight ) {
  17686. _lookTarget.copy( shadowCamera.position );
  17687. _lookTarget.add( cubeDirections[ face ] );
  17688. shadowCamera.up.copy( cubeUps[ face ] );
  17689. shadowCamera.lookAt( _lookTarget );
  17690. var vpDimensions = cube2DViewPorts[ face ];
  17691. _renderer.setViewport( vpDimensions.x, vpDimensions.y, vpDimensions.z, vpDimensions.w );
  17692. } else {
  17693. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  17694. shadowCamera.lookAt( _lookTarget );
  17695. }
  17696. shadowCamera.updateMatrixWorld();
  17697. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  17698. // compute shadow matrix
  17699. shadowMatrix.set(
  17700. 0.5, 0.0, 0.0, 0.5,
  17701. 0.0, 0.5, 0.0, 0.5,
  17702. 0.0, 0.0, 0.5, 0.5,
  17703. 0.0, 0.0, 0.0, 1.0
  17704. );
  17705. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  17706. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  17707. // update camera matrices and frustum
  17708. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  17709. _frustum.setFromMatrix( _projScreenMatrix );
  17710. // set object matrices & frustum culling
  17711. _renderList.length = 0;
  17712. projectObject( scene, camera, shadowCamera );
  17713. // render shadow map
  17714. // render regular objects
  17715. for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) {
  17716. var object = _renderList[ j ];
  17717. var geometry = _objects.update( object );
  17718. var material = object.material;
  17719. if ( material instanceof THREE.MeshFaceMaterial ) {
  17720. var groups = geometry.groups;
  17721. var materials = material.materials;
  17722. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  17723. var group = groups[ k ];
  17724. var groupMaterial = materials[ group.materialIndex ];
  17725. if ( groupMaterial.visible === true ) {
  17726. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  17727. _renderer.renderBufferDirect( shadowCamera, _lights, null, geometry, depthMaterial, object, group );
  17728. }
  17729. }
  17730. } else {
  17731. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  17732. _renderer.renderBufferDirect( shadowCamera, _lights, null, geometry, depthMaterial, object, null );
  17733. }
  17734. }
  17735. }
  17736. // We must call _renderer.resetGLState() at the end of each iteration of
  17737. // the light loop in order to force material updates for each light.
  17738. _renderer.resetGLState();
  17739. }
  17740. }
  17741. _renderer.setViewport( _vector4.x, _vector4.y, _vector4.z, _vector4.w );
  17742. // Restore GL state.
  17743. var clearColor = _renderer.getClearColor(),
  17744. clearAlpha = _renderer.getClearAlpha();
  17745. _renderer.setClearColor( clearColor, clearAlpha );
  17746. _state.enable( _gl.BLEND );
  17747. if ( scope.cullFace === THREE.CullFaceFront ) {
  17748. _gl.cullFace( _gl.BACK );
  17749. }
  17750. _renderer.resetGLState();
  17751. scope.needsUpdate = false;
  17752. };
  17753. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  17754. var geometry = object.geometry;
  17755. var newMaterial = null;
  17756. var materialVariants = _depthMaterials;
  17757. var customMaterial = object.customDepthMaterial;
  17758. if ( isPointLight ) {
  17759. materialVariants = _distanceMaterials;
  17760. customMaterial = object.customDistanceMaterial;
  17761. }
  17762. if ( ! customMaterial ) {
  17763. var useMorphing = geometry.morphTargets !== undefined &&
  17764. geometry.morphTargets.length > 0 && material.morphTargets;
  17765. var useSkinning = object instanceof THREE.SkinnedMesh && material.skinning;
  17766. var variantIndex = 0;
  17767. if ( useMorphing ) variantIndex |= _MorphingFlag;
  17768. if ( useSkinning ) variantIndex |= _SkinningFlag;
  17769. newMaterial = materialVariants[ variantIndex ];
  17770. } else {
  17771. newMaterial = customMaterial;
  17772. }
  17773. newMaterial.visible = material.visible;
  17774. newMaterial.wireframe = material.wireframe;
  17775. newMaterial.wireframeLinewidth = material.wireframeLinewidth;
  17776. if ( isPointLight && newMaterial.uniforms.lightPos !== undefined ) {
  17777. newMaterial.uniforms.lightPos.value.copy( lightPositionWorld );
  17778. }
  17779. return newMaterial;
  17780. }
  17781. function projectObject( object, camera, shadowCamera ) {
  17782. if ( object.visible === false ) return;
  17783. if ( object.layers.test( camera.layers ) && ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) ) {
  17784. if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  17785. var material = object.material;
  17786. if ( material.visible === true ) {
  17787. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  17788. _renderList.push( object );
  17789. }
  17790. }
  17791. }
  17792. var children = object.children;
  17793. for ( var i = 0, l = children.length; i < l; i ++ ) {
  17794. projectObject( children[ i ], camera, shadowCamera );
  17795. }
  17796. }
  17797. };
  17798. // File:src/renderers/webgl/WebGLState.js
  17799. /**
  17800. * @author mrdoob / http://mrdoob.com/
  17801. */
  17802. THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) {
  17803. var _this = this;
  17804. var newAttributes = new Uint8Array( 16 );
  17805. var enabledAttributes = new Uint8Array( 16 );
  17806. var attributeDivisors = new Uint8Array( 16 );
  17807. var capabilities = {};
  17808. var compressedTextureFormats = null;
  17809. var currentBlending = null;
  17810. var currentBlendEquation = null;
  17811. var currentBlendSrc = null;
  17812. var currentBlendDst = null;
  17813. var currentBlendEquationAlpha = null;
  17814. var currentBlendSrcAlpha = null;
  17815. var currentBlendDstAlpha = null;
  17816. var currentDepthFunc = null;
  17817. var currentDepthWrite = null;
  17818. var currentColorWrite = null;
  17819. var currentFlipSided = null;
  17820. var currentLineWidth = null;
  17821. var currentPolygonOffsetFactor = null;
  17822. var currentPolygonOffsetUnits = null;
  17823. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  17824. var currentTextureSlot = undefined;
  17825. var currentBoundTextures = {};
  17826. this.init = function () {
  17827. gl.clearColor( 0, 0, 0, 1 );
  17828. gl.clearDepth( 1 );
  17829. gl.clearStencil( 0 );
  17830. this.enable( gl.DEPTH_TEST );
  17831. gl.depthFunc( gl.LEQUAL );
  17832. gl.frontFace( gl.CCW );
  17833. gl.cullFace( gl.BACK );
  17834. this.enable( gl.CULL_FACE );
  17835. this.enable( gl.BLEND );
  17836. gl.blendEquation( gl.FUNC_ADD );
  17837. gl.blendFunc( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA );
  17838. };
  17839. this.initAttributes = function () {
  17840. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  17841. newAttributes[ i ] = 0;
  17842. }
  17843. };
  17844. this.enableAttribute = function ( attribute ) {
  17845. newAttributes[ attribute ] = 1;
  17846. if ( enabledAttributes[ attribute ] === 0 ) {
  17847. gl.enableVertexAttribArray( attribute );
  17848. enabledAttributes[ attribute ] = 1;
  17849. }
  17850. if ( attributeDivisors[ attribute ] !== 0 ) {
  17851. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  17852. extension.vertexAttribDivisorANGLE( attribute, 0 );
  17853. attributeDivisors[ attribute ] = 0;
  17854. }
  17855. };
  17856. this.enableAttributeAndDivisor = function ( attribute, meshPerAttribute, extension ) {
  17857. newAttributes[ attribute ] = 1;
  17858. if ( enabledAttributes[ attribute ] === 0 ) {
  17859. gl.enableVertexAttribArray( attribute );
  17860. enabledAttributes[ attribute ] = 1;
  17861. }
  17862. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  17863. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  17864. attributeDivisors[ attribute ] = meshPerAttribute;
  17865. }
  17866. };
  17867. this.disableUnusedAttributes = function () {
  17868. for ( var i = 0, l = enabledAttributes.length; i < l; i ++ ) {
  17869. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  17870. gl.disableVertexAttribArray( i );
  17871. enabledAttributes[ i ] = 0;
  17872. }
  17873. }
  17874. };
  17875. this.enable = function ( id ) {
  17876. if ( capabilities[ id ] !== true ) {
  17877. gl.enable( id );
  17878. capabilities[ id ] = true;
  17879. }
  17880. };
  17881. this.disable = function ( id ) {
  17882. if ( capabilities[ id ] !== false ) {
  17883. gl.disable( id );
  17884. capabilities[ id ] = false;
  17885. }
  17886. };
  17887. this.getCompressedTextureFormats = function () {
  17888. if ( compressedTextureFormats === null ) {
  17889. compressedTextureFormats = [];
  17890. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  17891. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ) {
  17892. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  17893. for ( var i = 0; i < formats.length; i ++ ) {
  17894. compressedTextureFormats.push( formats[ i ] );
  17895. }
  17896. }
  17897. }
  17898. return compressedTextureFormats;
  17899. };
  17900. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha ) {
  17901. if ( blending !== currentBlending ) {
  17902. if ( blending === THREE.NoBlending ) {
  17903. this.disable( gl.BLEND );
  17904. } else if ( blending === THREE.AdditiveBlending ) {
  17905. this.enable( gl.BLEND );
  17906. gl.blendEquation( gl.FUNC_ADD );
  17907. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  17908. } else if ( blending === THREE.SubtractiveBlending ) {
  17909. // TODO: Find blendFuncSeparate() combination
  17910. this.enable( gl.BLEND );
  17911. gl.blendEquation( gl.FUNC_ADD );
  17912. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  17913. } else if ( blending === THREE.MultiplyBlending ) {
  17914. // TODO: Find blendFuncSeparate() combination
  17915. this.enable( gl.BLEND );
  17916. gl.blendEquation( gl.FUNC_ADD );
  17917. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  17918. } else if ( blending === THREE.CustomBlending ) {
  17919. this.enable( gl.BLEND );
  17920. } else {
  17921. this.enable( gl.BLEND );
  17922. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  17923. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  17924. }
  17925. currentBlending = blending;
  17926. }
  17927. if ( blending === THREE.CustomBlending ) {
  17928. blendEquationAlpha = blendEquationAlpha || blendEquation;
  17929. blendSrcAlpha = blendSrcAlpha || blendSrc;
  17930. blendDstAlpha = blendDstAlpha || blendDst;
  17931. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  17932. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  17933. currentBlendEquation = blendEquation;
  17934. currentBlendEquationAlpha = blendEquationAlpha;
  17935. }
  17936. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  17937. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  17938. currentBlendSrc = blendSrc;
  17939. currentBlendDst = blendDst;
  17940. currentBlendSrcAlpha = blendSrcAlpha;
  17941. currentBlendDstAlpha = blendDstAlpha;
  17942. }
  17943. } else {
  17944. currentBlendEquation = null;
  17945. currentBlendSrc = null;
  17946. currentBlendDst = null;
  17947. currentBlendEquationAlpha = null;
  17948. currentBlendSrcAlpha = null;
  17949. currentBlendDstAlpha = null;
  17950. }
  17951. };
  17952. this.setDepthFunc = function ( depthFunc ) {
  17953. if ( currentDepthFunc !== depthFunc ) {
  17954. if ( depthFunc ) {
  17955. switch ( depthFunc ) {
  17956. case THREE.NeverDepth:
  17957. gl.depthFunc( gl.NEVER );
  17958. break;
  17959. case THREE.AlwaysDepth:
  17960. gl.depthFunc( gl.ALWAYS );
  17961. break;
  17962. case THREE.LessDepth:
  17963. gl.depthFunc( gl.LESS );
  17964. break;
  17965. case THREE.LessEqualDepth:
  17966. gl.depthFunc( gl.LEQUAL );
  17967. break;
  17968. case THREE.EqualDepth:
  17969. gl.depthFunc( gl.EQUAL );
  17970. break;
  17971. case THREE.GreaterEqualDepth:
  17972. gl.depthFunc( gl.GEQUAL );
  17973. break;
  17974. case THREE.GreaterDepth:
  17975. gl.depthFunc( gl.GREATER );
  17976. break;
  17977. case THREE.NotEqualDepth:
  17978. gl.depthFunc( gl.NOTEQUAL );
  17979. break;
  17980. default:
  17981. gl.depthFunc( gl.LEQUAL );
  17982. }
  17983. } else {
  17984. gl.depthFunc( gl.LEQUAL );
  17985. }
  17986. currentDepthFunc = depthFunc;
  17987. }
  17988. };
  17989. this.setDepthTest = function ( depthTest ) {
  17990. if ( depthTest ) {
  17991. this.enable( gl.DEPTH_TEST );
  17992. } else {
  17993. this.disable( gl.DEPTH_TEST );
  17994. }
  17995. };
  17996. this.setDepthWrite = function ( depthWrite ) {
  17997. if ( currentDepthWrite !== depthWrite ) {
  17998. gl.depthMask( depthWrite );
  17999. currentDepthWrite = depthWrite;
  18000. }
  18001. };
  18002. this.setColorWrite = function ( colorWrite ) {
  18003. if ( currentColorWrite !== colorWrite ) {
  18004. gl.colorMask( colorWrite, colorWrite, colorWrite, colorWrite );
  18005. currentColorWrite = colorWrite;
  18006. }
  18007. };
  18008. this.setFlipSided = function ( flipSided ) {
  18009. if ( currentFlipSided !== flipSided ) {
  18010. if ( flipSided ) {
  18011. gl.frontFace( gl.CW );
  18012. } else {
  18013. gl.frontFace( gl.CCW );
  18014. }
  18015. currentFlipSided = flipSided;
  18016. }
  18017. };
  18018. this.setLineWidth = function ( width ) {
  18019. if ( width !== currentLineWidth ) {
  18020. gl.lineWidth( width );
  18021. currentLineWidth = width;
  18022. }
  18023. };
  18024. this.setPolygonOffset = function ( polygonOffset, factor, units ) {
  18025. if ( polygonOffset ) {
  18026. this.enable( gl.POLYGON_OFFSET_FILL );
  18027. } else {
  18028. this.disable( gl.POLYGON_OFFSET_FILL );
  18029. }
  18030. if ( polygonOffset && ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) ) {
  18031. gl.polygonOffset( factor, units );
  18032. currentPolygonOffsetFactor = factor;
  18033. currentPolygonOffsetUnits = units;
  18034. }
  18035. };
  18036. this.setScissorTest = function ( scissorTest ) {
  18037. if ( scissorTest ) {
  18038. this.enable( gl.SCISSOR_TEST );
  18039. } else {
  18040. this.disable( gl.SCISSOR_TEST );
  18041. }
  18042. };
  18043. // texture
  18044. this.activeTexture = function ( webglSlot ) {
  18045. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  18046. if ( currentTextureSlot !== webglSlot ) {
  18047. gl.activeTexture( webglSlot );
  18048. currentTextureSlot = webglSlot;
  18049. }
  18050. }
  18051. this.bindTexture = function ( webglType, webglTexture ) {
  18052. if ( currentTextureSlot === undefined ) {
  18053. _this.activeTexture();
  18054. }
  18055. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  18056. if ( boundTexture === undefined ) {
  18057. boundTexture = { type: undefined, texture: undefined };
  18058. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  18059. }
  18060. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  18061. gl.bindTexture( webglType, webglTexture );
  18062. boundTexture.type = webglType;
  18063. boundTexture.texture = webglTexture;
  18064. }
  18065. };
  18066. this.compressedTexImage2D = function () {
  18067. try {
  18068. gl.compressedTexImage2D.apply( gl, arguments );
  18069. } catch ( error ) {
  18070. console.error( error );
  18071. }
  18072. };
  18073. this.texImage2D = function () {
  18074. try {
  18075. gl.texImage2D.apply( gl, arguments );
  18076. } catch ( error ) {
  18077. console.error( error );
  18078. }
  18079. };
  18080. //
  18081. this.reset = function () {
  18082. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  18083. if ( enabledAttributes[ i ] === 1 ) {
  18084. gl.disableVertexAttribArray( i );
  18085. enabledAttributes[ i ] = 0;
  18086. }
  18087. }
  18088. capabilities = {};
  18089. compressedTextureFormats = null;
  18090. currentBlending = null;
  18091. currentDepthWrite = null;
  18092. currentColorWrite = null;
  18093. currentFlipSided = null;
  18094. };
  18095. };
  18096. // File:src/renderers/webgl/plugins/LensFlarePlugin.js
  18097. /**
  18098. * @author mikael emtinger / http://gomo.se/
  18099. * @author alteredq / http://alteredqualia.com/
  18100. */
  18101. THREE.LensFlarePlugin = function ( renderer, flares ) {
  18102. var gl = renderer.context;
  18103. var state = renderer.state;
  18104. var vertexBuffer, elementBuffer;
  18105. var program, attributes, uniforms;
  18106. var hasVertexTexture;
  18107. var tempTexture, occlusionTexture;
  18108. function init() {
  18109. var vertices = new Float32Array( [
  18110. - 1, - 1, 0, 0,
  18111. 1, - 1, 1, 0,
  18112. 1, 1, 1, 1,
  18113. - 1, 1, 0, 1
  18114. ] );
  18115. var faces = new Uint16Array( [
  18116. 0, 1, 2,
  18117. 0, 2, 3
  18118. ] );
  18119. // buffers
  18120. vertexBuffer = gl.createBuffer();
  18121. elementBuffer = gl.createBuffer();
  18122. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  18123. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  18124. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  18125. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  18126. // textures
  18127. tempTexture = gl.createTexture();
  18128. occlusionTexture = gl.createTexture();
  18129. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  18130. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  18131. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  18132. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  18133. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  18134. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  18135. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  18136. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  18137. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  18138. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  18139. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  18140. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  18141. hasVertexTexture = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) > 0;
  18142. var shader;
  18143. if ( hasVertexTexture ) {
  18144. shader = {
  18145. vertexShader: [
  18146. "uniform lowp int renderType;",
  18147. "uniform vec3 screenPosition;",
  18148. "uniform vec2 scale;",
  18149. "uniform float rotation;",
  18150. "uniform sampler2D occlusionMap;",
  18151. "attribute vec2 position;",
  18152. "attribute vec2 uv;",
  18153. "varying vec2 vUV;",
  18154. "varying float vVisibility;",
  18155. "void main() {",
  18156. "vUV = uv;",
  18157. "vec2 pos = position;",
  18158. "if ( renderType == 2 ) {",
  18159. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  18160. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  18161. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  18162. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  18163. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  18164. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  18165. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  18166. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  18167. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  18168. "vVisibility = visibility.r / 9.0;",
  18169. "vVisibility *= 1.0 - visibility.g / 9.0;",
  18170. "vVisibility *= visibility.b / 9.0;",
  18171. "vVisibility *= 1.0 - visibility.a / 9.0;",
  18172. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  18173. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  18174. "}",
  18175. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  18176. "}"
  18177. ].join( "\n" ),
  18178. fragmentShader: [
  18179. "uniform lowp int renderType;",
  18180. "uniform sampler2D map;",
  18181. "uniform float opacity;",
  18182. "uniform vec3 color;",
  18183. "varying vec2 vUV;",
  18184. "varying float vVisibility;",
  18185. "void main() {",
  18186. // pink square
  18187. "if ( renderType == 0 ) {",
  18188. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  18189. // restore
  18190. "} else if ( renderType == 1 ) {",
  18191. "gl_FragColor = texture2D( map, vUV );",
  18192. // flare
  18193. "} else {",
  18194. "vec4 texture = texture2D( map, vUV );",
  18195. "texture.a *= opacity * vVisibility;",
  18196. "gl_FragColor = texture;",
  18197. "gl_FragColor.rgb *= color;",
  18198. "}",
  18199. "}"
  18200. ].join( "\n" )
  18201. };
  18202. } else {
  18203. shader = {
  18204. vertexShader: [
  18205. "uniform lowp int renderType;",
  18206. "uniform vec3 screenPosition;",
  18207. "uniform vec2 scale;",
  18208. "uniform float rotation;",
  18209. "attribute vec2 position;",
  18210. "attribute vec2 uv;",
  18211. "varying vec2 vUV;",
  18212. "void main() {",
  18213. "vUV = uv;",
  18214. "vec2 pos = position;",
  18215. "if ( renderType == 2 ) {",
  18216. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  18217. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  18218. "}",
  18219. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  18220. "}"
  18221. ].join( "\n" ),
  18222. fragmentShader: [
  18223. "precision mediump float;",
  18224. "uniform lowp int renderType;",
  18225. "uniform sampler2D map;",
  18226. "uniform sampler2D occlusionMap;",
  18227. "uniform float opacity;",
  18228. "uniform vec3 color;",
  18229. "varying vec2 vUV;",
  18230. "void main() {",
  18231. // pink square
  18232. "if ( renderType == 0 ) {",
  18233. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  18234. // restore
  18235. "} else if ( renderType == 1 ) {",
  18236. "gl_FragColor = texture2D( map, vUV );",
  18237. // flare
  18238. "} else {",
  18239. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  18240. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  18241. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  18242. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  18243. "visibility = ( 1.0 - visibility / 4.0 );",
  18244. "vec4 texture = texture2D( map, vUV );",
  18245. "texture.a *= opacity * visibility;",
  18246. "gl_FragColor = texture;",
  18247. "gl_FragColor.rgb *= color;",
  18248. "}",
  18249. "}"
  18250. ].join( "\n" )
  18251. };
  18252. }
  18253. program = createProgram( shader );
  18254. attributes = {
  18255. vertex: gl.getAttribLocation ( program, "position" ),
  18256. uv: gl.getAttribLocation ( program, "uv" )
  18257. };
  18258. uniforms = {
  18259. renderType: gl.getUniformLocation( program, "renderType" ),
  18260. map: gl.getUniformLocation( program, "map" ),
  18261. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  18262. opacity: gl.getUniformLocation( program, "opacity" ),
  18263. color: gl.getUniformLocation( program, "color" ),
  18264. scale: gl.getUniformLocation( program, "scale" ),
  18265. rotation: gl.getUniformLocation( program, "rotation" ),
  18266. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  18267. };
  18268. }
  18269. /*
  18270. * Render lens flares
  18271. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  18272. * reads these back and calculates occlusion.
  18273. */
  18274. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  18275. if ( flares.length === 0 ) return;
  18276. var tempPosition = new THREE.Vector3();
  18277. var invAspect = viewportHeight / viewportWidth,
  18278. halfViewportWidth = viewportWidth * 0.5,
  18279. halfViewportHeight = viewportHeight * 0.5;
  18280. var size = 16 / viewportHeight,
  18281. scale = new THREE.Vector2( size * invAspect, size );
  18282. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  18283. screenPositionPixels = new THREE.Vector2( 1, 1 );
  18284. if ( program === undefined ) {
  18285. init();
  18286. }
  18287. gl.useProgram( program );
  18288. state.initAttributes();
  18289. state.enableAttribute( attributes.vertex );
  18290. state.enableAttribute( attributes.uv );
  18291. state.disableUnusedAttributes();
  18292. // loop through all lens flares to update their occlusion and positions
  18293. // setup gl and common used attribs/uniforms
  18294. gl.uniform1i( uniforms.occlusionMap, 0 );
  18295. gl.uniform1i( uniforms.map, 1 );
  18296. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  18297. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  18298. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  18299. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  18300. state.disable( gl.CULL_FACE );
  18301. gl.depthMask( false );
  18302. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  18303. size = 16 / viewportHeight;
  18304. scale.set( size * invAspect, size );
  18305. // calc object screen position
  18306. var flare = flares[ i ];
  18307. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  18308. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  18309. tempPosition.applyProjection( camera.projectionMatrix );
  18310. // setup arrays for gl programs
  18311. screenPosition.copy( tempPosition );
  18312. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  18313. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  18314. // screen cull
  18315. if ( hasVertexTexture || (
  18316. screenPositionPixels.x > 0 &&
  18317. screenPositionPixels.x < viewportWidth &&
  18318. screenPositionPixels.y > 0 &&
  18319. screenPositionPixels.y < viewportHeight ) ) {
  18320. // save current RGB to temp texture
  18321. state.activeTexture( gl.TEXTURE0 );
  18322. state.bindTexture( gl.TEXTURE_2D, null );
  18323. state.activeTexture( gl.TEXTURE1 );
  18324. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  18325. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  18326. // render pink quad
  18327. gl.uniform1i( uniforms.renderType, 0 );
  18328. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  18329. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  18330. state.disable( gl.BLEND );
  18331. state.enable( gl.DEPTH_TEST );
  18332. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  18333. // copy result to occlusionMap
  18334. state.activeTexture( gl.TEXTURE0 );
  18335. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  18336. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  18337. // restore graphics
  18338. gl.uniform1i( uniforms.renderType, 1 );
  18339. state.disable( gl.DEPTH_TEST );
  18340. state.activeTexture( gl.TEXTURE1 );
  18341. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  18342. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  18343. // update object positions
  18344. flare.positionScreen.copy( screenPosition );
  18345. if ( flare.customUpdateCallback ) {
  18346. flare.customUpdateCallback( flare );
  18347. } else {
  18348. flare.updateLensFlares();
  18349. }
  18350. // render flares
  18351. gl.uniform1i( uniforms.renderType, 2 );
  18352. state.enable( gl.BLEND );
  18353. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  18354. var sprite = flare.lensFlares[ j ];
  18355. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  18356. screenPosition.x = sprite.x;
  18357. screenPosition.y = sprite.y;
  18358. screenPosition.z = sprite.z;
  18359. size = sprite.size * sprite.scale / viewportHeight;
  18360. scale.x = size * invAspect;
  18361. scale.y = size;
  18362. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  18363. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  18364. gl.uniform1f( uniforms.rotation, sprite.rotation );
  18365. gl.uniform1f( uniforms.opacity, sprite.opacity );
  18366. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  18367. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  18368. renderer.setTexture( sprite.texture, 1 );
  18369. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  18370. }
  18371. }
  18372. }
  18373. }
  18374. // restore gl
  18375. state.enable( gl.CULL_FACE );
  18376. state.enable( gl.DEPTH_TEST );
  18377. gl.depthMask( true );
  18378. renderer.resetGLState();
  18379. };
  18380. function createProgram ( shader ) {
  18381. var program = gl.createProgram();
  18382. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  18383. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  18384. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  18385. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  18386. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  18387. gl.compileShader( fragmentShader );
  18388. gl.compileShader( vertexShader );
  18389. gl.attachShader( program, fragmentShader );
  18390. gl.attachShader( program, vertexShader );
  18391. gl.linkProgram( program );
  18392. return program;
  18393. }
  18394. };
  18395. // File:src/renderers/webgl/plugins/SpritePlugin.js
  18396. /**
  18397. * @author mikael emtinger / http://gomo.se/
  18398. * @author alteredq / http://alteredqualia.com/
  18399. */
  18400. THREE.SpritePlugin = function ( renderer, sprites ) {
  18401. var gl = renderer.context;
  18402. var state = renderer.state;
  18403. var vertexBuffer, elementBuffer;
  18404. var program, attributes, uniforms;
  18405. var texture;
  18406. // decompose matrixWorld
  18407. var spritePosition = new THREE.Vector3();
  18408. var spriteRotation = new THREE.Quaternion();
  18409. var spriteScale = new THREE.Vector3();
  18410. function init() {
  18411. var vertices = new Float32Array( [
  18412. - 0.5, - 0.5, 0, 0,
  18413. 0.5, - 0.5, 1, 0,
  18414. 0.5, 0.5, 1, 1,
  18415. - 0.5, 0.5, 0, 1
  18416. ] );
  18417. var faces = new Uint16Array( [
  18418. 0, 1, 2,
  18419. 0, 2, 3
  18420. ] );
  18421. vertexBuffer = gl.createBuffer();
  18422. elementBuffer = gl.createBuffer();
  18423. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  18424. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  18425. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  18426. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  18427. program = createProgram();
  18428. attributes = {
  18429. position: gl.getAttribLocation ( program, 'position' ),
  18430. uv: gl.getAttribLocation ( program, 'uv' )
  18431. };
  18432. uniforms = {
  18433. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  18434. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  18435. rotation: gl.getUniformLocation( program, 'rotation' ),
  18436. scale: gl.getUniformLocation( program, 'scale' ),
  18437. color: gl.getUniformLocation( program, 'color' ),
  18438. map: gl.getUniformLocation( program, 'map' ),
  18439. opacity: gl.getUniformLocation( program, 'opacity' ),
  18440. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  18441. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  18442. fogType: gl.getUniformLocation( program, 'fogType' ),
  18443. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  18444. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  18445. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  18446. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  18447. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  18448. };
  18449. var canvas = document.createElement( 'canvas' );
  18450. canvas.width = 8;
  18451. canvas.height = 8;
  18452. var context = canvas.getContext( '2d' );
  18453. context.fillStyle = 'white';
  18454. context.fillRect( 0, 0, 8, 8 );
  18455. texture = new THREE.Texture( canvas );
  18456. texture.needsUpdate = true;
  18457. }
  18458. this.render = function ( scene, camera ) {
  18459. if ( sprites.length === 0 ) return;
  18460. // setup gl
  18461. if ( program === undefined ) {
  18462. init();
  18463. }
  18464. gl.useProgram( program );
  18465. state.initAttributes();
  18466. state.enableAttribute( attributes.position );
  18467. state.enableAttribute( attributes.uv );
  18468. state.disableUnusedAttributes();
  18469. state.disable( gl.CULL_FACE );
  18470. state.enable( gl.BLEND );
  18471. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  18472. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  18473. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  18474. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  18475. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  18476. state.activeTexture( gl.TEXTURE0 );
  18477. gl.uniform1i( uniforms.map, 0 );
  18478. var oldFogType = 0;
  18479. var sceneFogType = 0;
  18480. var fog = scene.fog;
  18481. if ( fog ) {
  18482. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  18483. if ( fog instanceof THREE.Fog ) {
  18484. gl.uniform1f( uniforms.fogNear, fog.near );
  18485. gl.uniform1f( uniforms.fogFar, fog.far );
  18486. gl.uniform1i( uniforms.fogType, 1 );
  18487. oldFogType = 1;
  18488. sceneFogType = 1;
  18489. } else if ( fog instanceof THREE.FogExp2 ) {
  18490. gl.uniform1f( uniforms.fogDensity, fog.density );
  18491. gl.uniform1i( uniforms.fogType, 2 );
  18492. oldFogType = 2;
  18493. sceneFogType = 2;
  18494. }
  18495. } else {
  18496. gl.uniform1i( uniforms.fogType, 0 );
  18497. oldFogType = 0;
  18498. sceneFogType = 0;
  18499. }
  18500. // update positions and sort
  18501. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  18502. var sprite = sprites[ i ];
  18503. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  18504. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  18505. }
  18506. sprites.sort( painterSortStable );
  18507. // render all sprites
  18508. var scale = [];
  18509. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  18510. var sprite = sprites[ i ];
  18511. var material = sprite.material;
  18512. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  18513. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  18514. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  18515. scale[ 0 ] = spriteScale.x;
  18516. scale[ 1 ] = spriteScale.y;
  18517. var fogType = 0;
  18518. if ( scene.fog && material.fog ) {
  18519. fogType = sceneFogType;
  18520. }
  18521. if ( oldFogType !== fogType ) {
  18522. gl.uniform1i( uniforms.fogType, fogType );
  18523. oldFogType = fogType;
  18524. }
  18525. if ( material.map !== null ) {
  18526. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  18527. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  18528. } else {
  18529. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  18530. gl.uniform2f( uniforms.uvScale, 1, 1 );
  18531. }
  18532. gl.uniform1f( uniforms.opacity, material.opacity );
  18533. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  18534. gl.uniform1f( uniforms.rotation, material.rotation );
  18535. gl.uniform2fv( uniforms.scale, scale );
  18536. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  18537. state.setDepthTest( material.depthTest );
  18538. state.setDepthWrite( material.depthWrite );
  18539. if ( material.map && material.map.image && material.map.image.width ) {
  18540. renderer.setTexture( material.map, 0 );
  18541. } else {
  18542. renderer.setTexture( texture, 0 );
  18543. }
  18544. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  18545. }
  18546. // restore gl
  18547. state.enable( gl.CULL_FACE );
  18548. renderer.resetGLState();
  18549. };
  18550. function createProgram () {
  18551. var program = gl.createProgram();
  18552. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  18553. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  18554. gl.shaderSource( vertexShader, [
  18555. 'precision ' + renderer.getPrecision() + ' float;',
  18556. 'uniform mat4 modelViewMatrix;',
  18557. 'uniform mat4 projectionMatrix;',
  18558. 'uniform float rotation;',
  18559. 'uniform vec2 scale;',
  18560. 'uniform vec2 uvOffset;',
  18561. 'uniform vec2 uvScale;',
  18562. 'attribute vec2 position;',
  18563. 'attribute vec2 uv;',
  18564. 'varying vec2 vUV;',
  18565. 'void main() {',
  18566. 'vUV = uvOffset + uv * uvScale;',
  18567. 'vec2 alignedPosition = position * scale;',
  18568. 'vec2 rotatedPosition;',
  18569. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  18570. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  18571. 'vec4 finalPosition;',
  18572. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  18573. 'finalPosition.xy += rotatedPosition;',
  18574. 'finalPosition = projectionMatrix * finalPosition;',
  18575. 'gl_Position = finalPosition;',
  18576. '}'
  18577. ].join( '\n' ) );
  18578. gl.shaderSource( fragmentShader, [
  18579. 'precision ' + renderer.getPrecision() + ' float;',
  18580. 'uniform vec3 color;',
  18581. 'uniform sampler2D map;',
  18582. 'uniform float opacity;',
  18583. 'uniform int fogType;',
  18584. 'uniform vec3 fogColor;',
  18585. 'uniform float fogDensity;',
  18586. 'uniform float fogNear;',
  18587. 'uniform float fogFar;',
  18588. 'uniform float alphaTest;',
  18589. 'varying vec2 vUV;',
  18590. 'void main() {',
  18591. 'vec4 texture = texture2D( map, vUV );',
  18592. 'if ( texture.a < alphaTest ) discard;',
  18593. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  18594. 'if ( fogType > 0 ) {',
  18595. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  18596. 'float fogFactor = 0.0;',
  18597. 'if ( fogType == 1 ) {',
  18598. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  18599. '} else {',
  18600. 'const float LOG2 = 1.442695;',
  18601. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  18602. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  18603. '}',
  18604. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  18605. '}',
  18606. '}'
  18607. ].join( '\n' ) );
  18608. gl.compileShader( vertexShader );
  18609. gl.compileShader( fragmentShader );
  18610. gl.attachShader( program, vertexShader );
  18611. gl.attachShader( program, fragmentShader );
  18612. gl.linkProgram( program );
  18613. return program;
  18614. }
  18615. function painterSortStable ( a, b ) {
  18616. if ( a.z !== b.z ) {
  18617. return b.z - a.z;
  18618. } else {
  18619. return b.id - a.id;
  18620. }
  18621. }
  18622. };
  18623. // File:src/Three.Legacy.js
  18624. /**
  18625. * @author mrdoob / http://mrdoob.com/
  18626. */
  18627. Object.defineProperties( THREE.Box2.prototype, {
  18628. isIntersectionBox: {
  18629. value: function ( box ) {
  18630. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  18631. return this.intersectsBox( box );
  18632. }
  18633. }
  18634. } );
  18635. Object.defineProperties( THREE.Box3.prototype, {
  18636. isIntersectionBox: {
  18637. value: function ( box ) {
  18638. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  18639. return this.intersectsBox( box );
  18640. }
  18641. },
  18642. isIntersectionSphere: {
  18643. value: function ( sphere ) {
  18644. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  18645. return this.intersectsSphere( sphere );
  18646. }
  18647. }
  18648. } );
  18649. Object.defineProperties( THREE.Matrix3.prototype, {
  18650. multiplyVector3: {
  18651. value: function ( vector ) {
  18652. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  18653. return vector.applyMatrix3( this );
  18654. }
  18655. },
  18656. multiplyVector3Array: {
  18657. value: function ( a ) {
  18658. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  18659. return this.applyToVector3Array( a );
  18660. }
  18661. }
  18662. } );
  18663. Object.defineProperties( THREE.Matrix4.prototype, {
  18664. extractPosition: {
  18665. value: function ( m ) {
  18666. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  18667. return this.copyPosition( m );
  18668. }
  18669. },
  18670. setRotationFromQuaternion: {
  18671. value: function ( q ) {
  18672. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  18673. return this.makeRotationFromQuaternion( q );
  18674. }
  18675. },
  18676. multiplyVector3: {
  18677. value: function ( vector ) {
  18678. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  18679. return vector.applyProjection( this );
  18680. }
  18681. },
  18682. multiplyVector4: {
  18683. value: function ( vector ) {
  18684. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  18685. return vector.applyMatrix4( this );
  18686. }
  18687. },
  18688. multiplyVector3Array: {
  18689. value: function ( a ) {
  18690. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  18691. return this.applyToVector3Array( a );
  18692. }
  18693. },
  18694. rotateAxis: {
  18695. value: function ( v ) {
  18696. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  18697. v.transformDirection( this );
  18698. }
  18699. },
  18700. crossVector: {
  18701. value: function ( vector ) {
  18702. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  18703. return vector.applyMatrix4( this );
  18704. }
  18705. },
  18706. translate: {
  18707. value: function ( v ) {
  18708. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  18709. }
  18710. },
  18711. rotateX: {
  18712. value: function ( angle ) {
  18713. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  18714. }
  18715. },
  18716. rotateY: {
  18717. value: function ( angle ) {
  18718. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  18719. }
  18720. },
  18721. rotateZ: {
  18722. value: function ( angle ) {
  18723. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  18724. }
  18725. },
  18726. rotateByAxis: {
  18727. value: function ( axis, angle ) {
  18728. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  18729. }
  18730. }
  18731. } );
  18732. Object.defineProperties( THREE.Plane.prototype, {
  18733. isIntersectionLine: {
  18734. value: function ( line ) {
  18735. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  18736. return this.intersectsLine( line );
  18737. }
  18738. }
  18739. } );
  18740. Object.defineProperties( THREE.Quaternion.prototype, {
  18741. multiplyVector3: {
  18742. value: function ( vector ) {
  18743. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  18744. return vector.applyQuaternion( this );
  18745. }
  18746. }
  18747. } );
  18748. Object.defineProperties( THREE.Ray.prototype, {
  18749. isIntersectionBox: {
  18750. value: function ( box ) {
  18751. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  18752. return this.intersectsBox( box );
  18753. }
  18754. },
  18755. isIntersectionPlane: {
  18756. value: function ( plane ) {
  18757. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  18758. return this.intersectsPlane( plane );
  18759. }
  18760. },
  18761. isIntersectionSphere: {
  18762. value: function ( sphere ) {
  18763. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  18764. return this.intersectsSphere( sphere );
  18765. }
  18766. }
  18767. } );
  18768. Object.defineProperties( THREE.Vector3.prototype, {
  18769. setEulerFromRotationMatrix: {
  18770. value: function () {
  18771. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  18772. }
  18773. },
  18774. setEulerFromQuaternion: {
  18775. value: function () {
  18776. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  18777. }
  18778. },
  18779. getPositionFromMatrix: {
  18780. value: function ( m ) {
  18781. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  18782. return this.setFromMatrixPosition( m );
  18783. }
  18784. },
  18785. getScaleFromMatrix: {
  18786. value: function ( m ) {
  18787. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  18788. return this.setFromMatrixScale( m );
  18789. }
  18790. },
  18791. getColumnFromMatrix: {
  18792. value: function ( index, matrix ) {
  18793. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  18794. return this.setFromMatrixColumn( index, matrix );
  18795. }
  18796. }
  18797. } );
  18798. //
  18799. Object.defineProperties( THREE.Object3D.prototype, {
  18800. eulerOrder: {
  18801. get: function () {
  18802. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  18803. return this.rotation.order;
  18804. },
  18805. set: function ( value ) {
  18806. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  18807. this.rotation.order = value;
  18808. }
  18809. },
  18810. getChildByName: {
  18811. value: function ( name ) {
  18812. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  18813. return this.getObjectByName( name );
  18814. }
  18815. },
  18816. renderDepth: {
  18817. set: function ( value ) {
  18818. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  18819. }
  18820. },
  18821. translate: {
  18822. value: function ( distance, axis ) {
  18823. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  18824. return this.translateOnAxis( axis, distance );
  18825. }
  18826. },
  18827. useQuaternion: {
  18828. get: function () {
  18829. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  18830. },
  18831. set: function ( value ) {
  18832. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  18833. }
  18834. }
  18835. } );
  18836. //
  18837. Object.defineProperties( THREE, {
  18838. PointCloud: {
  18839. value: function ( geometry, material ) {
  18840. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  18841. return new THREE.Points( geometry, material );
  18842. }
  18843. },
  18844. ParticleSystem: {
  18845. value: function ( geometry, material ) {
  18846. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  18847. return new THREE.Points( geometry, material );
  18848. }
  18849. }
  18850. } );
  18851. //
  18852. Object.defineProperties( THREE.Light.prototype, {
  18853. onlyShadow: {
  18854. set: function ( value ) {
  18855. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  18856. }
  18857. },
  18858. shadowCameraFov: {
  18859. set: function ( value ) {
  18860. this.shadow.camera.fov = value;
  18861. }
  18862. },
  18863. shadowCameraLeft: {
  18864. set: function ( value ) {
  18865. this.shadow.camera.left = value;
  18866. }
  18867. },
  18868. shadowCameraRight: {
  18869. set: function ( value ) {
  18870. this.shadow.camera.right = value;
  18871. }
  18872. },
  18873. shadowCameraTop: {
  18874. set: function ( value ) {
  18875. this.shadow.camera.top = value;
  18876. }
  18877. },
  18878. shadowCameraBottom: {
  18879. set: function ( value ) {
  18880. this.shadow.camera.bottom = value;
  18881. }
  18882. },
  18883. shadowCameraNear: {
  18884. set: function ( value ) {
  18885. this.shadow.camera.near = value;
  18886. }
  18887. },
  18888. shadowCameraFar: {
  18889. set: function ( value ) {
  18890. this.shadow.camera.far = value;
  18891. }
  18892. },
  18893. shadowCameraVisible: {
  18894. set: function ( value ) {
  18895. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow ) instead.' );
  18896. }
  18897. },
  18898. shadowBias: {
  18899. set: function ( value ) {
  18900. this.shadow.bias = value;
  18901. }
  18902. },
  18903. shadowDarkness: {
  18904. set: function ( value ) {
  18905. this.shadow.darkness = value;
  18906. }
  18907. },
  18908. shadowMapWidth: {
  18909. set: function ( value ) {
  18910. this.shadow.mapSize.width = value;
  18911. }
  18912. },
  18913. shadowMapHeight: {
  18914. set: function ( value ) {
  18915. this.shadow.mapSize.height = value;
  18916. }
  18917. }
  18918. } );
  18919. //
  18920. Object.defineProperties( THREE.Material.prototype, {
  18921. wrapAround: {
  18922. get: function () {
  18923. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  18924. },
  18925. set: function ( value ) {
  18926. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  18927. }
  18928. },
  18929. wrapRGB: {
  18930. get: function () {
  18931. console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' );
  18932. return new THREE.Color();
  18933. }
  18934. }
  18935. } );
  18936. Object.defineProperties( THREE, {
  18937. PointCloudMaterial: {
  18938. value: function ( parameters ) {
  18939. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  18940. return new THREE.PointsMaterial( parameters );
  18941. }
  18942. },
  18943. ParticleBasicMaterial: {
  18944. value: function ( parameters ) {
  18945. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  18946. return new THREE.PointsMaterial( parameters );
  18947. }
  18948. },
  18949. ParticleSystemMaterial:{
  18950. value: function ( parameters ) {
  18951. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  18952. return new THREE.PointsMaterial( parameters );
  18953. }
  18954. }
  18955. } );
  18956. Object.defineProperties( THREE.MeshPhongMaterial.prototype, {
  18957. metal: {
  18958. get: function () {
  18959. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshPhysicalMaterial instead.' );
  18960. return false;
  18961. },
  18962. set: function ( value ) {
  18963. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshPhysicalMaterial instead' );
  18964. }
  18965. }
  18966. } );
  18967. Object.defineProperties( THREE.ShaderMaterial.prototype, {
  18968. derivatives: {
  18969. get: function () {
  18970. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  18971. return this.extensions.derivatives;
  18972. },
  18973. set: function ( value ) {
  18974. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  18975. this.extensions.derivatives = value;
  18976. }
  18977. }
  18978. } );
  18979. //
  18980. Object.defineProperties( THREE.WebGLRenderer.prototype, {
  18981. supportsFloatTextures: {
  18982. value: function () {
  18983. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  18984. return this.extensions.get( 'OES_texture_float' );
  18985. }
  18986. },
  18987. supportsHalfFloatTextures: {
  18988. value: function () {
  18989. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  18990. return this.extensions.get( 'OES_texture_half_float' );
  18991. }
  18992. },
  18993. supportsStandardDerivatives: {
  18994. value: function () {
  18995. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  18996. return this.extensions.get( 'OES_standard_derivatives' );
  18997. }
  18998. },
  18999. supportsCompressedTextureS3TC: {
  19000. value: function () {
  19001. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  19002. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  19003. }
  19004. },
  19005. supportsCompressedTexturePVRTC: {
  19006. value: function () {
  19007. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  19008. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  19009. }
  19010. },
  19011. supportsBlendMinMax: {
  19012. value: function () {
  19013. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  19014. return this.extensions.get( 'EXT_blend_minmax' );
  19015. }
  19016. },
  19017. supportsVertexTextures: {
  19018. value: function () {
  19019. return this.capabilities.vertexTextures;
  19020. }
  19021. },
  19022. supportsInstancedArrays: {
  19023. value: function () {
  19024. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  19025. return this.extensions.get( 'ANGLE_instanced_arrays' );
  19026. }
  19027. },
  19028. initMaterial: {
  19029. value: function () {
  19030. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  19031. }
  19032. },
  19033. addPrePlugin: {
  19034. value: function () {
  19035. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  19036. }
  19037. },
  19038. addPostPlugin: {
  19039. value: function () {
  19040. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  19041. }
  19042. },
  19043. updateShadowMap: {
  19044. value: function () {
  19045. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  19046. }
  19047. },
  19048. shadowMapEnabled: {
  19049. get: function () {
  19050. return this.shadowMap.enabled;
  19051. },
  19052. set: function ( value ) {
  19053. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  19054. this.shadowMap.enabled = value;
  19055. }
  19056. },
  19057. shadowMapType: {
  19058. get: function () {
  19059. return this.shadowMap.type;
  19060. },
  19061. set: function ( value ) {
  19062. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  19063. this.shadowMap.type = value;
  19064. }
  19065. },
  19066. shadowMapCullFace: {
  19067. get: function () {
  19068. return this.shadowMap.cullFace;
  19069. },
  19070. set: function ( value ) {
  19071. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  19072. this.shadowMap.cullFace = value;
  19073. }
  19074. },
  19075. shadowMapDebug: {
  19076. get: function () {
  19077. return this.shadowMap.debug;
  19078. },
  19079. set: function ( value ) {
  19080. console.warn( 'THREE.WebGLRenderer: .shadowMapDebug is now .shadowMap.debug.' );
  19081. this.shadowMap.debug = value;
  19082. }
  19083. }
  19084. } );
  19085. //
  19086. Object.defineProperties( THREE.WebGLRenderTarget.prototype, {
  19087. wrapS: {
  19088. get: function () {
  19089. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  19090. return this.texture.wrapS;
  19091. },
  19092. set: function ( value ) {
  19093. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  19094. this.texture.wrapS = value;
  19095. }
  19096. },
  19097. wrapT: {
  19098. get: function () {
  19099. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  19100. return this.texture.wrapT;
  19101. },
  19102. set: function ( value ) {
  19103. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  19104. this.texture.wrapT = value;
  19105. }
  19106. },
  19107. magFilter: {
  19108. get: function () {
  19109. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  19110. return this.texture.magFilter;
  19111. },
  19112. set: function ( value ) {
  19113. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  19114. this.texture.magFilter = value;
  19115. }
  19116. },
  19117. minFilter: {
  19118. get: function () {
  19119. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  19120. return this.texture.minFilter;
  19121. },
  19122. set: function ( value ) {
  19123. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  19124. this.texture.minFilter = value;
  19125. }
  19126. },
  19127. anisotropy: {
  19128. get: function () {
  19129. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  19130. return this.texture.anisotropy;
  19131. },
  19132. set: function ( value ) {
  19133. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  19134. this.texture.anisotropy = value;
  19135. }
  19136. },
  19137. offset: {
  19138. get: function () {
  19139. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  19140. return this.texture.offset;
  19141. },
  19142. set: function ( value ) {
  19143. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  19144. this.texture.offset = value;
  19145. }
  19146. },
  19147. repeat: {
  19148. get: function () {
  19149. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  19150. return this.texture.repeat;
  19151. },
  19152. set: function ( value ) {
  19153. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  19154. this.texture.repeat = value;
  19155. }
  19156. },
  19157. format: {
  19158. get: function () {
  19159. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  19160. return this.texture.format;
  19161. },
  19162. set: function ( value ) {
  19163. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  19164. this.texture.format = value;
  19165. }
  19166. },
  19167. type: {
  19168. get: function () {
  19169. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  19170. return this.texture.type;
  19171. },
  19172. set: function ( value ) {
  19173. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  19174. this.texture.type = value;
  19175. }
  19176. },
  19177. generateMipmaps: {
  19178. get: function () {
  19179. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  19180. return this.texture.generateMipmaps;
  19181. },
  19182. set: function ( value ) {
  19183. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  19184. this.texture.generateMipmaps = value;
  19185. }
  19186. }
  19187. } );
  19188. //
  19189. THREE.GeometryUtils = {
  19190. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  19191. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  19192. var matrix;
  19193. if ( geometry2 instanceof THREE.Mesh ) {
  19194. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  19195. matrix = geometry2.matrix;
  19196. geometry2 = geometry2.geometry;
  19197. }
  19198. geometry1.merge( geometry2, matrix, materialIndexOffset );
  19199. },
  19200. center: function ( geometry ) {
  19201. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  19202. return geometry.center();
  19203. }
  19204. };
  19205. THREE.ImageUtils = {
  19206. crossOrigin: undefined,
  19207. loadTexture: function ( url, mapping, onLoad, onError ) {
  19208. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  19209. var loader = new THREE.TextureLoader();
  19210. loader.setCrossOrigin( this.crossOrigin );
  19211. var texture = loader.load( url, onLoad, undefined, onError );
  19212. if ( mapping ) texture.mapping = mapping;
  19213. return texture;
  19214. },
  19215. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  19216. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  19217. var loader = new THREE.CubeTextureLoader();
  19218. loader.setCrossOrigin( this.crossOrigin );
  19219. var texture = loader.load( urls, onLoad, undefined, onError );
  19220. if ( mapping ) texture.mapping = mapping;
  19221. return texture;
  19222. },
  19223. loadCompressedTexture: function () {
  19224. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' )
  19225. },
  19226. loadCompressedTextureCube: function () {
  19227. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' )
  19228. }
  19229. };
  19230. //
  19231. THREE.Projector = function () {
  19232. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  19233. this.projectVector = function ( vector, camera ) {
  19234. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  19235. vector.project( camera );
  19236. };
  19237. this.unprojectVector = function ( vector, camera ) {
  19238. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  19239. vector.unproject( camera );
  19240. };
  19241. this.pickingRay = function ( vector, camera ) {
  19242. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  19243. };
  19244. };
  19245. //
  19246. THREE.CanvasRenderer = function () {
  19247. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  19248. this.domElement = document.createElement( 'canvas' );
  19249. this.clear = function () {};
  19250. this.render = function () {};
  19251. this.setClearColor = function () {};
  19252. this.setSize = function () {};
  19253. };
  19254. // File:src/extras/CurveUtils.js
  19255. /**
  19256. * @author zz85 / http://www.lab4games.net/zz85/blog
  19257. */
  19258. THREE.CurveUtils = {
  19259. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  19260. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  19261. },
  19262. // Puay Bing, thanks for helping with this derivative!
  19263. tangentCubicBezier: function ( t, p0, p1, p2, p3 ) {
  19264. return - 3 * p0 * ( 1 - t ) * ( 1 - t ) +
  19265. 3 * p1 * ( 1 - t ) * ( 1 - t ) - 6 * t * p1 * ( 1 - t ) +
  19266. 6 * t * p2 * ( 1 - t ) - 3 * t * t * p2 +
  19267. 3 * t * t * p3;
  19268. },
  19269. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  19270. // To check if my formulas are correct
  19271. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  19272. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  19273. var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2
  19274. var h11 = 3 * t * t - 2 * t; // t3 − t2
  19275. return h00 + h10 + h01 + h11;
  19276. },
  19277. // Catmull-Rom
  19278. interpolate: function( p0, p1, p2, p3, t ) {
  19279. var v0 = ( p2 - p0 ) * 0.5;
  19280. var v1 = ( p3 - p1 ) * 0.5;
  19281. var t2 = t * t;
  19282. var t3 = t * t2;
  19283. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19284. }
  19285. };
  19286. // File:src/extras/SceneUtils.js
  19287. /**
  19288. * @author alteredq / http://alteredqualia.com/
  19289. */
  19290. THREE.SceneUtils = {
  19291. createMultiMaterialObject: function ( geometry, materials ) {
  19292. var group = new THREE.Group();
  19293. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  19294. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  19295. }
  19296. return group;
  19297. },
  19298. detach: function ( child, parent, scene ) {
  19299. child.applyMatrix( parent.matrixWorld );
  19300. parent.remove( child );
  19301. scene.add( child );
  19302. },
  19303. attach: function ( child, scene, parent ) {
  19304. var matrixWorldInverse = new THREE.Matrix4();
  19305. matrixWorldInverse.getInverse( parent.matrixWorld );
  19306. child.applyMatrix( matrixWorldInverse );
  19307. scene.remove( child );
  19308. parent.add( child );
  19309. }
  19310. };
  19311. // File:src/extras/ShapeUtils.js
  19312. /**
  19313. * @author zz85 / http://www.lab4games.net/zz85/blog
  19314. */
  19315. THREE.ShapeUtils = {
  19316. // calculate area of the contour polygon
  19317. area: function ( contour ) {
  19318. var n = contour.length;
  19319. var a = 0.0;
  19320. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  19321. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  19322. }
  19323. return a * 0.5;
  19324. },
  19325. triangulate: ( function () {
  19326. /**
  19327. * This code is a quick port of code written in C++ which was submitted to
  19328. * flipcode.com by John W. Ratcliff // July 22, 2000
  19329. * See original code and more information here:
  19330. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  19331. *
  19332. * ported to actionscript by Zevan Rosser
  19333. * www.actionsnippet.com
  19334. *
  19335. * ported to javascript by Joshua Koo
  19336. * http://www.lab4games.net/zz85/blog
  19337. *
  19338. */
  19339. function snip( contour, u, v, w, n, verts ) {
  19340. var p;
  19341. var ax, ay, bx, by;
  19342. var cx, cy, px, py;
  19343. ax = contour[ verts[ u ] ].x;
  19344. ay = contour[ verts[ u ] ].y;
  19345. bx = contour[ verts[ v ] ].x;
  19346. by = contour[ verts[ v ] ].y;
  19347. cx = contour[ verts[ w ] ].x;
  19348. cy = contour[ verts[ w ] ].y;
  19349. if ( Number.EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false;
  19350. var aX, aY, bX, bY, cX, cY;
  19351. var apx, apy, bpx, bpy, cpx, cpy;
  19352. var cCROSSap, bCROSScp, aCROSSbp;
  19353. aX = cx - bx; aY = cy - by;
  19354. bX = ax - cx; bY = ay - cy;
  19355. cX = bx - ax; cY = by - ay;
  19356. for ( p = 0; p < n; p ++ ) {
  19357. px = contour[ verts[ p ] ].x;
  19358. py = contour[ verts[ p ] ].y;
  19359. if ( ( ( px === ax ) && ( py === ay ) ) ||
  19360. ( ( px === bx ) && ( py === by ) ) ||
  19361. ( ( px === cx ) && ( py === cy ) ) ) continue;
  19362. apx = px - ax; apy = py - ay;
  19363. bpx = px - bx; bpy = py - by;
  19364. cpx = px - cx; cpy = py - cy;
  19365. // see if p is inside triangle abc
  19366. aCROSSbp = aX * bpy - aY * bpx;
  19367. cCROSSap = cX * apy - cY * apx;
  19368. bCROSScp = bX * cpy - bY * cpx;
  19369. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  19370. }
  19371. return true;
  19372. }
  19373. // takes in an contour array and returns
  19374. return function ( contour, indices ) {
  19375. var n = contour.length;
  19376. if ( n < 3 ) return null;
  19377. var result = [],
  19378. verts = [],
  19379. vertIndices = [];
  19380. /* we want a counter-clockwise polygon in verts */
  19381. var u, v, w;
  19382. if ( THREE.ShapeUtils.area( contour ) > 0.0 ) {
  19383. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  19384. } else {
  19385. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  19386. }
  19387. var nv = n;
  19388. /* remove nv - 2 vertices, creating 1 triangle every time */
  19389. var count = 2 * nv; /* error detection */
  19390. for ( v = nv - 1; nv > 2; ) {
  19391. /* if we loop, it is probably a non-simple polygon */
  19392. if ( ( count -- ) <= 0 ) {
  19393. //** Triangulate: ERROR - probable bad polygon!
  19394. //throw ( "Warning, unable to triangulate polygon!" );
  19395. //return null;
  19396. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  19397. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  19398. if ( indices ) return vertIndices;
  19399. return result;
  19400. }
  19401. /* three consecutive vertices in current polygon, <u,v,w> */
  19402. u = v; if ( nv <= u ) u = 0; /* previous */
  19403. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  19404. w = v + 1; if ( nv <= w ) w = 0; /* next */
  19405. if ( snip( contour, u, v, w, nv, verts ) ) {
  19406. var a, b, c, s, t;
  19407. /* true names of the vertices */
  19408. a = verts[ u ];
  19409. b = verts[ v ];
  19410. c = verts[ w ];
  19411. /* output Triangle */
  19412. result.push( [ contour[ a ],
  19413. contour[ b ],
  19414. contour[ c ] ] );
  19415. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  19416. /* remove v from the remaining polygon */
  19417. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  19418. verts[ s ] = verts[ t ];
  19419. }
  19420. nv --;
  19421. /* reset error detection counter */
  19422. count = 2 * nv;
  19423. }
  19424. }
  19425. if ( indices ) return vertIndices;
  19426. return result;
  19427. }
  19428. } )(),
  19429. triangulateShape: function ( contour, holes ) {
  19430. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  19431. // inOtherPt needs to be collinear to the inSegment
  19432. if ( inSegPt1.x !== inSegPt2.x ) {
  19433. if ( inSegPt1.x < inSegPt2.x ) {
  19434. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  19435. } else {
  19436. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  19437. }
  19438. } else {
  19439. if ( inSegPt1.y < inSegPt2.y ) {
  19440. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  19441. } else {
  19442. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  19443. }
  19444. }
  19445. }
  19446. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  19447. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  19448. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  19449. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  19450. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  19451. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  19452. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  19453. if ( Math.abs( limit ) > Number.EPSILON ) {
  19454. // not parallel
  19455. var perpSeg2;
  19456. if ( limit > 0 ) {
  19457. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  19458. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  19459. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  19460. } else {
  19461. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  19462. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  19463. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  19464. }
  19465. // i.e. to reduce rounding errors
  19466. // intersection at endpoint of segment#1?
  19467. if ( perpSeg2 === 0 ) {
  19468. if ( ( inExcludeAdjacentSegs ) &&
  19469. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  19470. return [ inSeg1Pt1 ];
  19471. }
  19472. if ( perpSeg2 === limit ) {
  19473. if ( ( inExcludeAdjacentSegs ) &&
  19474. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  19475. return [ inSeg1Pt2 ];
  19476. }
  19477. // intersection at endpoint of segment#2?
  19478. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  19479. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  19480. // return real intersection point
  19481. var factorSeg1 = perpSeg2 / limit;
  19482. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  19483. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  19484. } else {
  19485. // parallel or collinear
  19486. if ( ( perpSeg1 !== 0 ) ||
  19487. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  19488. // they are collinear or degenerate
  19489. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  19490. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  19491. // both segments are points
  19492. if ( seg1Pt && seg2Pt ) {
  19493. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  19494. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  19495. return [ inSeg1Pt1 ]; // they are the same point
  19496. }
  19497. // segment#1 is a single point
  19498. if ( seg1Pt ) {
  19499. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  19500. return [ inSeg1Pt1 ];
  19501. }
  19502. // segment#2 is a single point
  19503. if ( seg2Pt ) {
  19504. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  19505. return [ inSeg2Pt1 ];
  19506. }
  19507. // they are collinear segments, which might overlap
  19508. var seg1min, seg1max, seg1minVal, seg1maxVal;
  19509. var seg2min, seg2max, seg2minVal, seg2maxVal;
  19510. if ( seg1dx !== 0 ) {
  19511. // the segments are NOT on a vertical line
  19512. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  19513. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  19514. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  19515. } else {
  19516. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  19517. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  19518. }
  19519. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  19520. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  19521. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  19522. } else {
  19523. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  19524. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  19525. }
  19526. } else {
  19527. // the segments are on a vertical line
  19528. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  19529. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  19530. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  19531. } else {
  19532. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  19533. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  19534. }
  19535. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  19536. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  19537. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  19538. } else {
  19539. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  19540. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  19541. }
  19542. }
  19543. if ( seg1minVal <= seg2minVal ) {
  19544. if ( seg1maxVal < seg2minVal ) return [];
  19545. if ( seg1maxVal === seg2minVal ) {
  19546. if ( inExcludeAdjacentSegs ) return [];
  19547. return [ seg2min ];
  19548. }
  19549. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  19550. return [ seg2min, seg2max ];
  19551. } else {
  19552. if ( seg1minVal > seg2maxVal ) return [];
  19553. if ( seg1minVal === seg2maxVal ) {
  19554. if ( inExcludeAdjacentSegs ) return [];
  19555. return [ seg1min ];
  19556. }
  19557. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  19558. return [ seg1min, seg2max ];
  19559. }
  19560. }
  19561. }
  19562. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  19563. // The order of legs is important
  19564. // translation of all points, so that Vertex is at (0,0)
  19565. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  19566. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  19567. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  19568. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  19569. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  19570. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  19571. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  19572. // angle != 180 deg.
  19573. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  19574. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  19575. if ( from2toAngle > 0 ) {
  19576. // main angle < 180 deg.
  19577. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  19578. } else {
  19579. // main angle > 180 deg.
  19580. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  19581. }
  19582. } else {
  19583. // angle == 180 deg.
  19584. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  19585. return ( from2otherAngle > 0 );
  19586. }
  19587. }
  19588. function removeHoles( contour, holes ) {
  19589. var shape = contour.concat(); // work on this shape
  19590. var hole;
  19591. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  19592. // Check if hole point lies within angle around shape point
  19593. var lastShapeIdx = shape.length - 1;
  19594. var prevShapeIdx = inShapeIdx - 1;
  19595. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  19596. var nextShapeIdx = inShapeIdx + 1;
  19597. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  19598. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  19599. if ( ! insideAngle ) {
  19600. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  19601. return false;
  19602. }
  19603. // Check if shape point lies within angle around hole point
  19604. var lastHoleIdx = hole.length - 1;
  19605. var prevHoleIdx = inHoleIdx - 1;
  19606. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  19607. var nextHoleIdx = inHoleIdx + 1;
  19608. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  19609. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  19610. if ( ! insideAngle ) {
  19611. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  19612. return false;
  19613. }
  19614. return true;
  19615. }
  19616. function intersectsShapeEdge( inShapePt, inHolePt ) {
  19617. // checks for intersections with shape edges
  19618. var sIdx, nextIdx, intersection;
  19619. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  19620. nextIdx = sIdx + 1; nextIdx %= shape.length;
  19621. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  19622. if ( intersection.length > 0 ) return true;
  19623. }
  19624. return false;
  19625. }
  19626. var indepHoles = [];
  19627. function intersectsHoleEdge( inShapePt, inHolePt ) {
  19628. // checks for intersections with hole edges
  19629. var ihIdx, chkHole,
  19630. hIdx, nextIdx, intersection;
  19631. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  19632. chkHole = holes[ indepHoles[ ihIdx ]];
  19633. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  19634. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  19635. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  19636. if ( intersection.length > 0 ) return true;
  19637. }
  19638. }
  19639. return false;
  19640. }
  19641. var holeIndex, shapeIndex,
  19642. shapePt, holePt,
  19643. holeIdx, cutKey, failedCuts = [],
  19644. tmpShape1, tmpShape2,
  19645. tmpHole1, tmpHole2;
  19646. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  19647. indepHoles.push( h );
  19648. }
  19649. var minShapeIndex = 0;
  19650. var counter = indepHoles.length * 2;
  19651. while ( indepHoles.length > 0 ) {
  19652. counter --;
  19653. if ( counter < 0 ) {
  19654. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  19655. break;
  19656. }
  19657. // search for shape-vertex and hole-vertex,
  19658. // which can be connected without intersections
  19659. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  19660. shapePt = shape[ shapeIndex ];
  19661. holeIndex = - 1;
  19662. // search for hole which can be reached without intersections
  19663. for ( var h = 0; h < indepHoles.length; h ++ ) {
  19664. holeIdx = indepHoles[ h ];
  19665. // prevent multiple checks
  19666. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  19667. if ( failedCuts[ cutKey ] !== undefined ) continue;
  19668. hole = holes[ holeIdx ];
  19669. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  19670. holePt = hole[ h2 ];
  19671. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  19672. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  19673. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  19674. holeIndex = h2;
  19675. indepHoles.splice( h, 1 );
  19676. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  19677. tmpShape2 = shape.slice( shapeIndex );
  19678. tmpHole1 = hole.slice( holeIndex );
  19679. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  19680. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  19681. minShapeIndex = shapeIndex;
  19682. // Debug only, to show the selected cuts
  19683. // glob_CutLines.push( [ shapePt, holePt ] );
  19684. break;
  19685. }
  19686. if ( holeIndex >= 0 ) break; // hole-vertex found
  19687. failedCuts[ cutKey ] = true; // remember failure
  19688. }
  19689. if ( holeIndex >= 0 ) break; // hole-vertex found
  19690. }
  19691. }
  19692. return shape; /* shape with no holes */
  19693. }
  19694. var i, il, f, face,
  19695. key, index,
  19696. allPointsMap = {};
  19697. // To maintain reference to old shape, one must match coordinates, or offset the indices from original arrays. It's probably easier to do the first.
  19698. var allpoints = contour.concat();
  19699. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  19700. Array.prototype.push.apply( allpoints, holes[ h ] );
  19701. }
  19702. //console.log( "allpoints",allpoints, allpoints.length );
  19703. // prepare all points map
  19704. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  19705. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  19706. if ( allPointsMap[ key ] !== undefined ) {
  19707. console.warn( "THREE.Shape: Duplicate point", key );
  19708. }
  19709. allPointsMap[ key ] = i;
  19710. }
  19711. // remove holes by cutting paths to holes and adding them to the shape
  19712. var shapeWithoutHoles = removeHoles( contour, holes );
  19713. var triangles = THREE.ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  19714. //console.log( "triangles",triangles, triangles.length );
  19715. // check all face vertices against all points map
  19716. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  19717. face = triangles[ i ];
  19718. for ( f = 0; f < 3; f ++ ) {
  19719. key = face[ f ].x + ":" + face[ f ].y;
  19720. index = allPointsMap[ key ];
  19721. if ( index !== undefined ) {
  19722. face[ f ] = index;
  19723. }
  19724. }
  19725. }
  19726. return triangles.concat();
  19727. },
  19728. isClockWise: function ( pts ) {
  19729. return THREE.ShapeUtils.area( pts ) < 0;
  19730. },
  19731. // Bezier Curves formulas obtained from
  19732. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  19733. // Quad Bezier Functions
  19734. b2: ( function () {
  19735. function b2p0( t, p ) {
  19736. var k = 1 - t;
  19737. return k * k * p;
  19738. }
  19739. function b2p1( t, p ) {
  19740. return 2 * ( 1 - t ) * t * p;
  19741. }
  19742. function b2p2( t, p ) {
  19743. return t * t * p;
  19744. }
  19745. return function ( t, p0, p1, p2 ) {
  19746. return b2p0( t, p0 ) + b2p1( t, p1 ) + b2p2( t, p2 );
  19747. };
  19748. } )(),
  19749. // Cubic Bezier Functions
  19750. b3: ( function () {
  19751. function b3p0( t, p ) {
  19752. var k = 1 - t;
  19753. return k * k * k * p;
  19754. }
  19755. function b3p1( t, p ) {
  19756. var k = 1 - t;
  19757. return 3 * k * k * t * p;
  19758. }
  19759. function b3p2( t, p ) {
  19760. var k = 1 - t;
  19761. return 3 * k * t * t * p;
  19762. }
  19763. function b3p3( t, p ) {
  19764. return t * t * t * p;
  19765. }
  19766. return function ( t, p0, p1, p2, p3 ) {
  19767. return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 );
  19768. };
  19769. } )()
  19770. };
  19771. // File:src/extras/core/Curve.js
  19772. /**
  19773. * @author zz85 / http://www.lab4games.net/zz85/blog
  19774. * Extensible curve object
  19775. *
  19776. * Some common of Curve methods
  19777. * .getPoint(t), getTangent(t)
  19778. * .getPointAt(u), getTagentAt(u)
  19779. * .getPoints(), .getSpacedPoints()
  19780. * .getLength()
  19781. * .updateArcLengths()
  19782. *
  19783. * This following classes subclasses THREE.Curve:
  19784. *
  19785. * -- 2d classes --
  19786. * THREE.LineCurve
  19787. * THREE.QuadraticBezierCurve
  19788. * THREE.CubicBezierCurve
  19789. * THREE.SplineCurve
  19790. * THREE.ArcCurve
  19791. * THREE.EllipseCurve
  19792. *
  19793. * -- 3d classes --
  19794. * THREE.LineCurve3
  19795. * THREE.QuadraticBezierCurve3
  19796. * THREE.CubicBezierCurve3
  19797. * THREE.SplineCurve3
  19798. * THREE.ClosedSplineCurve3
  19799. *
  19800. * A series of curves can be represented as a THREE.CurvePath
  19801. *
  19802. **/
  19803. /**************************************************************
  19804. * Abstract Curve base class
  19805. **************************************************************/
  19806. THREE.Curve = function () {
  19807. };
  19808. THREE.Curve.prototype = {
  19809. constructor: THREE.Curve,
  19810. // Virtual base class method to overwrite and implement in subclasses
  19811. // - t [0 .. 1]
  19812. getPoint: function ( t ) {
  19813. console.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  19814. return null;
  19815. },
  19816. // Get point at relative position in curve according to arc length
  19817. // - u [0 .. 1]
  19818. getPointAt: function ( u ) {
  19819. var t = this.getUtoTmapping( u );
  19820. return this.getPoint( t );
  19821. },
  19822. // Get sequence of points using getPoint( t )
  19823. getPoints: function ( divisions ) {
  19824. if ( ! divisions ) divisions = 5;
  19825. var d, pts = [];
  19826. for ( d = 0; d <= divisions; d ++ ) {
  19827. pts.push( this.getPoint( d / divisions ) );
  19828. }
  19829. return pts;
  19830. },
  19831. // Get sequence of points using getPointAt( u )
  19832. getSpacedPoints: function ( divisions ) {
  19833. if ( ! divisions ) divisions = 5;
  19834. var d, pts = [];
  19835. for ( d = 0; d <= divisions; d ++ ) {
  19836. pts.push( this.getPointAt( d / divisions ) );
  19837. }
  19838. return pts;
  19839. },
  19840. // Get total curve arc length
  19841. getLength: function () {
  19842. var lengths = this.getLengths();
  19843. return lengths[ lengths.length - 1 ];
  19844. },
  19845. // Get list of cumulative segment lengths
  19846. getLengths: function ( divisions ) {
  19847. if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200;
  19848. if ( this.cacheArcLengths
  19849. && ( this.cacheArcLengths.length === divisions + 1 )
  19850. && ! this.needsUpdate ) {
  19851. //console.log( "cached", this.cacheArcLengths );
  19852. return this.cacheArcLengths;
  19853. }
  19854. this.needsUpdate = false;
  19855. var cache = [];
  19856. var current, last = this.getPoint( 0 );
  19857. var p, sum = 0;
  19858. cache.push( 0 );
  19859. for ( p = 1; p <= divisions; p ++ ) {
  19860. current = this.getPoint ( p / divisions );
  19861. sum += current.distanceTo( last );
  19862. cache.push( sum );
  19863. last = current;
  19864. }
  19865. this.cacheArcLengths = cache;
  19866. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  19867. },
  19868. updateArcLengths: function() {
  19869. this.needsUpdate = true;
  19870. this.getLengths();
  19871. },
  19872. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  19873. getUtoTmapping: function ( u, distance ) {
  19874. var arcLengths = this.getLengths();
  19875. var i = 0, il = arcLengths.length;
  19876. var targetArcLength; // The targeted u distance value to get
  19877. if ( distance ) {
  19878. targetArcLength = distance;
  19879. } else {
  19880. targetArcLength = u * arcLengths[ il - 1 ];
  19881. }
  19882. //var time = Date.now();
  19883. // binary search for the index with largest value smaller than target u distance
  19884. var low = 0, high = il - 1, comparison;
  19885. while ( low <= high ) {
  19886. 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
  19887. comparison = arcLengths[ i ] - targetArcLength;
  19888. if ( comparison < 0 ) {
  19889. low = i + 1;
  19890. } else if ( comparison > 0 ) {
  19891. high = i - 1;
  19892. } else {
  19893. high = i;
  19894. break;
  19895. // DONE
  19896. }
  19897. }
  19898. i = high;
  19899. //console.log('b' , i, low, high, Date.now()- time);
  19900. if ( arcLengths[ i ] === targetArcLength ) {
  19901. var t = i / ( il - 1 );
  19902. return t;
  19903. }
  19904. // we could get finer grain at lengths, or use simple interpolation between two points
  19905. var lengthBefore = arcLengths[ i ];
  19906. var lengthAfter = arcLengths[ i + 1 ];
  19907. var segmentLength = lengthAfter - lengthBefore;
  19908. // determine where we are between the 'before' and 'after' points
  19909. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  19910. // add that fractional amount to t
  19911. var t = ( i + segmentFraction ) / ( il - 1 );
  19912. return t;
  19913. },
  19914. // Returns a unit vector tangent at t
  19915. // In case any sub curve does not implement its tangent derivation,
  19916. // 2 points a small delta apart will be used to find its gradient
  19917. // which seems to give a reasonable approximation
  19918. getTangent: function( t ) {
  19919. var delta = 0.0001;
  19920. var t1 = t - delta;
  19921. var t2 = t + delta;
  19922. // Capping in case of danger
  19923. if ( t1 < 0 ) t1 = 0;
  19924. if ( t2 > 1 ) t2 = 1;
  19925. var pt1 = this.getPoint( t1 );
  19926. var pt2 = this.getPoint( t2 );
  19927. var vec = pt2.clone().sub( pt1 );
  19928. return vec.normalize();
  19929. },
  19930. getTangentAt: function ( u ) {
  19931. var t = this.getUtoTmapping( u );
  19932. return this.getTangent( t );
  19933. }
  19934. }
  19935. THREE.Curve.Utils = THREE.CurveUtils; // backwards compatibility
  19936. // TODO: Transformation for Curves?
  19937. /**************************************************************
  19938. * 3D Curves
  19939. **************************************************************/
  19940. // A Factory method for creating new curve subclasses
  19941. THREE.Curve.create = function ( constructor, getPointFunc ) {
  19942. constructor.prototype = Object.create( THREE.Curve.prototype );
  19943. constructor.prototype.constructor = constructor;
  19944. constructor.prototype.getPoint = getPointFunc;
  19945. return constructor;
  19946. };
  19947. // File:src/extras/core/CurvePath.js
  19948. /**
  19949. * @author zz85 / http://www.lab4games.net/zz85/blog
  19950. *
  19951. **/
  19952. /**************************************************************
  19953. * Curved Path - a curve path is simply a array of connected
  19954. * curves, but retains the api of a curve
  19955. **************************************************************/
  19956. THREE.CurvePath = function () {
  19957. this.curves = [];
  19958. this.autoClose = false; // Automatically closes the path
  19959. };
  19960. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  19961. THREE.CurvePath.prototype.constructor = THREE.CurvePath;
  19962. THREE.CurvePath.prototype.add = function ( curve ) {
  19963. this.curves.push( curve );
  19964. };
  19965. /*
  19966. THREE.CurvePath.prototype.checkConnection = function() {
  19967. // TODO
  19968. // If the ending of curve is not connected to the starting
  19969. // or the next curve, then, this is not a real path
  19970. };
  19971. */
  19972. THREE.CurvePath.prototype.closePath = function() {
  19973. // TODO Test
  19974. // and verify for vector3 (needs to implement equals)
  19975. // Add a line curve if start and end of lines are not connected
  19976. var startPoint = this.curves[ 0 ].getPoint( 0 );
  19977. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  19978. if ( ! startPoint.equals( endPoint ) ) {
  19979. this.curves.push( new THREE.LineCurve( endPoint, startPoint ) );
  19980. }
  19981. };
  19982. // To get accurate point with reference to
  19983. // entire path distance at time t,
  19984. // following has to be done:
  19985. // 1. Length of each sub path have to be known
  19986. // 2. Locate and identify type of curve
  19987. // 3. Get t for the curve
  19988. // 4. Return curve.getPointAt(t')
  19989. THREE.CurvePath.prototype.getPoint = function( t ) {
  19990. var d = t * this.getLength();
  19991. var curveLengths = this.getCurveLengths();
  19992. var i = 0;
  19993. // To think about boundaries points.
  19994. while ( i < curveLengths.length ) {
  19995. if ( curveLengths[ i ] >= d ) {
  19996. var diff = curveLengths[ i ] - d;
  19997. var curve = this.curves[ i ];
  19998. var u = 1 - diff / curve.getLength();
  19999. return curve.getPointAt( u );
  20000. }
  20001. i ++;
  20002. }
  20003. return null;
  20004. // loop where sum != 0, sum > d , sum+1 <d
  20005. };
  20006. /*
  20007. THREE.CurvePath.prototype.getTangent = function( t ) {
  20008. };
  20009. */
  20010. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  20011. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  20012. // getPoint() depends on getLength
  20013. THREE.CurvePath.prototype.getLength = function() {
  20014. var lens = this.getCurveLengths();
  20015. return lens[ lens.length - 1 ];
  20016. };
  20017. // Compute lengths and cache them
  20018. // We cannot overwrite getLengths() because UtoT mapping uses it.
  20019. THREE.CurvePath.prototype.getCurveLengths = function() {
  20020. // We use cache values if curves and cache array are same length
  20021. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  20022. return this.cacheLengths;
  20023. }
  20024. // Get length of sub-curve
  20025. // Push sums into cached array
  20026. var lengths = [], sums = 0;
  20027. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  20028. sums += this.curves[ i ].getLength();
  20029. lengths.push( sums );
  20030. }
  20031. this.cacheLengths = lengths;
  20032. return lengths;
  20033. };
  20034. /**************************************************************
  20035. * Create Geometries Helpers
  20036. **************************************************************/
  20037. /// Generate geometry from path points (for Line or Points objects)
  20038. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  20039. var pts = this.getPoints( divisions, true );
  20040. return this.createGeometry( pts );
  20041. };
  20042. // Generate geometry from equidistant sampling along the path
  20043. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  20044. var pts = this.getSpacedPoints( divisions, true );
  20045. return this.createGeometry( pts );
  20046. };
  20047. THREE.CurvePath.prototype.createGeometry = function( points ) {
  20048. var geometry = new THREE.Geometry();
  20049. for ( var i = 0, l = points.length; i < l; i ++ ) {
  20050. var point = points[ i ];
  20051. geometry.vertices.push( new THREE.Vector3( point.x, point.y, point.z || 0 ) );
  20052. }
  20053. return geometry;
  20054. };
  20055. // File:src/extras/core/Path.js
  20056. /**
  20057. * @author zz85 / http://www.lab4games.net/zz85/blog
  20058. * Creates free form 2d path using series of points, lines or curves.
  20059. *
  20060. **/
  20061. THREE.Path = function ( points ) {
  20062. THREE.CurvePath.call( this );
  20063. this.actions = [];
  20064. if ( points ) {
  20065. this.fromPoints( points );
  20066. }
  20067. };
  20068. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  20069. THREE.Path.prototype.constructor = THREE.Path;
  20070. // TODO Clean up PATH API
  20071. // Create path using straight lines to connect all points
  20072. // - vectors: array of Vector2
  20073. THREE.Path.prototype.fromPoints = function ( vectors ) {
  20074. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  20075. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  20076. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  20077. }
  20078. };
  20079. // startPath() endPath()?
  20080. THREE.Path.prototype.moveTo = function ( x, y ) {
  20081. this.actions.push( { action: 'moveTo', args: [ x, y ] } );
  20082. };
  20083. THREE.Path.prototype.lineTo = function ( x, y ) {
  20084. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20085. var x0 = lastargs[ lastargs.length - 2 ];
  20086. var y0 = lastargs[ lastargs.length - 1 ];
  20087. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  20088. this.curves.push( curve );
  20089. this.actions.push( { action: 'lineTo', args: [ x, y ] } );
  20090. };
  20091. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  20092. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20093. var x0 = lastargs[ lastargs.length - 2 ];
  20094. var y0 = lastargs[ lastargs.length - 1 ];
  20095. var curve = new THREE.QuadraticBezierCurve(
  20096. new THREE.Vector2( x0, y0 ),
  20097. new THREE.Vector2( aCPx, aCPy ),
  20098. new THREE.Vector2( aX, aY )
  20099. );
  20100. this.curves.push( curve );
  20101. this.actions.push( { action: 'quadraticCurveTo', args: [ aCPx, aCPy, aX, aY ] } );
  20102. };
  20103. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20104. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20105. var x0 = lastargs[ lastargs.length - 2 ];
  20106. var y0 = lastargs[ lastargs.length - 1 ];
  20107. var curve = new THREE.CubicBezierCurve(
  20108. new THREE.Vector2( x0, y0 ),
  20109. new THREE.Vector2( aCP1x, aCP1y ),
  20110. new THREE.Vector2( aCP2x, aCP2y ),
  20111. new THREE.Vector2( aX, aY )
  20112. );
  20113. this.curves.push( curve );
  20114. this.actions.push( { action: 'bezierCurveTo', args: [ aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ] } );
  20115. };
  20116. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  20117. var args = Array.prototype.slice.call( arguments );
  20118. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20119. var x0 = lastargs[ lastargs.length - 2 ];
  20120. var y0 = lastargs[ lastargs.length - 1 ];
  20121. var npts = [ new THREE.Vector2( x0, y0 ) ];
  20122. Array.prototype.push.apply( npts, pts );
  20123. var curve = new THREE.SplineCurve( npts );
  20124. this.curves.push( curve );
  20125. this.actions.push( { action: 'splineThru', args: args } );
  20126. };
  20127. // FUTURE: Change the API or follow canvas API?
  20128. THREE.Path.prototype.arc = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20129. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20130. var x0 = lastargs[ lastargs.length - 2 ];
  20131. var y0 = lastargs[ lastargs.length - 1 ];
  20132. this.absarc( aX + x0, aY + y0, aRadius,
  20133. aStartAngle, aEndAngle, aClockwise );
  20134. };
  20135. THREE.Path.prototype.absarc = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20136. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20137. };
  20138. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20139. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20140. var x0 = lastargs[ lastargs.length - 2 ];
  20141. var y0 = lastargs[ lastargs.length - 1 ];
  20142. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20143. };
  20144. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20145. var args = [
  20146. aX, aY,
  20147. xRadius, yRadius,
  20148. aStartAngle, aEndAngle,
  20149. aClockwise,
  20150. aRotation || 0 // aRotation is optional.
  20151. ];
  20152. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20153. this.curves.push( curve );
  20154. var lastPoint = curve.getPoint( 1 );
  20155. args.push( lastPoint.x );
  20156. args.push( lastPoint.y );
  20157. this.actions.push( { action: 'ellipse', args: args } );
  20158. };
  20159. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  20160. if ( ! divisions ) divisions = 40;
  20161. var points = [];
  20162. for ( var i = 0; i < divisions; i ++ ) {
  20163. points.push( this.getPoint( i / divisions ) );
  20164. //if ( !this.getPoint( i / divisions ) ) throw "DIE";
  20165. }
  20166. // if ( closedPath ) {
  20167. //
  20168. // points.push( points[ 0 ] );
  20169. //
  20170. // }
  20171. return points;
  20172. };
  20173. /* Return an array of vectors based on contour of the path */
  20174. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  20175. divisions = divisions || 12;
  20176. var b2 = THREE.ShapeUtils.b2;
  20177. var b3 = THREE.ShapeUtils.b3;
  20178. var points = [];
  20179. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  20180. laste, tx, ty;
  20181. for ( var i = 0, l = this.actions.length; i < l; i ++ ) {
  20182. var item = this.actions[ i ];
  20183. var action = item.action;
  20184. var args = item.args;
  20185. switch ( action ) {
  20186. case 'moveTo':
  20187. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  20188. break;
  20189. case 'lineTo':
  20190. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  20191. break;
  20192. case 'quadraticCurveTo':
  20193. cpx = args[ 2 ];
  20194. cpy = args[ 3 ];
  20195. cpx1 = args[ 0 ];
  20196. cpy1 = args[ 1 ];
  20197. if ( points.length > 0 ) {
  20198. laste = points[ points.length - 1 ];
  20199. cpx0 = laste.x;
  20200. cpy0 = laste.y;
  20201. } else {
  20202. laste = this.actions[ i - 1 ].args;
  20203. cpx0 = laste[ laste.length - 2 ];
  20204. cpy0 = laste[ laste.length - 1 ];
  20205. }
  20206. for ( var j = 1; j <= divisions; j ++ ) {
  20207. var t = j / divisions;
  20208. tx = b2( t, cpx0, cpx1, cpx );
  20209. ty = b2( t, cpy0, cpy1, cpy );
  20210. points.push( new THREE.Vector2( tx, ty ) );
  20211. }
  20212. break;
  20213. case 'bezierCurveTo':
  20214. cpx = args[ 4 ];
  20215. cpy = args[ 5 ];
  20216. cpx1 = args[ 0 ];
  20217. cpy1 = args[ 1 ];
  20218. cpx2 = args[ 2 ];
  20219. cpy2 = args[ 3 ];
  20220. if ( points.length > 0 ) {
  20221. laste = points[ points.length - 1 ];
  20222. cpx0 = laste.x;
  20223. cpy0 = laste.y;
  20224. } else {
  20225. laste = this.actions[ i - 1 ].args;
  20226. cpx0 = laste[ laste.length - 2 ];
  20227. cpy0 = laste[ laste.length - 1 ];
  20228. }
  20229. for ( var j = 1; j <= divisions; j ++ ) {
  20230. var t = j / divisions;
  20231. tx = b3( t, cpx0, cpx1, cpx2, cpx );
  20232. ty = b3( t, cpy0, cpy1, cpy2, cpy );
  20233. points.push( new THREE.Vector2( tx, ty ) );
  20234. }
  20235. break;
  20236. case 'splineThru':
  20237. laste = this.actions[ i - 1 ].args;
  20238. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  20239. var spts = [ last ];
  20240. var n = divisions * args[ 0 ].length;
  20241. spts = spts.concat( args[ 0 ] );
  20242. var spline = new THREE.SplineCurve( spts );
  20243. for ( var j = 1; j <= n; j ++ ) {
  20244. points.push( spline.getPointAt( j / n ) );
  20245. }
  20246. break;
  20247. case 'arc':
  20248. var aX = args[ 0 ], aY = args[ 1 ],
  20249. aRadius = args[ 2 ],
  20250. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  20251. aClockwise = !! args[ 5 ];
  20252. var deltaAngle = aEndAngle - aStartAngle;
  20253. var angle;
  20254. var tdivisions = divisions * 2;
  20255. for ( var j = 1; j <= tdivisions; j ++ ) {
  20256. var t = j / tdivisions;
  20257. if ( ! aClockwise ) {
  20258. t = 1 - t;
  20259. }
  20260. angle = aStartAngle + t * deltaAngle;
  20261. tx = aX + aRadius * Math.cos( angle );
  20262. ty = aY + aRadius * Math.sin( angle );
  20263. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  20264. points.push( new THREE.Vector2( tx, ty ) );
  20265. }
  20266. //console.log(points);
  20267. break;
  20268. case 'ellipse':
  20269. var aX = args[ 0 ], aY = args[ 1 ],
  20270. xRadius = args[ 2 ],
  20271. yRadius = args[ 3 ],
  20272. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  20273. aClockwise = !! args[ 6 ],
  20274. aRotation = args[ 7 ];
  20275. var deltaAngle = aEndAngle - aStartAngle;
  20276. var angle;
  20277. var tdivisions = divisions * 2;
  20278. var cos, sin;
  20279. if ( aRotation !== 0 ) {
  20280. cos = Math.cos( aRotation );
  20281. sin = Math.sin( aRotation );
  20282. }
  20283. for ( var j = 1; j <= tdivisions; j ++ ) {
  20284. var t = j / tdivisions;
  20285. if ( ! aClockwise ) {
  20286. t = 1 - t;
  20287. }
  20288. angle = aStartAngle + t * deltaAngle;
  20289. tx = aX + xRadius * Math.cos( angle );
  20290. ty = aY + yRadius * Math.sin( angle );
  20291. if ( aRotation !== 0 ) {
  20292. var x = tx, y = ty;
  20293. // Rotate the point about the center of the ellipse.
  20294. tx = ( x - aX ) * cos - ( y - aY ) * sin + aX;
  20295. ty = ( x - aX ) * sin + ( y - aY ) * cos + aY;
  20296. }
  20297. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  20298. points.push( new THREE.Vector2( tx, ty ) );
  20299. }
  20300. //console.log(points);
  20301. break;
  20302. } // end switch
  20303. }
  20304. // Normalize to remove the closing point by default.
  20305. var lastPoint = points[ points.length - 1 ];
  20306. if ( Math.abs( lastPoint.x - points[ 0 ].x ) < Number.EPSILON &&
  20307. Math.abs( lastPoint.y - points[ 0 ].y ) < Number.EPSILON )
  20308. points.splice( points.length - 1, 1 );
  20309. if ( closedPath ) {
  20310. points.push( points[ 0 ] );
  20311. }
  20312. return points;
  20313. };
  20314. //
  20315. // Breaks path into shapes
  20316. //
  20317. // Assumptions (if parameter isCCW==true the opposite holds):
  20318. // - solid shapes are defined clockwise (CW)
  20319. // - holes are defined counterclockwise (CCW)
  20320. //
  20321. // If parameter noHoles==true:
  20322. // - all subPaths are regarded as solid shapes
  20323. // - definition order CW/CCW has no relevance
  20324. //
  20325. THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
  20326. function extractSubpaths( inActions ) {
  20327. var subPaths = [], lastPath = new THREE.Path();
  20328. for ( var i = 0, l = inActions.length; i < l; i ++ ) {
  20329. var item = inActions[ i ];
  20330. var args = item.args;
  20331. var action = item.action;
  20332. if ( action === 'moveTo' ) {
  20333. if ( lastPath.actions.length !== 0 ) {
  20334. subPaths.push( lastPath );
  20335. lastPath = new THREE.Path();
  20336. }
  20337. }
  20338. lastPath[ action ].apply( lastPath, args );
  20339. }
  20340. if ( lastPath.actions.length !== 0 ) {
  20341. subPaths.push( lastPath );
  20342. }
  20343. // console.log(subPaths);
  20344. return subPaths;
  20345. }
  20346. function toShapesNoHoles( inSubpaths ) {
  20347. var shapes = [];
  20348. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  20349. var tmpPath = inSubpaths[ i ];
  20350. var tmpShape = new THREE.Shape();
  20351. tmpShape.actions = tmpPath.actions;
  20352. tmpShape.curves = tmpPath.curves;
  20353. shapes.push( tmpShape );
  20354. }
  20355. //console.log("shape", shapes);
  20356. return shapes;
  20357. }
  20358. function isPointInsidePolygon( inPt, inPolygon ) {
  20359. var polyLen = inPolygon.length;
  20360. // inPt on polygon contour => immediate success or
  20361. // toggling of inside/outside at every single! intersection point of an edge
  20362. // with the horizontal line through inPt, left of inPt
  20363. // not counting lowerY endpoints of edges and whole edges on that line
  20364. var inside = false;
  20365. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  20366. var edgeLowPt = inPolygon[ p ];
  20367. var edgeHighPt = inPolygon[ q ];
  20368. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  20369. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  20370. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  20371. // not parallel
  20372. if ( edgeDy < 0 ) {
  20373. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  20374. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  20375. }
  20376. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  20377. if ( inPt.y === edgeLowPt.y ) {
  20378. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  20379. // continue; // no intersection or edgeLowPt => doesn't count !!!
  20380. } else {
  20381. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  20382. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  20383. if ( perpEdge < 0 ) continue;
  20384. inside = ! inside; // true intersection left of inPt
  20385. }
  20386. } else {
  20387. // parallel or collinear
  20388. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  20389. // edge lies on the same horizontal line as inPt
  20390. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  20391. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  20392. // continue;
  20393. }
  20394. }
  20395. return inside;
  20396. }
  20397. var isClockWise = THREE.ShapeUtils.isClockWise;
  20398. var subPaths = extractSubpaths( this.actions );
  20399. if ( subPaths.length === 0 ) return [];
  20400. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  20401. var solid, tmpPath, tmpShape, shapes = [];
  20402. if ( subPaths.length === 1 ) {
  20403. tmpPath = subPaths[ 0 ];
  20404. tmpShape = new THREE.Shape();
  20405. tmpShape.actions = tmpPath.actions;
  20406. tmpShape.curves = tmpPath.curves;
  20407. shapes.push( tmpShape );
  20408. return shapes;
  20409. }
  20410. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  20411. holesFirst = isCCW ? ! holesFirst : holesFirst;
  20412. // console.log("Holes first", holesFirst);
  20413. var betterShapeHoles = [];
  20414. var newShapes = [];
  20415. var newShapeHoles = [];
  20416. var mainIdx = 0;
  20417. var tmpPoints;
  20418. newShapes[ mainIdx ] = undefined;
  20419. newShapeHoles[ mainIdx ] = [];
  20420. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  20421. tmpPath = subPaths[ i ];
  20422. tmpPoints = tmpPath.getPoints();
  20423. solid = isClockWise( tmpPoints );
  20424. solid = isCCW ? ! solid : solid;
  20425. if ( solid ) {
  20426. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  20427. newShapes[ mainIdx ] = { s: new THREE.Shape(), p: tmpPoints };
  20428. newShapes[ mainIdx ].s.actions = tmpPath.actions;
  20429. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  20430. if ( holesFirst ) mainIdx ++;
  20431. newShapeHoles[ mainIdx ] = [];
  20432. //console.log('cw', i);
  20433. } else {
  20434. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  20435. //console.log('ccw', i);
  20436. }
  20437. }
  20438. // only Holes? -> probably all Shapes with wrong orientation
  20439. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  20440. if ( newShapes.length > 1 ) {
  20441. var ambiguous = false;
  20442. var toChange = [];
  20443. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  20444. betterShapeHoles[ sIdx ] = [];
  20445. }
  20446. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  20447. var sho = newShapeHoles[ sIdx ];
  20448. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  20449. var ho = sho[ hIdx ];
  20450. var hole_unassigned = true;
  20451. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  20452. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  20453. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  20454. if ( hole_unassigned ) {
  20455. hole_unassigned = false;
  20456. betterShapeHoles[ s2Idx ].push( ho );
  20457. } else {
  20458. ambiguous = true;
  20459. }
  20460. }
  20461. }
  20462. if ( hole_unassigned ) {
  20463. betterShapeHoles[ sIdx ].push( ho );
  20464. }
  20465. }
  20466. }
  20467. // console.log("ambiguous: ", ambiguous);
  20468. if ( toChange.length > 0 ) {
  20469. // console.log("to change: ", toChange);
  20470. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  20471. }
  20472. }
  20473. var tmpHoles;
  20474. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  20475. tmpShape = newShapes[ i ].s;
  20476. shapes.push( tmpShape );
  20477. tmpHoles = newShapeHoles[ i ];
  20478. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  20479. tmpShape.holes.push( tmpHoles[ j ].h );
  20480. }
  20481. }
  20482. //console.log("shape", shapes);
  20483. return shapes;
  20484. };
  20485. // File:src/extras/core/Shape.js
  20486. /**
  20487. * @author zz85 / http://www.lab4games.net/zz85/blog
  20488. * Defines a 2d shape plane using paths.
  20489. **/
  20490. // STEP 1 Create a path.
  20491. // STEP 2 Turn path into shape.
  20492. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  20493. // STEP 3a - Extract points from each shape, turn to vertices
  20494. // STEP 3b - Triangulate each shape, add faces.
  20495. THREE.Shape = function () {
  20496. THREE.Path.apply( this, arguments );
  20497. this.holes = [];
  20498. };
  20499. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  20500. THREE.Shape.prototype.constructor = THREE.Shape;
  20501. // Convenience method to return ExtrudeGeometry
  20502. THREE.Shape.prototype.extrude = function ( options ) {
  20503. return new THREE.ExtrudeGeometry( this, options );
  20504. };
  20505. // Convenience method to return ShapeGeometry
  20506. THREE.Shape.prototype.makeGeometry = function ( options ) {
  20507. return new THREE.ShapeGeometry( this, options );
  20508. };
  20509. // Get points of holes
  20510. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  20511. var holesPts = [];
  20512. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  20513. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20514. }
  20515. return holesPts;
  20516. };
  20517. // Get points of shape and holes (keypoints based on segments parameter)
  20518. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  20519. return {
  20520. shape: this.getPoints( divisions ),
  20521. holes: this.getPointsHoles( divisions )
  20522. };
  20523. };
  20524. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  20525. return this.extractAllPoints( divisions );
  20526. };
  20527. THREE.Shape.Utils = THREE.ShapeUtils; // backwards compatibility
  20528. // File:src/extras/curves/LineCurve.js
  20529. /**************************************************************
  20530. * Line
  20531. **************************************************************/
  20532. THREE.LineCurve = function ( v1, v2 ) {
  20533. this.v1 = v1;
  20534. this.v2 = v2;
  20535. };
  20536. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  20537. THREE.LineCurve.prototype.constructor = THREE.LineCurve;
  20538. THREE.LineCurve.prototype.getPoint = function ( t ) {
  20539. var point = this.v2.clone().sub( this.v1 );
  20540. point.multiplyScalar( t ).add( this.v1 );
  20541. return point;
  20542. };
  20543. // Line curve is linear, so we can overwrite default getPointAt
  20544. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  20545. return this.getPoint( u );
  20546. };
  20547. THREE.LineCurve.prototype.getTangent = function( t ) {
  20548. var tangent = this.v2.clone().sub( this.v1 );
  20549. return tangent.normalize();
  20550. };
  20551. // File:src/extras/curves/QuadraticBezierCurve.js
  20552. /**************************************************************
  20553. * Quadratic Bezier curve
  20554. **************************************************************/
  20555. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  20556. this.v0 = v0;
  20557. this.v1 = v1;
  20558. this.v2 = v2;
  20559. };
  20560. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  20561. THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve;
  20562. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  20563. var b2 = THREE.ShapeUtils.b2;
  20564. return new THREE.Vector2(
  20565. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  20566. b2( t, this.v0.y, this.v1.y, this.v2.y )
  20567. );
  20568. };
  20569. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  20570. var tangentQuadraticBezier = THREE.CurveUtils.tangentQuadraticBezier;
  20571. return new THREE.Vector2(
  20572. tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ),
  20573. tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y )
  20574. ).normalize();
  20575. };
  20576. // File:src/extras/curves/CubicBezierCurve.js
  20577. /**************************************************************
  20578. * Cubic Bezier curve
  20579. **************************************************************/
  20580. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  20581. this.v0 = v0;
  20582. this.v1 = v1;
  20583. this.v2 = v2;
  20584. this.v3 = v3;
  20585. };
  20586. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  20587. THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve;
  20588. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  20589. var b3 = THREE.ShapeUtils.b3;
  20590. return new THREE.Vector2(
  20591. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  20592. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  20593. );
  20594. };
  20595. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  20596. var tangentCubicBezier = THREE.CurveUtils.tangentCubicBezier;
  20597. return new THREE.Vector2(
  20598. tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  20599. tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  20600. ).normalize();
  20601. };
  20602. // File:src/extras/curves/SplineCurve.js
  20603. /**************************************************************
  20604. * Spline curve
  20605. **************************************************************/
  20606. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  20607. this.points = ( points == undefined ) ? [] : points;
  20608. };
  20609. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  20610. THREE.SplineCurve.prototype.constructor = THREE.SplineCurve;
  20611. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  20612. var points = this.points;
  20613. var point = ( points.length - 1 ) * t;
  20614. var intPoint = Math.floor( point );
  20615. var weight = point - intPoint;
  20616. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  20617. var point1 = points[ intPoint ];
  20618. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  20619. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  20620. var interpolate = THREE.CurveUtils.interpolate;
  20621. return new THREE.Vector2(
  20622. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  20623. interpolate( point0.y, point1.y, point2.y, point3.y, weight )
  20624. );
  20625. };
  20626. // File:src/extras/curves/EllipseCurve.js
  20627. /**************************************************************
  20628. * Ellipse curve
  20629. **************************************************************/
  20630. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20631. this.aX = aX;
  20632. this.aY = aY;
  20633. this.xRadius = xRadius;
  20634. this.yRadius = yRadius;
  20635. this.aStartAngle = aStartAngle;
  20636. this.aEndAngle = aEndAngle;
  20637. this.aClockwise = aClockwise;
  20638. this.aRotation = aRotation || 0;
  20639. };
  20640. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  20641. THREE.EllipseCurve.prototype.constructor = THREE.EllipseCurve;
  20642. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  20643. var deltaAngle = this.aEndAngle - this.aStartAngle;
  20644. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  20645. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  20646. var angle;
  20647. if ( this.aClockwise === true ) {
  20648. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  20649. } else {
  20650. angle = this.aStartAngle + t * deltaAngle;
  20651. }
  20652. var x = this.aX + this.xRadius * Math.cos( angle );
  20653. var y = this.aY + this.yRadius * Math.sin( angle );
  20654. if ( this.aRotation !== 0 ) {
  20655. var cos = Math.cos( this.aRotation );
  20656. var sin = Math.sin( this.aRotation );
  20657. var tx = x, ty = y;
  20658. // Rotate the point about the center of the ellipse.
  20659. x = ( tx - this.aX ) * cos - ( ty - this.aY ) * sin + this.aX;
  20660. y = ( tx - this.aX ) * sin + ( ty - this.aY ) * cos + this.aY;
  20661. }
  20662. return new THREE.Vector2( x, y );
  20663. };
  20664. // File:src/extras/curves/ArcCurve.js
  20665. /**************************************************************
  20666. * Arc curve
  20667. **************************************************************/
  20668. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20669. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20670. };
  20671. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  20672. THREE.ArcCurve.prototype.constructor = THREE.ArcCurve;
  20673. // File:src/extras/curves/LineCurve3.js
  20674. /**************************************************************
  20675. * Line3D
  20676. **************************************************************/
  20677. THREE.LineCurve3 = THREE.Curve.create(
  20678. function ( v1, v2 ) {
  20679. this.v1 = v1;
  20680. this.v2 = v2;
  20681. },
  20682. function ( t ) {
  20683. var vector = new THREE.Vector3();
  20684. vector.subVectors( this.v2, this.v1 ); // diff
  20685. vector.multiplyScalar( t );
  20686. vector.add( this.v1 );
  20687. return vector;
  20688. }
  20689. );
  20690. // File:src/extras/curves/QuadraticBezierCurve3.js
  20691. /**************************************************************
  20692. * Quadratic Bezier 3D curve
  20693. **************************************************************/
  20694. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  20695. function ( v0, v1, v2 ) {
  20696. this.v0 = v0;
  20697. this.v1 = v1;
  20698. this.v2 = v2;
  20699. },
  20700. function ( t ) {
  20701. var b2 = THREE.ShapeUtils.b2;
  20702. return new THREE.Vector3(
  20703. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  20704. b2( t, this.v0.y, this.v1.y, this.v2.y ),
  20705. b2( t, this.v0.z, this.v1.z, this.v2.z )
  20706. );
  20707. }
  20708. );
  20709. // File:src/extras/curves/CubicBezierCurve3.js
  20710. /**************************************************************
  20711. * Cubic Bezier 3D curve
  20712. **************************************************************/
  20713. THREE.CubicBezierCurve3 = THREE.Curve.create(
  20714. function ( v0, v1, v2, v3 ) {
  20715. this.v0 = v0;
  20716. this.v1 = v1;
  20717. this.v2 = v2;
  20718. this.v3 = v3;
  20719. },
  20720. function ( t ) {
  20721. var b3 = THREE.ShapeUtils.b3;
  20722. return new THREE.Vector3(
  20723. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  20724. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ),
  20725. b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z )
  20726. );
  20727. }
  20728. );
  20729. // File:src/extras/curves/SplineCurve3.js
  20730. /**************************************************************
  20731. * Spline 3D curve
  20732. **************************************************************/
  20733. THREE.SplineCurve3 = THREE.Curve.create(
  20734. function ( points /* array of Vector3 */ ) {
  20735. console.warn( 'THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3' );
  20736. this.points = ( points == undefined ) ? [] : points;
  20737. },
  20738. function ( t ) {
  20739. var points = this.points;
  20740. var point = ( points.length - 1 ) * t;
  20741. var intPoint = Math.floor( point );
  20742. var weight = point - intPoint;
  20743. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ];
  20744. var point1 = points[ intPoint ];
  20745. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  20746. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  20747. var interpolate = THREE.CurveUtils.interpolate;
  20748. return new THREE.Vector3(
  20749. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  20750. interpolate( point0.y, point1.y, point2.y, point3.y, weight ),
  20751. interpolate( point0.z, point1.z, point2.z, point3.z, weight )
  20752. );
  20753. }
  20754. );
  20755. // File:src/extras/curves/CatmullRomCurve3.js
  20756. /**
  20757. * @author zz85 https://github.com/zz85
  20758. *
  20759. * Centripetal CatmullRom Curve - which is useful for avoiding
  20760. * cusps and self-intersections in non-uniform catmull rom curves.
  20761. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  20762. *
  20763. * curve.type accepts centripetal(default), chordal and catmullrom
  20764. * curve.tension is used for catmullrom which defaults to 0.5
  20765. */
  20766. THREE.CatmullRomCurve3 = ( function() {
  20767. var
  20768. tmp = new THREE.Vector3(),
  20769. px = new CubicPoly(),
  20770. py = new CubicPoly(),
  20771. pz = new CubicPoly();
  20772. /*
  20773. Based on an optimized c++ solution in
  20774. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  20775. - http://ideone.com/NoEbVM
  20776. This CubicPoly class could be used for reusing some variables and calculations,
  20777. but for three.js curve use, it could be possible inlined and flatten into a single function call
  20778. which can be placed in CurveUtils.
  20779. */
  20780. function CubicPoly() {
  20781. }
  20782. /*
  20783. * Compute coefficients for a cubic polynomial
  20784. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  20785. * such that
  20786. * p(0) = x0, p(1) = x1
  20787. * and
  20788. * p'(0) = t0, p'(1) = t1.
  20789. */
  20790. CubicPoly.prototype.init = function( x0, x1, t0, t1 ) {
  20791. this.c0 = x0;
  20792. this.c1 = t0;
  20793. this.c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  20794. this.c3 = 2 * x0 - 2 * x1 + t0 + t1;
  20795. };
  20796. CubicPoly.prototype.initNonuniformCatmullRom = function( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  20797. // compute tangents when parameterized in [t1,t2]
  20798. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  20799. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  20800. // rescale tangents for parametrization in [0,1]
  20801. t1 *= dt1;
  20802. t2 *= dt1;
  20803. // initCubicPoly
  20804. this.init( x1, x2, t1, t2 );
  20805. };
  20806. // standard Catmull-Rom spline: interpolate between x1 and x2 with previous/following points x1/x4
  20807. CubicPoly.prototype.initCatmullRom = function( x0, x1, x2, x3, tension ) {
  20808. this.init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  20809. };
  20810. CubicPoly.prototype.calc = function( t ) {
  20811. var t2 = t * t;
  20812. var t3 = t2 * t;
  20813. return this.c0 + this.c1 * t + this.c2 * t2 + this.c3 * t3;
  20814. };
  20815. // Subclass Three.js curve
  20816. return THREE.Curve.create(
  20817. function ( p /* array of Vector3 */ ) {
  20818. this.points = p || [];
  20819. },
  20820. function ( t ) {
  20821. var points = this.points,
  20822. point, intPoint, weight, l;
  20823. l = points.length;
  20824. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  20825. point = ( l - 1 ) * t;
  20826. intPoint = Math.floor( point );
  20827. weight = point - intPoint;
  20828. if ( weight === 0 && intPoint === l - 1 ) {
  20829. intPoint = l - 2;
  20830. weight = 1;
  20831. }
  20832. var p0, p1, p2, p3;
  20833. if ( intPoint === 0 ) {
  20834. // extrapolate first point
  20835. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  20836. p0 = tmp;
  20837. } else {
  20838. p0 = points[ intPoint - 1 ];
  20839. }
  20840. p1 = points[ intPoint ];
  20841. p2 = points[ intPoint + 1 ];
  20842. if ( intPoint + 2 < l ) {
  20843. p3 = points[ intPoint + 2 ]
  20844. } else {
  20845. // extrapolate last point
  20846. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 2 ] );
  20847. p3 = tmp;
  20848. }
  20849. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  20850. // init Centripetal / Chordal Catmull-Rom
  20851. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  20852. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  20853. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  20854. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  20855. // safety check for repeated points
  20856. if ( dt1 < 1e-4 ) dt1 = 1.0;
  20857. if ( dt0 < 1e-4 ) dt0 = dt1;
  20858. if ( dt2 < 1e-4 ) dt2 = dt1;
  20859. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  20860. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  20861. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  20862. } else if ( this.type === 'catmullrom' ) {
  20863. var tension = this.tension !== undefined ? this.tension : 0.5;
  20864. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  20865. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  20866. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  20867. }
  20868. var v = new THREE.Vector3(
  20869. px.calc( weight ),
  20870. py.calc( weight ),
  20871. pz.calc( weight )
  20872. );
  20873. return v;
  20874. }
  20875. );
  20876. } )();
  20877. // File:src/extras/curves/ClosedSplineCurve3.js
  20878. /**************************************************************
  20879. * Closed Spline 3D curve
  20880. **************************************************************/
  20881. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  20882. function ( points /* array of Vector3 */ ) {
  20883. this.points = ( points == undefined ) ? [] : points;
  20884. },
  20885. function ( t ) {
  20886. var points = this.points;
  20887. var point = ( points.length - 0 ) * t; // This needs to be from 0-length +1
  20888. var intPoint = Math.floor( point );
  20889. var weight = point - intPoint;
  20890. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  20891. var point0 = points[ ( intPoint - 1 ) % points.length ];
  20892. var point1 = points[ ( intPoint ) % points.length ];
  20893. var point2 = points[ ( intPoint + 1 ) % points.length ];
  20894. var point3 = points[ ( intPoint + 2 ) % points.length ];
  20895. var interpolate = THREE.CurveUtils.interpolate;
  20896. return new THREE.Vector3(
  20897. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  20898. interpolate( point0.y, point1.y, point2.y, point3.y, weight ),
  20899. interpolate( point0.z, point1.z, point2.z, point3.z, weight )
  20900. );
  20901. }
  20902. );
  20903. // File:src/extras/geometries/BoxGeometry.js
  20904. /**
  20905. * @author mrdoob / http://mrdoob.com/
  20906. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  20907. */
  20908. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  20909. THREE.Geometry.call( this );
  20910. this.type = 'BoxGeometry';
  20911. this.parameters = {
  20912. width: width,
  20913. height: height,
  20914. depth: depth,
  20915. widthSegments: widthSegments,
  20916. heightSegments: heightSegments,
  20917. depthSegments: depthSegments
  20918. };
  20919. this.widthSegments = widthSegments || 1;
  20920. this.heightSegments = heightSegments || 1;
  20921. this.depthSegments = depthSegments || 1;
  20922. var scope = this;
  20923. var width_half = width / 2;
  20924. var height_half = height / 2;
  20925. var depth_half = depth / 2;
  20926. buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, 0 ); // px
  20927. buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, 1 ); // nx
  20928. buildPlane( 'x', 'z', 1, 1, width, depth, height_half, 2 ); // py
  20929. buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, 3 ); // ny
  20930. buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, 4 ); // pz
  20931. buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, 5 ); // nz
  20932. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  20933. var w, ix, iy,
  20934. gridX = scope.widthSegments,
  20935. gridY = scope.heightSegments,
  20936. width_half = width / 2,
  20937. height_half = height / 2,
  20938. offset = scope.vertices.length;
  20939. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  20940. w = 'z';
  20941. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  20942. w = 'y';
  20943. gridY = scope.depthSegments;
  20944. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  20945. w = 'x';
  20946. gridX = scope.depthSegments;
  20947. }
  20948. var gridX1 = gridX + 1,
  20949. gridY1 = gridY + 1,
  20950. segment_width = width / gridX,
  20951. segment_height = height / gridY,
  20952. normal = new THREE.Vector3();
  20953. normal[ w ] = depth > 0 ? 1 : - 1;
  20954. for ( iy = 0; iy < gridY1; iy ++ ) {
  20955. for ( ix = 0; ix < gridX1; ix ++ ) {
  20956. var vector = new THREE.Vector3();
  20957. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  20958. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  20959. vector[ w ] = depth;
  20960. scope.vertices.push( vector );
  20961. }
  20962. }
  20963. for ( iy = 0; iy < gridY; iy ++ ) {
  20964. for ( ix = 0; ix < gridX; ix ++ ) {
  20965. var a = ix + gridX1 * iy;
  20966. var b = ix + gridX1 * ( iy + 1 );
  20967. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  20968. var d = ( ix + 1 ) + gridX1 * iy;
  20969. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  20970. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  20971. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  20972. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  20973. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  20974. face.normal.copy( normal );
  20975. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  20976. face.materialIndex = materialIndex;
  20977. scope.faces.push( face );
  20978. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  20979. face = new THREE.Face3( b + offset, c + offset, d + offset );
  20980. face.normal.copy( normal );
  20981. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  20982. face.materialIndex = materialIndex;
  20983. scope.faces.push( face );
  20984. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  20985. }
  20986. }
  20987. }
  20988. this.mergeVertices();
  20989. };
  20990. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20991. THREE.BoxGeometry.prototype.constructor = THREE.BoxGeometry;
  20992. THREE.CubeGeometry = THREE.BoxGeometry; // backwards compatibility
  20993. // File:src/extras/geometries/CircleGeometry.js
  20994. /**
  20995. * @author hughes
  20996. */
  20997. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  20998. THREE.Geometry.call( this );
  20999. this.type = 'CircleGeometry';
  21000. this.parameters = {
  21001. radius: radius,
  21002. segments: segments,
  21003. thetaStart: thetaStart,
  21004. thetaLength: thetaLength
  21005. };
  21006. this.fromBufferGeometry( new THREE.CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  21007. };
  21008. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21009. THREE.CircleGeometry.prototype.constructor = THREE.CircleGeometry;
  21010. // File:src/extras/geometries/CircleBufferGeometry.js
  21011. /**
  21012. * @author benaadams / https://twitter.com/ben_a_adams
  21013. */
  21014. THREE.CircleBufferGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  21015. THREE.BufferGeometry.call( this );
  21016. this.type = 'CircleBufferGeometry';
  21017. this.parameters = {
  21018. radius: radius,
  21019. segments: segments,
  21020. thetaStart: thetaStart,
  21021. thetaLength: thetaLength
  21022. };
  21023. radius = radius || 50;
  21024. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  21025. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21026. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  21027. var vertices = segments + 2;
  21028. var positions = new Float32Array( vertices * 3 );
  21029. var normals = new Float32Array( vertices * 3 );
  21030. var uvs = new Float32Array( vertices * 2 );
  21031. // center data is already zero, but need to set a few extras
  21032. normals[ 2 ] = 1.0;
  21033. uvs[ 0 ] = 0.5;
  21034. uvs[ 1 ] = 0.5;
  21035. for ( var s = 0, i = 3, ii = 2 ; s <= segments; s ++, i += 3, ii += 2 ) {
  21036. var segment = thetaStart + s / segments * thetaLength;
  21037. positions[ i ] = radius * Math.cos( segment );
  21038. positions[ i + 1 ] = radius * Math.sin( segment );
  21039. normals[ i + 2 ] = 1; // normal z
  21040. uvs[ ii ] = ( positions[ i ] / radius + 1 ) / 2;
  21041. uvs[ ii + 1 ] = ( positions[ i + 1 ] / radius + 1 ) / 2;
  21042. }
  21043. var indices = [];
  21044. for ( var i = 1; i <= segments; i ++ ) {
  21045. indices.push( i, i + 1, 0 );
  21046. }
  21047. this.setIndex( new THREE.BufferAttribute( new Uint16Array( indices ), 1 ) );
  21048. this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  21049. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  21050. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  21051. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  21052. };
  21053. THREE.CircleBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  21054. THREE.CircleBufferGeometry.prototype.constructor = THREE.CircleBufferGeometry;
  21055. // File:src/extras/geometries/CylinderGeometry.js
  21056. /**
  21057. * @author mrdoob / http://mrdoob.com/
  21058. */
  21059. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21060. THREE.Geometry.call( this );
  21061. this.type = 'CylinderGeometry';
  21062. this.parameters = {
  21063. radiusTop: radiusTop,
  21064. radiusBottom: radiusBottom,
  21065. height: height,
  21066. radialSegments: radialSegments,
  21067. heightSegments: heightSegments,
  21068. openEnded: openEnded,
  21069. thetaStart: thetaStart,
  21070. thetaLength: thetaLength
  21071. };
  21072. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  21073. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  21074. height = height !== undefined ? height : 100;
  21075. radialSegments = radialSegments || 8;
  21076. heightSegments = heightSegments || 1;
  21077. openEnded = openEnded !== undefined ? openEnded : false;
  21078. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21079. thetaLength = thetaLength !== undefined ? thetaLength : 2 * Math.PI;
  21080. var heightHalf = height / 2;
  21081. var x, y, vertices = [], uvs = [];
  21082. for ( y = 0; y <= heightSegments; y ++ ) {
  21083. var verticesRow = [];
  21084. var uvsRow = [];
  21085. var v = y / heightSegments;
  21086. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  21087. for ( x = 0; x <= radialSegments; x ++ ) {
  21088. var u = x / radialSegments;
  21089. var vertex = new THREE.Vector3();
  21090. vertex.x = radius * Math.sin( u * thetaLength + thetaStart );
  21091. vertex.y = - v * height + heightHalf;
  21092. vertex.z = radius * Math.cos( u * thetaLength + thetaStart );
  21093. this.vertices.push( vertex );
  21094. verticesRow.push( this.vertices.length - 1 );
  21095. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  21096. }
  21097. vertices.push( verticesRow );
  21098. uvs.push( uvsRow );
  21099. }
  21100. var tanTheta = ( radiusBottom - radiusTop ) / height;
  21101. var na, nb;
  21102. for ( x = 0; x < radialSegments; x ++ ) {
  21103. if ( radiusTop !== 0 ) {
  21104. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  21105. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  21106. } else {
  21107. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  21108. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  21109. }
  21110. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  21111. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  21112. for ( y = 0; y < heightSegments; y ++ ) {
  21113. var v1 = vertices[ y ][ x ];
  21114. var v2 = vertices[ y + 1 ][ x ];
  21115. var v3 = vertices[ y + 1 ][ x + 1 ];
  21116. var v4 = vertices[ y ][ x + 1 ];
  21117. var n1 = na.clone();
  21118. var n2 = na.clone();
  21119. var n3 = nb.clone();
  21120. var n4 = nb.clone();
  21121. var uv1 = uvs[ y ][ x ].clone();
  21122. var uv2 = uvs[ y + 1 ][ x ].clone();
  21123. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  21124. var uv4 = uvs[ y ][ x + 1 ].clone();
  21125. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  21126. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  21127. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  21128. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  21129. }
  21130. }
  21131. // top cap
  21132. if ( openEnded === false && radiusTop > 0 ) {
  21133. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  21134. for ( x = 0; x < radialSegments; x ++ ) {
  21135. var v1 = vertices[ 0 ][ x ];
  21136. var v2 = vertices[ 0 ][ x + 1 ];
  21137. var v3 = this.vertices.length - 1;
  21138. var n1 = new THREE.Vector3( 0, 1, 0 );
  21139. var n2 = new THREE.Vector3( 0, 1, 0 );
  21140. var n3 = new THREE.Vector3( 0, 1, 0 );
  21141. var uv1 = uvs[ 0 ][ x ].clone();
  21142. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  21143. var uv3 = new THREE.Vector2( uv2.x, 0 );
  21144. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ], undefined, 1 ) );
  21145. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  21146. }
  21147. }
  21148. // bottom cap
  21149. if ( openEnded === false && radiusBottom > 0 ) {
  21150. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  21151. for ( x = 0; x < radialSegments; x ++ ) {
  21152. var v1 = vertices[ heightSegments ][ x + 1 ];
  21153. var v2 = vertices[ heightSegments ][ x ];
  21154. var v3 = this.vertices.length - 1;
  21155. var n1 = new THREE.Vector3( 0, - 1, 0 );
  21156. var n2 = new THREE.Vector3( 0, - 1, 0 );
  21157. var n3 = new THREE.Vector3( 0, - 1, 0 );
  21158. var uv1 = uvs[ heightSegments ][ x + 1 ].clone();
  21159. var uv2 = uvs[ heightSegments ][ x ].clone();
  21160. var uv3 = new THREE.Vector2( uv2.x, 1 );
  21161. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ], undefined, 2 ) );
  21162. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  21163. }
  21164. }
  21165. this.computeFaceNormals();
  21166. };
  21167. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21168. THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry;
  21169. // File:src/extras/geometries/EdgesGeometry.js
  21170. /**
  21171. * @author WestLangley / http://github.com/WestLangley
  21172. */
  21173. THREE.EdgesGeometry = function ( geometry, thresholdAngle ) {
  21174. THREE.BufferGeometry.call( this );
  21175. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  21176. var thresholdDot = Math.cos( THREE.Math.degToRad( thresholdAngle ) );
  21177. var edge = [ 0, 0 ], hash = {};
  21178. function sortFunction( a, b ) {
  21179. return a - b;
  21180. }
  21181. var keys = [ 'a', 'b', 'c' ];
  21182. var geometry2;
  21183. if ( geometry instanceof THREE.BufferGeometry ) {
  21184. geometry2 = new THREE.Geometry();
  21185. geometry2.fromBufferGeometry( geometry );
  21186. } else {
  21187. geometry2 = geometry.clone();
  21188. }
  21189. geometry2.mergeVertices();
  21190. geometry2.computeFaceNormals();
  21191. var vertices = geometry2.vertices;
  21192. var faces = geometry2.faces;
  21193. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21194. var face = faces[ i ];
  21195. for ( var j = 0; j < 3; j ++ ) {
  21196. edge[ 0 ] = face[ keys[ j ] ];
  21197. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  21198. edge.sort( sortFunction );
  21199. var key = edge.toString();
  21200. if ( hash[ key ] === undefined ) {
  21201. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  21202. } else {
  21203. hash[ key ].face2 = i;
  21204. }
  21205. }
  21206. }
  21207. var coords = [];
  21208. for ( var key in hash ) {
  21209. var h = hash[ key ];
  21210. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) {
  21211. var vertex = vertices[ h.vert1 ];
  21212. coords.push( vertex.x );
  21213. coords.push( vertex.y );
  21214. coords.push( vertex.z );
  21215. vertex = vertices[ h.vert2 ];
  21216. coords.push( vertex.x );
  21217. coords.push( vertex.y );
  21218. coords.push( vertex.z );
  21219. }
  21220. }
  21221. this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( coords ), 3 ) );
  21222. };
  21223. THREE.EdgesGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  21224. THREE.EdgesGeometry.prototype.constructor = THREE.EdgesGeometry;
  21225. // File:src/extras/geometries/ExtrudeGeometry.js
  21226. /**
  21227. * @author zz85 / http://www.lab4games.net/zz85/blog
  21228. *
  21229. * Creates extruded geometry from a path shape.
  21230. *
  21231. * parameters = {
  21232. *
  21233. * curveSegments: <int>, // number of points on the curves
  21234. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  21235. * amount: <int>, // Depth to extrude the shape
  21236. *
  21237. * bevelEnabled: <bool>, // turn on bevel
  21238. * bevelThickness: <float>, // how deep into the original shape bevel goes
  21239. * bevelSize: <float>, // how far from shape outline is bevel
  21240. * bevelSegments: <int>, // number of bevel layers
  21241. *
  21242. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  21243. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  21244. *
  21245. * uvGenerator: <Object> // object that provides UV generator functions
  21246. *
  21247. * }
  21248. **/
  21249. THREE.ExtrudeGeometry = function ( shapes, options ) {
  21250. if ( typeof( shapes ) === "undefined" ) {
  21251. shapes = [];
  21252. return;
  21253. }
  21254. THREE.Geometry.call( this );
  21255. this.type = 'ExtrudeGeometry';
  21256. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  21257. this.addShapeList( shapes, options );
  21258. this.computeFaceNormals();
  21259. // can't really use automatic vertex normals
  21260. // as then front and back sides get smoothed too
  21261. // should do separate smoothing just for sides
  21262. //this.computeVertexNormals();
  21263. //console.log( "took", ( Date.now() - startTime ) );
  21264. };
  21265. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21266. THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry;
  21267. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  21268. var sl = shapes.length;
  21269. for ( var s = 0; s < sl; s ++ ) {
  21270. var shape = shapes[ s ];
  21271. this.addShape( shape, options );
  21272. }
  21273. };
  21274. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  21275. var amount = options.amount !== undefined ? options.amount : 100;
  21276. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  21277. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  21278. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21279. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  21280. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21281. var steps = options.steps !== undefined ? options.steps : 1;
  21282. var extrudePath = options.extrudePath;
  21283. var extrudePts, extrudeByPath = false;
  21284. // Use default WorldUVGenerator if no UV generators are specified.
  21285. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  21286. var splineTube, binormal, normal, position2;
  21287. if ( extrudePath ) {
  21288. extrudePts = extrudePath.getSpacedPoints( steps );
  21289. extrudeByPath = true;
  21290. bevelEnabled = false; // bevels not supported for path extrusion
  21291. // SETUP TNB variables
  21292. // Reuse TNB from TubeGeomtry for now.
  21293. // TODO1 - have a .isClosed in spline?
  21294. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames( extrudePath, steps, false );
  21295. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21296. binormal = new THREE.Vector3();
  21297. normal = new THREE.Vector3();
  21298. position2 = new THREE.Vector3();
  21299. }
  21300. // Safeguards if bevels are not enabled
  21301. if ( ! bevelEnabled ) {
  21302. bevelSegments = 0;
  21303. bevelThickness = 0;
  21304. bevelSize = 0;
  21305. }
  21306. // Variables initialization
  21307. var ahole, h, hl; // looping of holes
  21308. var scope = this;
  21309. var shapesOffset = this.vertices.length;
  21310. var shapePoints = shape.extractPoints( curveSegments );
  21311. var vertices = shapePoints.shape;
  21312. var holes = shapePoints.holes;
  21313. var reverse = ! THREE.ShapeUtils.isClockWise( vertices );
  21314. if ( reverse ) {
  21315. vertices = vertices.reverse();
  21316. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  21317. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21318. ahole = holes[ h ];
  21319. if ( THREE.ShapeUtils.isClockWise( ahole ) ) {
  21320. holes[ h ] = ahole.reverse();
  21321. }
  21322. }
  21323. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  21324. }
  21325. var faces = THREE.ShapeUtils.triangulateShape( vertices, holes );
  21326. /* Vertices */
  21327. var contour = vertices; // vertices has all points but contour has only points of circumference
  21328. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21329. ahole = holes[ h ];
  21330. vertices = vertices.concat( ahole );
  21331. }
  21332. function scalePt2 ( pt, vec, size ) {
  21333. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  21334. return vec.clone().multiplyScalar( size ).add( pt );
  21335. }
  21336. var b, bs, t, z,
  21337. vert, vlen = vertices.length,
  21338. face, flen = faces.length;
  21339. // Find directions for point movement
  21340. function getBevelVec( inPt, inPrev, inNext ) {
  21341. // computes for inPt the corresponding point inPt' on a new contour
  21342. // shifted by 1 unit (length of normalized vector) to the left
  21343. // if we walk along contour clockwise, this new contour is outside the old one
  21344. //
  21345. // inPt' is the intersection of the two lines parallel to the two
  21346. // adjacent edges of inPt at a distance of 1 unit on the left side.
  21347. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  21348. // good reading for geometry algorithms (here: line-line intersection)
  21349. // http://geomalgorithms.com/a05-_intersect-1.html
  21350. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  21351. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  21352. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  21353. // check for collinear edges
  21354. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21355. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  21356. // not collinear
  21357. // length of vectors for normalizing
  21358. var v_prev_len = Math.sqrt( v_prev_lensq );
  21359. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  21360. // shift adjacent points by unit vectors to the left
  21361. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  21362. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  21363. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  21364. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  21365. // scaling factor for v_prev to intersection point
  21366. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  21367. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  21368. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21369. // vector from inPt to intersection point
  21370. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  21371. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  21372. // Don't normalize!, otherwise sharp corners become ugly
  21373. // but prevent crazy spikes
  21374. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  21375. if ( v_trans_lensq <= 2 ) {
  21376. return new THREE.Vector2( v_trans_x, v_trans_y );
  21377. } else {
  21378. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  21379. }
  21380. } else {
  21381. // handle special case of collinear edges
  21382. var direction_eq = false; // assumes: opposite
  21383. if ( v_prev_x > Number.EPSILON ) {
  21384. if ( v_next_x > Number.EPSILON ) {
  21385. direction_eq = true;
  21386. }
  21387. } else {
  21388. if ( v_prev_x < - Number.EPSILON ) {
  21389. if ( v_next_x < - Number.EPSILON ) {
  21390. direction_eq = true;
  21391. }
  21392. } else {
  21393. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  21394. direction_eq = true;
  21395. }
  21396. }
  21397. }
  21398. if ( direction_eq ) {
  21399. // console.log("Warning: lines are a straight sequence");
  21400. v_trans_x = - v_prev_y;
  21401. v_trans_y = v_prev_x;
  21402. shrink_by = Math.sqrt( v_prev_lensq );
  21403. } else {
  21404. // console.log("Warning: lines are a straight spike");
  21405. v_trans_x = v_prev_x;
  21406. v_trans_y = v_prev_y;
  21407. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  21408. }
  21409. }
  21410. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  21411. }
  21412. var contourMovements = [];
  21413. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21414. if ( j === il ) j = 0;
  21415. if ( k === il ) k = 0;
  21416. // (j)---(i)---(k)
  21417. // console.log('i,j,k', i, j , k)
  21418. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21419. }
  21420. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  21421. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21422. ahole = holes[ h ];
  21423. oneHoleMovements = [];
  21424. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21425. if ( j === il ) j = 0;
  21426. if ( k === il ) k = 0;
  21427. // (j)---(i)---(k)
  21428. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21429. }
  21430. holesMovements.push( oneHoleMovements );
  21431. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21432. }
  21433. // Loop bevelSegments, 1 for the front, 1 for the back
  21434. for ( b = 0; b < bevelSegments; b ++ ) {
  21435. //for ( b = bevelSegments; b > 0; b -- ) {
  21436. t = b / bevelSegments;
  21437. z = bevelThickness * ( 1 - t );
  21438. //z = bevelThickness * t;
  21439. bs = bevelSize * ( Math.sin ( t * Math.PI / 2 ) ); // curved
  21440. //bs = bevelSize * t; // linear
  21441. // contract shape
  21442. for ( i = 0, il = contour.length; i < il; i ++ ) {
  21443. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21444. v( vert.x, vert.y, - z );
  21445. }
  21446. // expand holes
  21447. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21448. ahole = holes[ h ];
  21449. oneHoleMovements = holesMovements[ h ];
  21450. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  21451. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21452. v( vert.x, vert.y, - z );
  21453. }
  21454. }
  21455. }
  21456. bs = bevelSize;
  21457. // Back facing vertices
  21458. for ( i = 0; i < vlen; i ++ ) {
  21459. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21460. if ( ! extrudeByPath ) {
  21461. v( vert.x, vert.y, 0 );
  21462. } else {
  21463. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21464. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  21465. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  21466. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  21467. v( position2.x, position2.y, position2.z );
  21468. }
  21469. }
  21470. // Add stepped vertices...
  21471. // Including front facing vertices
  21472. var s;
  21473. for ( s = 1; s <= steps; s ++ ) {
  21474. for ( i = 0; i < vlen; i ++ ) {
  21475. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21476. if ( ! extrudeByPath ) {
  21477. v( vert.x, vert.y, amount / steps * s );
  21478. } else {
  21479. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21480. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  21481. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  21482. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  21483. v( position2.x, position2.y, position2.z );
  21484. }
  21485. }
  21486. }
  21487. // Add bevel segments planes
  21488. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21489. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  21490. t = b / bevelSegments;
  21491. z = bevelThickness * ( 1 - t );
  21492. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  21493. bs = bevelSize * Math.sin ( t * Math.PI / 2 );
  21494. // contract shape
  21495. for ( i = 0, il = contour.length; i < il; i ++ ) {
  21496. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21497. v( vert.x, vert.y, amount + z );
  21498. }
  21499. // expand holes
  21500. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21501. ahole = holes[ h ];
  21502. oneHoleMovements = holesMovements[ h ];
  21503. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  21504. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21505. if ( ! extrudeByPath ) {
  21506. v( vert.x, vert.y, amount + z );
  21507. } else {
  21508. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  21509. }
  21510. }
  21511. }
  21512. }
  21513. /* Faces */
  21514. // Top and bottom faces
  21515. buildLidFaces();
  21516. // Sides faces
  21517. buildSideFaces();
  21518. ///// Internal functions
  21519. function buildLidFaces() {
  21520. if ( bevelEnabled ) {
  21521. var layer = 0; // steps + 1
  21522. var offset = vlen * layer;
  21523. // Bottom faces
  21524. for ( i = 0; i < flen; i ++ ) {
  21525. face = faces[ i ];
  21526. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  21527. }
  21528. layer = steps + bevelSegments * 2;
  21529. offset = vlen * layer;
  21530. // Top faces
  21531. for ( i = 0; i < flen; i ++ ) {
  21532. face = faces[ i ];
  21533. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  21534. }
  21535. } else {
  21536. // Bottom faces
  21537. for ( i = 0; i < flen; i ++ ) {
  21538. face = faces[ i ];
  21539. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  21540. }
  21541. // Top faces
  21542. for ( i = 0; i < flen; i ++ ) {
  21543. face = faces[ i ];
  21544. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  21545. }
  21546. }
  21547. }
  21548. // Create faces for the z-sides of the shape
  21549. function buildSideFaces() {
  21550. var layeroffset = 0;
  21551. sidewalls( contour, layeroffset );
  21552. layeroffset += contour.length;
  21553. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21554. ahole = holes[ h ];
  21555. sidewalls( ahole, layeroffset );
  21556. //, true
  21557. layeroffset += ahole.length;
  21558. }
  21559. }
  21560. function sidewalls( contour, layeroffset ) {
  21561. var j, k;
  21562. i = contour.length;
  21563. while ( -- i >= 0 ) {
  21564. j = i;
  21565. k = i - 1;
  21566. if ( k < 0 ) k = contour.length - 1;
  21567. //console.log('b', i,j, i-1, k,vertices.length);
  21568. var s = 0, sl = steps + bevelSegments * 2;
  21569. for ( s = 0; s < sl; s ++ ) {
  21570. var slen1 = vlen * s;
  21571. var slen2 = vlen * ( s + 1 );
  21572. var a = layeroffset + j + slen1,
  21573. b = layeroffset + k + slen1,
  21574. c = layeroffset + k + slen2,
  21575. d = layeroffset + j + slen2;
  21576. f4( a, b, c, d, contour, s, sl, j, k );
  21577. }
  21578. }
  21579. }
  21580. function v( x, y, z ) {
  21581. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  21582. }
  21583. function f3( a, b, c ) {
  21584. a += shapesOffset;
  21585. b += shapesOffset;
  21586. c += shapesOffset;
  21587. scope.faces.push( new THREE.Face3( a, b, c, null, null, 0 ) );
  21588. var uvs = uvgen.generateTopUV( scope, a, b, c );
  21589. scope.faceVertexUvs[ 0 ].push( uvs );
  21590. }
  21591. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  21592. a += shapesOffset;
  21593. b += shapesOffset;
  21594. c += shapesOffset;
  21595. d += shapesOffset;
  21596. scope.faces.push( new THREE.Face3( a, b, d, null, null, 1 ) );
  21597. scope.faces.push( new THREE.Face3( b, c, d, null, null, 1 ) );
  21598. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  21599. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  21600. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  21601. }
  21602. };
  21603. THREE.ExtrudeGeometry.WorldUVGenerator = {
  21604. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  21605. var vertices = geometry.vertices;
  21606. var a = vertices[ indexA ];
  21607. var b = vertices[ indexB ];
  21608. var c = vertices[ indexC ];
  21609. return [
  21610. new THREE.Vector2( a.x, a.y ),
  21611. new THREE.Vector2( b.x, b.y ),
  21612. new THREE.Vector2( c.x, c.y )
  21613. ];
  21614. },
  21615. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  21616. var vertices = geometry.vertices;
  21617. var a = vertices[ indexA ];
  21618. var b = vertices[ indexB ];
  21619. var c = vertices[ indexC ];
  21620. var d = vertices[ indexD ];
  21621. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  21622. return [
  21623. new THREE.Vector2( a.x, 1 - a.z ),
  21624. new THREE.Vector2( b.x, 1 - b.z ),
  21625. new THREE.Vector2( c.x, 1 - c.z ),
  21626. new THREE.Vector2( d.x, 1 - d.z )
  21627. ];
  21628. } else {
  21629. return [
  21630. new THREE.Vector2( a.y, 1 - a.z ),
  21631. new THREE.Vector2( b.y, 1 - b.z ),
  21632. new THREE.Vector2( c.y, 1 - c.z ),
  21633. new THREE.Vector2( d.y, 1 - d.z )
  21634. ];
  21635. }
  21636. }
  21637. };
  21638. // File:src/extras/geometries/ShapeGeometry.js
  21639. /**
  21640. * @author jonobr1 / http://jonobr1.com
  21641. *
  21642. * Creates a one-sided polygonal geometry from a path shape. Similar to
  21643. * ExtrudeGeometry.
  21644. *
  21645. * parameters = {
  21646. *
  21647. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  21648. *
  21649. * material: <int> // material index for front and back faces
  21650. * uvGenerator: <Object> // object that provides UV generator functions
  21651. *
  21652. * }
  21653. **/
  21654. THREE.ShapeGeometry = function ( shapes, options ) {
  21655. THREE.Geometry.call( this );
  21656. this.type = 'ShapeGeometry';
  21657. if ( Array.isArray( shapes ) === false ) shapes = [ shapes ];
  21658. this.addShapeList( shapes, options );
  21659. this.computeFaceNormals();
  21660. };
  21661. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21662. THREE.ShapeGeometry.prototype.constructor = THREE.ShapeGeometry;
  21663. /**
  21664. * Add an array of shapes to THREE.ShapeGeometry.
  21665. */
  21666. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  21667. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  21668. this.addShape( shapes[ i ], options );
  21669. }
  21670. return this;
  21671. };
  21672. /**
  21673. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  21674. */
  21675. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  21676. if ( options === undefined ) options = {};
  21677. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21678. var material = options.material;
  21679. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  21680. //
  21681. var i, l, hole;
  21682. var shapesOffset = this.vertices.length;
  21683. var shapePoints = shape.extractPoints( curveSegments );
  21684. var vertices = shapePoints.shape;
  21685. var holes = shapePoints.holes;
  21686. var reverse = ! THREE.ShapeUtils.isClockWise( vertices );
  21687. if ( reverse ) {
  21688. vertices = vertices.reverse();
  21689. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  21690. for ( i = 0, l = holes.length; i < l; i ++ ) {
  21691. hole = holes[ i ];
  21692. if ( THREE.ShapeUtils.isClockWise( hole ) ) {
  21693. holes[ i ] = hole.reverse();
  21694. }
  21695. }
  21696. reverse = false;
  21697. }
  21698. var faces = THREE.ShapeUtils.triangulateShape( vertices, holes );
  21699. // Vertices
  21700. for ( i = 0, l = holes.length; i < l; i ++ ) {
  21701. hole = holes[ i ];
  21702. vertices = vertices.concat( hole );
  21703. }
  21704. //
  21705. var vert, vlen = vertices.length;
  21706. var face, flen = faces.length;
  21707. for ( i = 0; i < vlen; i ++ ) {
  21708. vert = vertices[ i ];
  21709. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  21710. }
  21711. for ( i = 0; i < flen; i ++ ) {
  21712. face = faces[ i ];
  21713. var a = face[ 0 ] + shapesOffset;
  21714. var b = face[ 1 ] + shapesOffset;
  21715. var c = face[ 2 ] + shapesOffset;
  21716. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  21717. this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) );
  21718. }
  21719. };
  21720. // File:src/extras/geometries/LatheGeometry.js
  21721. /**
  21722. * @author astrodud / http://astrodud.isgreat.org/
  21723. * @author zz85 / https://github.com/zz85
  21724. * @author bhouston / http://clara.io
  21725. */
  21726. // points - to create a closed torus, one must use a set of points
  21727. // like so: [ a, b, c, d, a ], see first is the same as last.
  21728. // segments - the number of circumference segments to create
  21729. // phiStart - the starting radian
  21730. // phiLength - the radian (0 to 2*PI) range of the lathed section
  21731. // 2*pi is a closed lathe, less than 2PI is a portion.
  21732. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  21733. THREE.Geometry.call( this );
  21734. this.type = 'LatheGeometry';
  21735. this.parameters = {
  21736. points: points,
  21737. segments: segments,
  21738. phiStart: phiStart,
  21739. phiLength: phiLength
  21740. };
  21741. segments = segments || 12;
  21742. phiStart = phiStart || 0;
  21743. phiLength = phiLength || 2 * Math.PI;
  21744. var inversePointLength = 1.0 / ( points.length - 1 );
  21745. var inverseSegments = 1.0 / segments;
  21746. for ( var i = 0, il = segments; i <= il; i ++ ) {
  21747. var phi = phiStart + i * inverseSegments * phiLength;
  21748. var c = Math.cos( phi ),
  21749. s = Math.sin( phi );
  21750. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  21751. var pt = points[ j ];
  21752. var vertex = new THREE.Vector3();
  21753. vertex.x = c * pt.x - s * pt.y;
  21754. vertex.y = s * pt.x + c * pt.y;
  21755. vertex.z = pt.z;
  21756. this.vertices.push( vertex );
  21757. }
  21758. }
  21759. var np = points.length;
  21760. for ( var i = 0, il = segments; i < il; i ++ ) {
  21761. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  21762. var base = j + np * i;
  21763. var a = base;
  21764. var b = base + np;
  21765. var c = base + 1 + np;
  21766. var d = base + 1;
  21767. var u0 = i * inverseSegments;
  21768. var v0 = j * inversePointLength;
  21769. var u1 = u0 + inverseSegments;
  21770. var v1 = v0 + inversePointLength;
  21771. this.faces.push( new THREE.Face3( a, b, d ) );
  21772. this.faceVertexUvs[ 0 ].push( [
  21773. new THREE.Vector2( u0, v0 ),
  21774. new THREE.Vector2( u1, v0 ),
  21775. new THREE.Vector2( u0, v1 )
  21776. ] );
  21777. this.faces.push( new THREE.Face3( b, c, d ) );
  21778. this.faceVertexUvs[ 0 ].push( [
  21779. new THREE.Vector2( u1, v0 ),
  21780. new THREE.Vector2( u1, v1 ),
  21781. new THREE.Vector2( u0, v1 )
  21782. ] );
  21783. }
  21784. }
  21785. this.mergeVertices();
  21786. this.computeFaceNormals();
  21787. this.computeVertexNormals();
  21788. };
  21789. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21790. THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry;
  21791. // File:src/extras/geometries/PlaneGeometry.js
  21792. /**
  21793. * @author mrdoob / http://mrdoob.com/
  21794. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  21795. */
  21796. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  21797. THREE.Geometry.call( this );
  21798. this.type = 'PlaneGeometry';
  21799. this.parameters = {
  21800. width: width,
  21801. height: height,
  21802. widthSegments: widthSegments,
  21803. heightSegments: heightSegments
  21804. };
  21805. this.fromBufferGeometry( new THREE.PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  21806. };
  21807. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21808. THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry;
  21809. // File:src/extras/geometries/PlaneBufferGeometry.js
  21810. /**
  21811. * @author mrdoob / http://mrdoob.com/
  21812. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  21813. */
  21814. THREE.PlaneBufferGeometry = function ( width, height, widthSegments, heightSegments ) {
  21815. THREE.BufferGeometry.call( this );
  21816. this.type = 'PlaneBufferGeometry';
  21817. this.parameters = {
  21818. width: width,
  21819. height: height,
  21820. widthSegments: widthSegments,
  21821. heightSegments: heightSegments
  21822. };
  21823. var width_half = width / 2;
  21824. var height_half = height / 2;
  21825. var gridX = Math.floor( widthSegments ) || 1;
  21826. var gridY = Math.floor( heightSegments ) || 1;
  21827. var gridX1 = gridX + 1;
  21828. var gridY1 = gridY + 1;
  21829. var segment_width = width / gridX;
  21830. var segment_height = height / gridY;
  21831. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  21832. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  21833. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  21834. var offset = 0;
  21835. var offset2 = 0;
  21836. for ( var iy = 0; iy < gridY1; iy ++ ) {
  21837. var y = iy * segment_height - height_half;
  21838. for ( var ix = 0; ix < gridX1; ix ++ ) {
  21839. var x = ix * segment_width - width_half;
  21840. vertices[ offset ] = x;
  21841. vertices[ offset + 1 ] = - y;
  21842. normals[ offset + 2 ] = 1;
  21843. uvs[ offset2 ] = ix / gridX;
  21844. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  21845. offset += 3;
  21846. offset2 += 2;
  21847. }
  21848. }
  21849. offset = 0;
  21850. var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  21851. for ( var iy = 0; iy < gridY; iy ++ ) {
  21852. for ( var ix = 0; ix < gridX; ix ++ ) {
  21853. var a = ix + gridX1 * iy;
  21854. var b = ix + gridX1 * ( iy + 1 );
  21855. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  21856. var d = ( ix + 1 ) + gridX1 * iy;
  21857. indices[ offset ] = a;
  21858. indices[ offset + 1 ] = b;
  21859. indices[ offset + 2 ] = d;
  21860. indices[ offset + 3 ] = b;
  21861. indices[ offset + 4 ] = c;
  21862. indices[ offset + 5 ] = d;
  21863. offset += 6;
  21864. }
  21865. }
  21866. this.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  21867. this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  21868. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  21869. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  21870. };
  21871. THREE.PlaneBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  21872. THREE.PlaneBufferGeometry.prototype.constructor = THREE.PlaneBufferGeometry;
  21873. // File:src/extras/geometries/RingGeometry.js
  21874. /**
  21875. * @author Kaleb Murphy
  21876. */
  21877. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  21878. THREE.Geometry.call( this );
  21879. this.type = 'RingGeometry';
  21880. this.parameters = {
  21881. innerRadius: innerRadius,
  21882. outerRadius: outerRadius,
  21883. thetaSegments: thetaSegments,
  21884. phiSegments: phiSegments,
  21885. thetaStart: thetaStart,
  21886. thetaLength: thetaLength
  21887. };
  21888. innerRadius = innerRadius || 0;
  21889. outerRadius = outerRadius || 50;
  21890. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21891. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  21892. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  21893. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 8;
  21894. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  21895. for ( i = 0; i < phiSegments + 1; i ++ ) {
  21896. // concentric circles inside ring
  21897. for ( o = 0; o < thetaSegments + 1; o ++ ) {
  21898. // number of segments per circle
  21899. var vertex = new THREE.Vector3();
  21900. var segment = thetaStart + o / thetaSegments * thetaLength;
  21901. vertex.x = radius * Math.cos( segment );
  21902. vertex.y = radius * Math.sin( segment );
  21903. this.vertices.push( vertex );
  21904. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  21905. }
  21906. radius += radiusStep;
  21907. }
  21908. var n = new THREE.Vector3( 0, 0, 1 );
  21909. for ( i = 0; i < phiSegments; i ++ ) {
  21910. // concentric circles inside ring
  21911. var thetaSegment = i * ( thetaSegments + 1 );
  21912. for ( o = 0; o < thetaSegments ; o ++ ) {
  21913. // number of segments per circle
  21914. var segment = o + thetaSegment;
  21915. var v1 = segment;
  21916. var v2 = segment + thetaSegments + 1;
  21917. var v3 = segment + thetaSegments + 2;
  21918. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  21919. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ] );
  21920. v1 = segment;
  21921. v2 = segment + thetaSegments + 2;
  21922. v3 = segment + 1;
  21923. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  21924. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ] );
  21925. }
  21926. }
  21927. this.computeFaceNormals();
  21928. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  21929. };
  21930. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21931. THREE.RingGeometry.prototype.constructor = THREE.RingGeometry;
  21932. // File:src/extras/geometries/SphereGeometry.js
  21933. /**
  21934. * @author mrdoob / http://mrdoob.com/
  21935. */
  21936. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  21937. THREE.Geometry.call( this );
  21938. this.type = 'SphereGeometry';
  21939. this.parameters = {
  21940. radius: radius,
  21941. widthSegments: widthSegments,
  21942. heightSegments: heightSegments,
  21943. phiStart: phiStart,
  21944. phiLength: phiLength,
  21945. thetaStart: thetaStart,
  21946. thetaLength: thetaLength
  21947. };
  21948. this.fromBufferGeometry( new THREE.SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  21949. };
  21950. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21951. THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry;
  21952. // File:src/extras/geometries/SphereBufferGeometry.js
  21953. /**
  21954. * @author benaadams / https://twitter.com/ben_a_adams
  21955. * based on THREE.SphereGeometry
  21956. */
  21957. THREE.SphereBufferGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  21958. THREE.BufferGeometry.call( this );
  21959. this.type = 'SphereBufferGeometry';
  21960. this.parameters = {
  21961. radius: radius,
  21962. widthSegments: widthSegments,
  21963. heightSegments: heightSegments,
  21964. phiStart: phiStart,
  21965. phiLength: phiLength,
  21966. thetaStart: thetaStart,
  21967. thetaLength: thetaLength
  21968. };
  21969. radius = radius || 50;
  21970. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  21971. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  21972. phiStart = phiStart !== undefined ? phiStart : 0;
  21973. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  21974. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21975. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  21976. var thetaEnd = thetaStart + thetaLength;
  21977. var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) );
  21978. var positions = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  21979. var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  21980. var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  21981. var index = 0, vertices = [], normal = new THREE.Vector3();
  21982. for ( var y = 0; y <= heightSegments; y ++ ) {
  21983. var verticesRow = [];
  21984. var v = y / heightSegments;
  21985. for ( var x = 0; x <= widthSegments; x ++ ) {
  21986. var u = x / widthSegments;
  21987. var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21988. var py = radius * Math.cos( thetaStart + v * thetaLength );
  21989. var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21990. normal.set( px, py, pz ).normalize();
  21991. positions.setXYZ( index, px, py, pz );
  21992. normals.setXYZ( index, normal.x, normal.y, normal.z );
  21993. uvs.setXY( index, u, 1 - v );
  21994. verticesRow.push( index );
  21995. index ++;
  21996. }
  21997. vertices.push( verticesRow );
  21998. }
  21999. var indices = [];
  22000. for ( var y = 0; y < heightSegments; y ++ ) {
  22001. for ( var x = 0; x < widthSegments; x ++ ) {
  22002. var v1 = vertices[ y ][ x + 1 ];
  22003. var v2 = vertices[ y ][ x ];
  22004. var v3 = vertices[ y + 1 ][ x ];
  22005. var v4 = vertices[ y + 1 ][ x + 1 ];
  22006. if ( y !== 0 || thetaStart > 0 ) indices.push( v1, v2, v4 );
  22007. if ( y !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( v2, v3, v4 );
  22008. }
  22009. }
  22010. this.setIndex( new ( positions.count > 65535 ? THREE.Uint32Attribute : THREE.Uint16Attribute )( indices, 1 ) );
  22011. this.addAttribute( 'position', positions );
  22012. this.addAttribute( 'normal', normals );
  22013. this.addAttribute( 'uv', uvs );
  22014. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  22015. };
  22016. THREE.SphereBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  22017. THREE.SphereBufferGeometry.prototype.constructor = THREE.SphereBufferGeometry;
  22018. // File:src/extras/geometries/TorusGeometry.js
  22019. /**
  22020. * @author oosmoxiecode
  22021. * @author mrdoob / http://mrdoob.com/
  22022. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  22023. */
  22024. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  22025. THREE.Geometry.call( this );
  22026. this.type = 'TorusGeometry';
  22027. this.parameters = {
  22028. radius: radius,
  22029. tube: tube,
  22030. radialSegments: radialSegments,
  22031. tubularSegments: tubularSegments,
  22032. arc: arc
  22033. };
  22034. radius = radius || 100;
  22035. tube = tube || 40;
  22036. radialSegments = radialSegments || 8;
  22037. tubularSegments = tubularSegments || 6;
  22038. arc = arc || Math.PI * 2;
  22039. var center = new THREE.Vector3(), uvs = [], normals = [];
  22040. for ( var j = 0; j <= radialSegments; j ++ ) {
  22041. for ( var i = 0; i <= tubularSegments; i ++ ) {
  22042. var u = i / tubularSegments * arc;
  22043. var v = j / radialSegments * Math.PI * 2;
  22044. center.x = radius * Math.cos( u );
  22045. center.y = radius * Math.sin( u );
  22046. var vertex = new THREE.Vector3();
  22047. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  22048. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  22049. vertex.z = tube * Math.sin( v );
  22050. this.vertices.push( vertex );
  22051. uvs.push( new THREE.Vector2( i / tubularSegments, j / radialSegments ) );
  22052. normals.push( vertex.clone().sub( center ).normalize() );
  22053. }
  22054. }
  22055. for ( var j = 1; j <= radialSegments; j ++ ) {
  22056. for ( var i = 1; i <= tubularSegments; i ++ ) {
  22057. var a = ( tubularSegments + 1 ) * j + i - 1;
  22058. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  22059. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  22060. var d = ( tubularSegments + 1 ) * j + i;
  22061. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  22062. this.faces.push( face );
  22063. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  22064. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  22065. this.faces.push( face );
  22066. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  22067. }
  22068. }
  22069. this.computeFaceNormals();
  22070. };
  22071. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22072. THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry;
  22073. // File:src/extras/geometries/TorusKnotGeometry.js
  22074. /**
  22075. * @author oosmoxiecode
  22076. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  22077. */
  22078. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  22079. THREE.Geometry.call( this );
  22080. this.type = 'TorusKnotGeometry';
  22081. this.parameters = {
  22082. radius: radius,
  22083. tube: tube,
  22084. radialSegments: radialSegments,
  22085. tubularSegments: tubularSegments,
  22086. p: p,
  22087. q: q,
  22088. heightScale: heightScale
  22089. };
  22090. radius = radius || 100;
  22091. tube = tube || 40;
  22092. radialSegments = radialSegments || 64;
  22093. tubularSegments = tubularSegments || 8;
  22094. p = p || 2;
  22095. q = q || 3;
  22096. heightScale = heightScale || 1;
  22097. var grid = new Array( radialSegments );
  22098. var tang = new THREE.Vector3();
  22099. var n = new THREE.Vector3();
  22100. var bitan = new THREE.Vector3();
  22101. for ( var i = 0; i < radialSegments; ++ i ) {
  22102. grid[ i ] = new Array( tubularSegments );
  22103. var u = i / radialSegments * 2 * p * Math.PI;
  22104. var p1 = getPos( u, q, p, radius, heightScale );
  22105. var p2 = getPos( u + 0.01, q, p, radius, heightScale );
  22106. tang.subVectors( p2, p1 );
  22107. n.addVectors( p2, p1 );
  22108. bitan.crossVectors( tang, n );
  22109. n.crossVectors( bitan, tang );
  22110. bitan.normalize();
  22111. n.normalize();
  22112. for ( var j = 0; j < tubularSegments; ++ j ) {
  22113. var v = j / tubularSegments * 2 * Math.PI;
  22114. var cx = - tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  22115. var cy = tube * Math.sin( v );
  22116. var pos = new THREE.Vector3();
  22117. pos.x = p1.x + cx * n.x + cy * bitan.x;
  22118. pos.y = p1.y + cx * n.y + cy * bitan.y;
  22119. pos.z = p1.z + cx * n.z + cy * bitan.z;
  22120. grid[ i ][ j ] = this.vertices.push( pos ) - 1;
  22121. }
  22122. }
  22123. for ( var i = 0; i < radialSegments; ++ i ) {
  22124. for ( var j = 0; j < tubularSegments; ++ j ) {
  22125. var ip = ( i + 1 ) % radialSegments;
  22126. var jp = ( j + 1 ) % tubularSegments;
  22127. var a = grid[ i ][ j ];
  22128. var b = grid[ ip ][ j ];
  22129. var c = grid[ ip ][ jp ];
  22130. var d = grid[ i ][ jp ];
  22131. var uva = new THREE.Vector2( i / radialSegments, j / tubularSegments );
  22132. var uvb = new THREE.Vector2( ( i + 1 ) / radialSegments, j / tubularSegments );
  22133. var uvc = new THREE.Vector2( ( i + 1 ) / radialSegments, ( j + 1 ) / tubularSegments );
  22134. var uvd = new THREE.Vector2( i / radialSegments, ( j + 1 ) / tubularSegments );
  22135. this.faces.push( new THREE.Face3( a, b, d ) );
  22136. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  22137. this.faces.push( new THREE.Face3( b, c, d ) );
  22138. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  22139. }
  22140. }
  22141. this.computeFaceNormals();
  22142. this.computeVertexNormals();
  22143. function getPos( u, in_q, in_p, radius, heightScale ) {
  22144. var cu = Math.cos( u );
  22145. var su = Math.sin( u );
  22146. var quOverP = in_q / in_p * u;
  22147. var cs = Math.cos( quOverP );
  22148. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  22149. var ty = radius * ( 2 + cs ) * su * 0.5;
  22150. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  22151. return new THREE.Vector3( tx, ty, tz );
  22152. }
  22153. };
  22154. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22155. THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry;
  22156. // File:src/extras/geometries/TubeGeometry.js
  22157. /**
  22158. * @author WestLangley / https://github.com/WestLangley
  22159. * @author zz85 / https://github.com/zz85
  22160. * @author miningold / https://github.com/miningold
  22161. * @author jonobr1 / https://github.com/jonobr1
  22162. *
  22163. * Modified from the TorusKnotGeometry by @oosmoxiecode
  22164. *
  22165. * Creates a tube which extrudes along a 3d spline
  22166. *
  22167. * Uses parallel transport frames as described in
  22168. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  22169. */
  22170. THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, taper ) {
  22171. THREE.Geometry.call( this );
  22172. this.type = 'TubeGeometry';
  22173. this.parameters = {
  22174. path: path,
  22175. segments: segments,
  22176. radius: radius,
  22177. radialSegments: radialSegments,
  22178. closed: closed,
  22179. taper: taper
  22180. };
  22181. segments = segments || 64;
  22182. radius = radius || 1;
  22183. radialSegments = radialSegments || 8;
  22184. closed = closed || false;
  22185. taper = taper || THREE.TubeGeometry.NoTaper;
  22186. var grid = [];
  22187. var scope = this,
  22188. tangent,
  22189. normal,
  22190. binormal,
  22191. numpoints = segments + 1,
  22192. u, v, r,
  22193. cx, cy,
  22194. pos, pos2 = new THREE.Vector3(),
  22195. i, j,
  22196. ip, jp,
  22197. a, b, c, d,
  22198. uva, uvb, uvc, uvd;
  22199. var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ),
  22200. tangents = frames.tangents,
  22201. normals = frames.normals,
  22202. binormals = frames.binormals;
  22203. // proxy internals
  22204. this.tangents = tangents;
  22205. this.normals = normals;
  22206. this.binormals = binormals;
  22207. function vert( x, y, z ) {
  22208. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  22209. }
  22210. // construct the grid
  22211. for ( i = 0; i < numpoints; i ++ ) {
  22212. grid[ i ] = [];
  22213. u = i / ( numpoints - 1 );
  22214. pos = path.getPointAt( u );
  22215. tangent = tangents[ i ];
  22216. normal = normals[ i ];
  22217. binormal = binormals[ i ];
  22218. r = radius * taper( u );
  22219. for ( j = 0; j < radialSegments; j ++ ) {
  22220. v = j / radialSegments * 2 * Math.PI;
  22221. cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  22222. cy = r * Math.sin( v );
  22223. pos2.copy( pos );
  22224. pos2.x += cx * normal.x + cy * binormal.x;
  22225. pos2.y += cx * normal.y + cy * binormal.y;
  22226. pos2.z += cx * normal.z + cy * binormal.z;
  22227. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  22228. }
  22229. }
  22230. // construct the mesh
  22231. for ( i = 0; i < segments; i ++ ) {
  22232. for ( j = 0; j < radialSegments; j ++ ) {
  22233. ip = ( closed ) ? ( i + 1 ) % segments : i + 1;
  22234. jp = ( j + 1 ) % radialSegments;
  22235. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  22236. b = grid[ ip ][ j ];
  22237. c = grid[ ip ][ jp ];
  22238. d = grid[ i ][ jp ];
  22239. uva = new THREE.Vector2( i / segments, j / radialSegments );
  22240. uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments );
  22241. uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  22242. uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments );
  22243. this.faces.push( new THREE.Face3( a, b, d ) );
  22244. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  22245. this.faces.push( new THREE.Face3( b, c, d ) );
  22246. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  22247. }
  22248. }
  22249. this.computeFaceNormals();
  22250. this.computeVertexNormals();
  22251. };
  22252. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22253. THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry;
  22254. THREE.TubeGeometry.NoTaper = function ( u ) {
  22255. return 1;
  22256. };
  22257. THREE.TubeGeometry.SinusoidalTaper = function ( u ) {
  22258. return Math.sin( Math.PI * u );
  22259. };
  22260. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  22261. THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  22262. var normal = new THREE.Vector3(),
  22263. tangents = [],
  22264. normals = [],
  22265. binormals = [],
  22266. vec = new THREE.Vector3(),
  22267. mat = new THREE.Matrix4(),
  22268. numpoints = segments + 1,
  22269. theta,
  22270. smallest,
  22271. tx, ty, tz,
  22272. i, u;
  22273. // expose internals
  22274. this.tangents = tangents;
  22275. this.normals = normals;
  22276. this.binormals = binormals;
  22277. // compute the tangent vectors for each segment on the path
  22278. for ( i = 0; i < numpoints; i ++ ) {
  22279. u = i / ( numpoints - 1 );
  22280. tangents[ i ] = path.getTangentAt( u );
  22281. tangents[ i ].normalize();
  22282. }
  22283. initialNormal3();
  22284. /*
  22285. function initialNormal1(lastBinormal) {
  22286. // fixed start binormal. Has dangers of 0 vectors
  22287. normals[ 0 ] = new THREE.Vector3();
  22288. binormals[ 0 ] = new THREE.Vector3();
  22289. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  22290. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  22291. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  22292. }
  22293. function initialNormal2() {
  22294. // This uses the Frenet-Serret formula for deriving binormal
  22295. var t2 = path.getTangentAt( epsilon );
  22296. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  22297. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  22298. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  22299. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  22300. }
  22301. */
  22302. function initialNormal3() {
  22303. // select an initial normal vector perpendicular to the first tangent vector,
  22304. // and in the direction of the smallest tangent xyz component
  22305. normals[ 0 ] = new THREE.Vector3();
  22306. binormals[ 0 ] = new THREE.Vector3();
  22307. smallest = Number.MAX_VALUE;
  22308. tx = Math.abs( tangents[ 0 ].x );
  22309. ty = Math.abs( tangents[ 0 ].y );
  22310. tz = Math.abs( tangents[ 0 ].z );
  22311. if ( tx <= smallest ) {
  22312. smallest = tx;
  22313. normal.set( 1, 0, 0 );
  22314. }
  22315. if ( ty <= smallest ) {
  22316. smallest = ty;
  22317. normal.set( 0, 1, 0 );
  22318. }
  22319. if ( tz <= smallest ) {
  22320. normal.set( 0, 0, 1 );
  22321. }
  22322. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  22323. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  22324. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  22325. }
  22326. // compute the slowly-varying normal and binormal vectors for each segment on the path
  22327. for ( i = 1; i < numpoints; i ++ ) {
  22328. normals[ i ] = normals[ i - 1 ].clone();
  22329. binormals[ i ] = binormals[ i - 1 ].clone();
  22330. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  22331. if ( vec.length() > Number.EPSILON ) {
  22332. vec.normalize();
  22333. theta = Math.acos( THREE.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  22334. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  22335. }
  22336. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  22337. }
  22338. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  22339. if ( closed ) {
  22340. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) );
  22341. theta /= ( numpoints - 1 );
  22342. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) {
  22343. theta = - theta;
  22344. }
  22345. for ( i = 1; i < numpoints; i ++ ) {
  22346. // twist a little...
  22347. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  22348. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  22349. }
  22350. }
  22351. };
  22352. // File:src/extras/geometries/PolyhedronGeometry.js
  22353. /**
  22354. * @author clockworkgeek / https://github.com/clockworkgeek
  22355. * @author timothypratley / https://github.com/timothypratley
  22356. * @author WestLangley / http://github.com/WestLangley
  22357. */
  22358. THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) {
  22359. THREE.Geometry.call( this );
  22360. this.type = 'PolyhedronGeometry';
  22361. this.parameters = {
  22362. vertices: vertices,
  22363. indices: indices,
  22364. radius: radius,
  22365. detail: detail
  22366. };
  22367. radius = radius || 1;
  22368. detail = detail || 0;
  22369. var that = this;
  22370. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  22371. prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  22372. }
  22373. var p = this.vertices;
  22374. var faces = [];
  22375. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  22376. var v1 = p[ indices[ i ] ];
  22377. var v2 = p[ indices[ i + 1 ] ];
  22378. var v3 = p[ indices[ i + 2 ] ];
  22379. faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ], undefined, j );
  22380. }
  22381. var centroid = new THREE.Vector3();
  22382. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22383. subdivide( faces[ i ], detail );
  22384. }
  22385. // Handle case when face straddles the seam
  22386. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  22387. var uvs = this.faceVertexUvs[ 0 ][ i ];
  22388. var x0 = uvs[ 0 ].x;
  22389. var x1 = uvs[ 1 ].x;
  22390. var x2 = uvs[ 2 ].x;
  22391. var max = Math.max( x0, x1, x2 );
  22392. var min = Math.min( x0, x1, x2 );
  22393. if ( max > 0.9 && min < 0.1 ) {
  22394. // 0.9 is somewhat arbitrary
  22395. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  22396. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  22397. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  22398. }
  22399. }
  22400. // Apply radius
  22401. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  22402. this.vertices[ i ].multiplyScalar( radius );
  22403. }
  22404. // Merge vertices
  22405. this.mergeVertices();
  22406. this.computeFaceNormals();
  22407. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  22408. // Project vector onto sphere's surface
  22409. function prepare( vector ) {
  22410. var vertex = vector.normalize().clone();
  22411. vertex.index = that.vertices.push( vertex ) - 1;
  22412. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  22413. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  22414. var v = inclination( vector ) / Math.PI + 0.5;
  22415. vertex.uv = new THREE.Vector2( u, 1 - v );
  22416. return vertex;
  22417. }
  22418. // Approximate a curved face with recursively sub-divided triangles.
  22419. function make( v1, v2, v3, materialIndex ) {
  22420. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ], undefined, materialIndex );
  22421. that.faces.push( face );
  22422. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  22423. var azi = azimuth( centroid );
  22424. that.faceVertexUvs[ 0 ].push( [
  22425. correctUV( v1.uv, v1, azi ),
  22426. correctUV( v2.uv, v2, azi ),
  22427. correctUV( v3.uv, v3, azi )
  22428. ] );
  22429. }
  22430. // Analytically subdivide a face to the required detail level.
  22431. function subdivide( face, detail ) {
  22432. var cols = Math.pow( 2, detail );
  22433. var a = prepare( that.vertices[ face.a ] );
  22434. var b = prepare( that.vertices[ face.b ] );
  22435. var c = prepare( that.vertices[ face.c ] );
  22436. var v = [];
  22437. var materialIndex = face.materialIndex;
  22438. // Construct all of the vertices for this subdivision.
  22439. for ( var i = 0 ; i <= cols; i ++ ) {
  22440. v[ i ] = [];
  22441. var aj = prepare( a.clone().lerp( c, i / cols ) );
  22442. var bj = prepare( b.clone().lerp( c, i / cols ) );
  22443. var rows = cols - i;
  22444. for ( var j = 0; j <= rows; j ++ ) {
  22445. if ( j === 0 && i === cols ) {
  22446. v[ i ][ j ] = aj;
  22447. } else {
  22448. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  22449. }
  22450. }
  22451. }
  22452. // Construct all of the faces.
  22453. for ( var i = 0; i < cols ; i ++ ) {
  22454. for ( var j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22455. var k = Math.floor( j / 2 );
  22456. if ( j % 2 === 0 ) {
  22457. make(
  22458. v[ i ][ k + 1 ],
  22459. v[ i + 1 ][ k ],
  22460. v[ i ][ k ],
  22461. materialIndex
  22462. );
  22463. } else {
  22464. make(
  22465. v[ i ][ k + 1 ],
  22466. v[ i + 1 ][ k + 1 ],
  22467. v[ i + 1 ][ k ],
  22468. materialIndex
  22469. );
  22470. }
  22471. }
  22472. }
  22473. }
  22474. // Angle around the Y axis, counter-clockwise when looking from above.
  22475. function azimuth( vector ) {
  22476. return Math.atan2( vector.z, - vector.x );
  22477. }
  22478. // Angle above the XZ plane.
  22479. function inclination( vector ) {
  22480. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22481. }
  22482. // Texture fixing helper. Spheres have some odd behaviours.
  22483. function correctUV( uv, vector, azimuth ) {
  22484. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  22485. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  22486. return uv.clone();
  22487. }
  22488. };
  22489. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22490. THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry;
  22491. // File:src/extras/geometries/DodecahedronGeometry.js
  22492. /**
  22493. * @author Abe Pazos / https://hamoid.com
  22494. */
  22495. THREE.DodecahedronGeometry = function ( radius, detail ) {
  22496. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22497. var r = 1 / t;
  22498. var vertices = [
  22499. // (±1, ±1, ±1)
  22500. - 1, - 1, - 1, - 1, - 1, 1,
  22501. - 1, 1, - 1, - 1, 1, 1,
  22502. 1, - 1, - 1, 1, - 1, 1,
  22503. 1, 1, - 1, 1, 1, 1,
  22504. // (0, ±1/φ, ±φ)
  22505. 0, - r, - t, 0, - r, t,
  22506. 0, r, - t, 0, r, t,
  22507. // (±1/φ, ±φ, 0)
  22508. - r, - t, 0, - r, t, 0,
  22509. r, - t, 0, r, t, 0,
  22510. // (±φ, 0, ±1/φ)
  22511. - t, 0, - r, t, 0, - r,
  22512. - t, 0, r, t, 0, r
  22513. ];
  22514. var indices = [
  22515. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22516. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22517. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22518. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22519. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22520. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22521. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22522. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22523. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22524. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22525. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22526. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22527. ];
  22528. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  22529. this.type = 'DodecahedronGeometry';
  22530. this.parameters = {
  22531. radius: radius,
  22532. detail: detail
  22533. };
  22534. };
  22535. THREE.DodecahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  22536. THREE.DodecahedronGeometry.prototype.constructor = THREE.DodecahedronGeometry;
  22537. // File:src/extras/geometries/IcosahedronGeometry.js
  22538. /**
  22539. * @author timothypratley / https://github.com/timothypratley
  22540. */
  22541. THREE.IcosahedronGeometry = function ( radius, detail ) {
  22542. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22543. var vertices = [
  22544. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  22545. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  22546. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  22547. ];
  22548. var indices = [
  22549. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  22550. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  22551. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  22552. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  22553. ];
  22554. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  22555. this.type = 'IcosahedronGeometry';
  22556. this.parameters = {
  22557. radius: radius,
  22558. detail: detail
  22559. };
  22560. };
  22561. THREE.IcosahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  22562. THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry;
  22563. // File:src/extras/geometries/OctahedronGeometry.js
  22564. /**
  22565. * @author timothypratley / https://github.com/timothypratley
  22566. */
  22567. THREE.OctahedronGeometry = function ( radius, detail ) {
  22568. var vertices = [
  22569. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  22570. ];
  22571. var indices = [
  22572. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  22573. ];
  22574. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  22575. this.type = 'OctahedronGeometry';
  22576. this.parameters = {
  22577. radius: radius,
  22578. detail: detail
  22579. };
  22580. };
  22581. THREE.OctahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  22582. THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry;
  22583. // File:src/extras/geometries/TetrahedronGeometry.js
  22584. /**
  22585. * @author timothypratley / https://github.com/timothypratley
  22586. */
  22587. THREE.TetrahedronGeometry = function ( radius, detail ) {
  22588. var vertices = [
  22589. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  22590. ];
  22591. var indices = [
  22592. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  22593. ];
  22594. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  22595. this.type = 'TetrahedronGeometry';
  22596. this.parameters = {
  22597. radius: radius,
  22598. detail: detail
  22599. };
  22600. };
  22601. THREE.TetrahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  22602. THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry;
  22603. // File:src/extras/geometries/ParametricGeometry.js
  22604. /**
  22605. * @author zz85 / https://github.com/zz85
  22606. * Parametric Surfaces Geometry
  22607. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  22608. *
  22609. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  22610. *
  22611. */
  22612. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  22613. THREE.Geometry.call( this );
  22614. this.type = 'ParametricGeometry';
  22615. this.parameters = {
  22616. func: func,
  22617. slices: slices,
  22618. stacks: stacks
  22619. };
  22620. var verts = this.vertices;
  22621. var faces = this.faces;
  22622. var uvs = this.faceVertexUvs[ 0 ];
  22623. var i, j, p;
  22624. var u, v;
  22625. var sliceCount = slices + 1;
  22626. for ( i = 0; i <= stacks; i ++ ) {
  22627. v = i / stacks;
  22628. for ( j = 0; j <= slices; j ++ ) {
  22629. u = j / slices;
  22630. p = func( u, v );
  22631. verts.push( p );
  22632. }
  22633. }
  22634. var a, b, c, d;
  22635. var uva, uvb, uvc, uvd;
  22636. for ( i = 0; i < stacks; i ++ ) {
  22637. for ( j = 0; j < slices; j ++ ) {
  22638. a = i * sliceCount + j;
  22639. b = i * sliceCount + j + 1;
  22640. c = ( i + 1 ) * sliceCount + j + 1;
  22641. d = ( i + 1 ) * sliceCount + j;
  22642. uva = new THREE.Vector2( j / slices, i / stacks );
  22643. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  22644. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  22645. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  22646. faces.push( new THREE.Face3( a, b, d ) );
  22647. uvs.push( [ uva, uvb, uvd ] );
  22648. faces.push( new THREE.Face3( b, c, d ) );
  22649. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  22650. }
  22651. }
  22652. // console.log(this);
  22653. // magic bullet
  22654. // var diff = this.mergeVertices();
  22655. // console.log('removed ', diff, ' vertices by merging');
  22656. this.computeFaceNormals();
  22657. this.computeVertexNormals();
  22658. };
  22659. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22660. THREE.ParametricGeometry.prototype.constructor = THREE.ParametricGeometry;
  22661. // File:src/extras/geometries/WireframeGeometry.js
  22662. /**
  22663. * @author mrdoob / http://mrdoob.com/
  22664. */
  22665. THREE.WireframeGeometry = function ( geometry ) {
  22666. THREE.BufferGeometry.call( this );
  22667. var edge = [ 0, 0 ], hash = {};
  22668. function sortFunction( a, b ) {
  22669. return a - b;
  22670. }
  22671. var keys = [ 'a', 'b', 'c' ];
  22672. if ( geometry instanceof THREE.Geometry ) {
  22673. var vertices = geometry.vertices;
  22674. var faces = geometry.faces;
  22675. var numEdges = 0;
  22676. // allocate maximal size
  22677. var edges = new Uint32Array( 6 * faces.length );
  22678. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22679. var face = faces[ i ];
  22680. for ( var j = 0; j < 3; j ++ ) {
  22681. edge[ 0 ] = face[ keys[ j ] ];
  22682. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  22683. edge.sort( sortFunction );
  22684. var key = edge.toString();
  22685. if ( hash[ key ] === undefined ) {
  22686. edges[ 2 * numEdges ] = edge[ 0 ];
  22687. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  22688. hash[ key ] = true;
  22689. numEdges ++;
  22690. }
  22691. }
  22692. }
  22693. var coords = new Float32Array( numEdges * 2 * 3 );
  22694. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  22695. for ( var j = 0; j < 2; j ++ ) {
  22696. var vertex = vertices[ edges [ 2 * i + j ] ];
  22697. var index = 6 * i + 3 * j;
  22698. coords[ index + 0 ] = vertex.x;
  22699. coords[ index + 1 ] = vertex.y;
  22700. coords[ index + 2 ] = vertex.z;
  22701. }
  22702. }
  22703. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  22704. } else if ( geometry instanceof THREE.BufferGeometry ) {
  22705. if ( geometry.index !== null ) {
  22706. // Indexed BufferGeometry
  22707. var indices = geometry.index.array;
  22708. var vertices = geometry.attributes.position;
  22709. var drawcalls = geometry.drawcalls;
  22710. var numEdges = 0;
  22711. if ( drawcalls.length === 0 ) {
  22712. geometry.addGroup( 0, indices.length );
  22713. }
  22714. // allocate maximal size
  22715. var edges = new Uint32Array( 2 * indices.length );
  22716. for ( var o = 0, ol = drawcalls.length; o < ol; ++ o ) {
  22717. var drawcall = drawcalls[ o ];
  22718. var start = drawcall.start;
  22719. var count = drawcall.count;
  22720. for ( var i = start, il = start + count; i < il; i += 3 ) {
  22721. for ( var j = 0; j < 3; j ++ ) {
  22722. edge[ 0 ] = indices[ i + j ];
  22723. edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ];
  22724. edge.sort( sortFunction );
  22725. var key = edge.toString();
  22726. if ( hash[ key ] === undefined ) {
  22727. edges[ 2 * numEdges ] = edge[ 0 ];
  22728. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  22729. hash[ key ] = true;
  22730. numEdges ++;
  22731. }
  22732. }
  22733. }
  22734. }
  22735. var coords = new Float32Array( numEdges * 2 * 3 );
  22736. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  22737. for ( var j = 0; j < 2; j ++ ) {
  22738. var index = 6 * i + 3 * j;
  22739. var index2 = edges[ 2 * i + j ];
  22740. coords[ index + 0 ] = vertices.getX( index2 );
  22741. coords[ index + 1 ] = vertices.getY( index2 );
  22742. coords[ index + 2 ] = vertices.getZ( index2 );
  22743. }
  22744. }
  22745. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  22746. } else {
  22747. // non-indexed BufferGeometry
  22748. var vertices = geometry.attributes.position.array;
  22749. var numEdges = vertices.length / 3;
  22750. var numTris = numEdges / 3;
  22751. var coords = new Float32Array( numEdges * 2 * 3 );
  22752. for ( var i = 0, l = numTris; i < l; i ++ ) {
  22753. for ( var j = 0; j < 3; j ++ ) {
  22754. var index = 18 * i + 6 * j;
  22755. var index1 = 9 * i + 3 * j;
  22756. coords[ index + 0 ] = vertices[ index1 ];
  22757. coords[ index + 1 ] = vertices[ index1 + 1 ];
  22758. coords[ index + 2 ] = vertices[ index1 + 2 ];
  22759. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  22760. coords[ index + 3 ] = vertices[ index2 ];
  22761. coords[ index + 4 ] = vertices[ index2 + 1 ];
  22762. coords[ index + 5 ] = vertices[ index2 + 2 ];
  22763. }
  22764. }
  22765. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  22766. }
  22767. }
  22768. };
  22769. THREE.WireframeGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  22770. THREE.WireframeGeometry.prototype.constructor = THREE.WireframeGeometry;
  22771. // File:src/extras/helpers/AxisHelper.js
  22772. /**
  22773. * @author sroucheray / http://sroucheray.org/
  22774. * @author mrdoob / http://mrdoob.com/
  22775. */
  22776. THREE.AxisHelper = function ( size ) {
  22777. size = size || 1;
  22778. var vertices = new Float32Array( [
  22779. 0, 0, 0, size, 0, 0,
  22780. 0, 0, 0, 0, size, 0,
  22781. 0, 0, 0, 0, 0, size
  22782. ] );
  22783. var colors = new Float32Array( [
  22784. 1, 0, 0, 1, 0.6, 0,
  22785. 0, 1, 0, 0.6, 1, 0,
  22786. 0, 0, 1, 0, 0.6, 1
  22787. ] );
  22788. var geometry = new THREE.BufferGeometry();
  22789. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  22790. geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
  22791. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  22792. THREE.LineSegments.call( this, geometry, material );
  22793. };
  22794. THREE.AxisHelper.prototype = Object.create( THREE.LineSegments.prototype );
  22795. THREE.AxisHelper.prototype.constructor = THREE.AxisHelper;
  22796. // File:src/extras/helpers/ArrowHelper.js
  22797. /**
  22798. * @author WestLangley / http://github.com/WestLangley
  22799. * @author zz85 / http://github.com/zz85
  22800. * @author bhouston / http://clara.io
  22801. *
  22802. * Creates an arrow for visualizing directions
  22803. *
  22804. * Parameters:
  22805. * dir - Vector3
  22806. * origin - Vector3
  22807. * length - Number
  22808. * color - color in hex value
  22809. * headLength - Number
  22810. * headWidth - Number
  22811. */
  22812. THREE.ArrowHelper = ( function () {
  22813. var lineGeometry = new THREE.Geometry();
  22814. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) );
  22815. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  22816. coneGeometry.translate( 0, - 0.5, 0 );
  22817. return function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  22818. // dir is assumed to be normalized
  22819. THREE.Object3D.call( this );
  22820. if ( color === undefined ) color = 0xffff00;
  22821. if ( length === undefined ) length = 1;
  22822. if ( headLength === undefined ) headLength = 0.2 * length;
  22823. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  22824. this.position.copy( origin );
  22825. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) );
  22826. this.line.matrixAutoUpdate = false;
  22827. this.add( this.line );
  22828. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) );
  22829. this.cone.matrixAutoUpdate = false;
  22830. this.add( this.cone );
  22831. this.setDirection( dir );
  22832. this.setLength( length, headLength, headWidth );
  22833. }
  22834. }() );
  22835. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  22836. THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper;
  22837. THREE.ArrowHelper.prototype.setDirection = ( function () {
  22838. var axis = new THREE.Vector3();
  22839. var radians;
  22840. return function setDirection( dir ) {
  22841. // dir is assumed to be normalized
  22842. if ( dir.y > 0.99999 ) {
  22843. this.quaternion.set( 0, 0, 0, 1 );
  22844. } else if ( dir.y < - 0.99999 ) {
  22845. this.quaternion.set( 1, 0, 0, 0 );
  22846. } else {
  22847. axis.set( dir.z, 0, - dir.x ).normalize();
  22848. radians = Math.acos( dir.y );
  22849. this.quaternion.setFromAxisAngle( axis, radians );
  22850. }
  22851. };
  22852. }() );
  22853. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  22854. if ( headLength === undefined ) headLength = 0.2 * length;
  22855. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  22856. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  22857. this.line.updateMatrix();
  22858. this.cone.scale.set( headWidth, headLength, headWidth );
  22859. this.cone.position.y = length;
  22860. this.cone.updateMatrix();
  22861. };
  22862. THREE.ArrowHelper.prototype.setColor = function ( color ) {
  22863. this.line.material.color.set( color );
  22864. this.cone.material.color.set( color );
  22865. };
  22866. // File:src/extras/helpers/BoxHelper.js
  22867. /**
  22868. * @author mrdoob / http://mrdoob.com/
  22869. */
  22870. THREE.BoxHelper = function ( object ) {
  22871. 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 ] );
  22872. var positions = new Float32Array( 8 * 3 );
  22873. var geometry = new THREE.BufferGeometry();
  22874. geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  22875. geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  22876. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ) );
  22877. if ( object !== undefined ) {
  22878. this.update( object );
  22879. }
  22880. };
  22881. THREE.BoxHelper.prototype = Object.create( THREE.LineSegments.prototype );
  22882. THREE.BoxHelper.prototype.constructor = THREE.BoxHelper;
  22883. THREE.BoxHelper.prototype.update = ( function () {
  22884. var box = new THREE.Box3();
  22885. return function ( object ) {
  22886. box.setFromObject( object );
  22887. if ( box.empty() ) return;
  22888. var min = box.min;
  22889. var max = box.max;
  22890. /*
  22891. 5____4
  22892. 1/___0/|
  22893. | 6__|_7
  22894. 2/___3/
  22895. 0: max.x, max.y, max.z
  22896. 1: min.x, max.y, max.z
  22897. 2: min.x, min.y, max.z
  22898. 3: max.x, min.y, max.z
  22899. 4: max.x, max.y, min.z
  22900. 5: min.x, max.y, min.z
  22901. 6: min.x, min.y, min.z
  22902. 7: max.x, min.y, min.z
  22903. */
  22904. var position = this.geometry.attributes.position;
  22905. var array = position.array;
  22906. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  22907. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  22908. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  22909. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  22910. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  22911. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  22912. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  22913. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  22914. position.needsUpdate = true;
  22915. this.geometry.computeBoundingSphere();
  22916. }
  22917. } )();
  22918. // File:src/extras/helpers/BoundingBoxHelper.js
  22919. /**
  22920. * @author WestLangley / http://github.com/WestLangley
  22921. */
  22922. // a helper to show the world-axis-aligned bounding box for an object
  22923. THREE.BoundingBoxHelper = function ( object, hex ) {
  22924. var color = ( hex !== undefined ) ? hex : 0x888888;
  22925. this.object = object;
  22926. this.box = new THREE.Box3();
  22927. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  22928. };
  22929. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  22930. THREE.BoundingBoxHelper.prototype.constructor = THREE.BoundingBoxHelper;
  22931. THREE.BoundingBoxHelper.prototype.update = function () {
  22932. this.box.setFromObject( this.object );
  22933. this.box.size( this.scale );
  22934. this.box.center( this.position );
  22935. };
  22936. // File:src/extras/helpers/CameraHelper.js
  22937. /**
  22938. * @author alteredq / http://alteredqualia.com/
  22939. *
  22940. * - shows frustum, line of sight and up of the camera
  22941. * - suitable for fast updates
  22942. * - based on frustum visualization in lightgl.js shadowmap example
  22943. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  22944. */
  22945. THREE.CameraHelper = function ( camera ) {
  22946. var geometry = new THREE.Geometry();
  22947. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  22948. var pointMap = {};
  22949. // colors
  22950. var hexFrustum = 0xffaa00;
  22951. var hexCone = 0xff0000;
  22952. var hexUp = 0x00aaff;
  22953. var hexTarget = 0xffffff;
  22954. var hexCross = 0x333333;
  22955. // near
  22956. addLine( "n1", "n2", hexFrustum );
  22957. addLine( "n2", "n4", hexFrustum );
  22958. addLine( "n4", "n3", hexFrustum );
  22959. addLine( "n3", "n1", hexFrustum );
  22960. // far
  22961. addLine( "f1", "f2", hexFrustum );
  22962. addLine( "f2", "f4", hexFrustum );
  22963. addLine( "f4", "f3", hexFrustum );
  22964. addLine( "f3", "f1", hexFrustum );
  22965. // sides
  22966. addLine( "n1", "f1", hexFrustum );
  22967. addLine( "n2", "f2", hexFrustum );
  22968. addLine( "n3", "f3", hexFrustum );
  22969. addLine( "n4", "f4", hexFrustum );
  22970. // cone
  22971. addLine( "p", "n1", hexCone );
  22972. addLine( "p", "n2", hexCone );
  22973. addLine( "p", "n3", hexCone );
  22974. addLine( "p", "n4", hexCone );
  22975. // up
  22976. addLine( "u1", "u2", hexUp );
  22977. addLine( "u2", "u3", hexUp );
  22978. addLine( "u3", "u1", hexUp );
  22979. // target
  22980. addLine( "c", "t", hexTarget );
  22981. addLine( "p", "c", hexCross );
  22982. // cross
  22983. addLine( "cn1", "cn2", hexCross );
  22984. addLine( "cn3", "cn4", hexCross );
  22985. addLine( "cf1", "cf2", hexCross );
  22986. addLine( "cf3", "cf4", hexCross );
  22987. function addLine( a, b, hex ) {
  22988. addPoint( a, hex );
  22989. addPoint( b, hex );
  22990. }
  22991. function addPoint( id, hex ) {
  22992. geometry.vertices.push( new THREE.Vector3() );
  22993. geometry.colors.push( new THREE.Color( hex ) );
  22994. if ( pointMap[ id ] === undefined ) {
  22995. pointMap[ id ] = [];
  22996. }
  22997. pointMap[ id ].push( geometry.vertices.length - 1 );
  22998. }
  22999. THREE.LineSegments.call( this, geometry, material );
  23000. this.camera = camera;
  23001. this.camera.updateProjectionMatrix();
  23002. this.matrix = camera.matrixWorld;
  23003. this.matrixAutoUpdate = false;
  23004. this.pointMap = pointMap;
  23005. this.update();
  23006. };
  23007. THREE.CameraHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23008. THREE.CameraHelper.prototype.constructor = THREE.CameraHelper;
  23009. THREE.CameraHelper.prototype.update = function () {
  23010. var geometry, pointMap;
  23011. var vector = new THREE.Vector3();
  23012. var camera = new THREE.Camera();
  23013. function setPoint( point, x, y, z ) {
  23014. vector.set( x, y, z ).unproject( camera );
  23015. var points = pointMap[ point ];
  23016. if ( points !== undefined ) {
  23017. for ( var i = 0, il = points.length; i < il; i ++ ) {
  23018. geometry.vertices[ points[ i ] ].copy( vector );
  23019. }
  23020. }
  23021. }
  23022. return function () {
  23023. geometry = this.geometry;
  23024. pointMap = this.pointMap;
  23025. var w = 1, h = 1;
  23026. // we need just camera projection matrix
  23027. // world matrix must be identity
  23028. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  23029. // center / target
  23030. setPoint( "c", 0, 0, - 1 );
  23031. setPoint( "t", 0, 0, 1 );
  23032. // near
  23033. setPoint( "n1", - w, - h, - 1 );
  23034. setPoint( "n2", w, - h, - 1 );
  23035. setPoint( "n3", - w, h, - 1 );
  23036. setPoint( "n4", w, h, - 1 );
  23037. // far
  23038. setPoint( "f1", - w, - h, 1 );
  23039. setPoint( "f2", w, - h, 1 );
  23040. setPoint( "f3", - w, h, 1 );
  23041. setPoint( "f4", w, h, 1 );
  23042. // up
  23043. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  23044. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  23045. setPoint( "u3", 0, h * 2, - 1 );
  23046. // cross
  23047. setPoint( "cf1", - w, 0, 1 );
  23048. setPoint( "cf2", w, 0, 1 );
  23049. setPoint( "cf3", 0, - h, 1 );
  23050. setPoint( "cf4", 0, h, 1 );
  23051. setPoint( "cn1", - w, 0, - 1 );
  23052. setPoint( "cn2", w, 0, - 1 );
  23053. setPoint( "cn3", 0, - h, - 1 );
  23054. setPoint( "cn4", 0, h, - 1 );
  23055. geometry.verticesNeedUpdate = true;
  23056. };
  23057. }();
  23058. // File:src/extras/helpers/DirectionalLightHelper.js
  23059. /**
  23060. * @author alteredq / http://alteredqualia.com/
  23061. * @author mrdoob / http://mrdoob.com/
  23062. * @author WestLangley / http://github.com/WestLangley
  23063. */
  23064. THREE.DirectionalLightHelper = function ( light, size ) {
  23065. THREE.Object3D.call( this );
  23066. this.light = light;
  23067. this.light.updateMatrixWorld();
  23068. this.matrix = light.matrixWorld;
  23069. this.matrixAutoUpdate = false;
  23070. size = size || 1;
  23071. var geometry = new THREE.Geometry();
  23072. geometry.vertices.push(
  23073. new THREE.Vector3( - size, size, 0 ),
  23074. new THREE.Vector3( size, size, 0 ),
  23075. new THREE.Vector3( size, - size, 0 ),
  23076. new THREE.Vector3( - size, - size, 0 ),
  23077. new THREE.Vector3( - size, size, 0 )
  23078. );
  23079. var material = new THREE.LineBasicMaterial( { fog: false } );
  23080. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23081. this.lightPlane = new THREE.Line( geometry, material );
  23082. this.add( this.lightPlane );
  23083. geometry = new THREE.Geometry();
  23084. geometry.vertices.push(
  23085. new THREE.Vector3(),
  23086. new THREE.Vector3()
  23087. );
  23088. material = new THREE.LineBasicMaterial( { fog: false } );
  23089. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23090. this.targetLine = new THREE.Line( geometry, material );
  23091. this.add( this.targetLine );
  23092. this.update();
  23093. };
  23094. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  23095. THREE.DirectionalLightHelper.prototype.constructor = THREE.DirectionalLightHelper;
  23096. THREE.DirectionalLightHelper.prototype.dispose = function () {
  23097. this.lightPlane.geometry.dispose();
  23098. this.lightPlane.material.dispose();
  23099. this.targetLine.geometry.dispose();
  23100. this.targetLine.material.dispose();
  23101. };
  23102. THREE.DirectionalLightHelper.prototype.update = function () {
  23103. var v1 = new THREE.Vector3();
  23104. var v2 = new THREE.Vector3();
  23105. var v3 = new THREE.Vector3();
  23106. return function () {
  23107. v1.setFromMatrixPosition( this.light.matrixWorld );
  23108. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  23109. v3.subVectors( v2, v1 );
  23110. this.lightPlane.lookAt( v3 );
  23111. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23112. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  23113. this.targetLine.geometry.verticesNeedUpdate = true;
  23114. this.targetLine.material.color.copy( this.lightPlane.material.color );
  23115. };
  23116. }();
  23117. // File:src/extras/helpers/EdgesHelper.js
  23118. /**
  23119. * @author WestLangley / http://github.com/WestLangley
  23120. * @param object THREE.Mesh whose geometry will be used
  23121. * @param hex line color
  23122. * @param thresholdAngle the minimum angle (in degrees),
  23123. * between the face normals of adjacent faces,
  23124. * that is required to render an edge. A value of 10 means
  23125. * an edge is only rendered if the angle is at least 10 degrees.
  23126. */
  23127. THREE.EdgesHelper = function ( object, hex, thresholdAngle ) {
  23128. var color = ( hex !== undefined ) ? hex : 0xffffff;
  23129. THREE.LineSegments.call( this, new THREE.EdgesGeometry( object.geometry, thresholdAngle ), new THREE.LineBasicMaterial( { color: color } ) );
  23130. this.matrix = object.matrixWorld;
  23131. this.matrixAutoUpdate = false;
  23132. };
  23133. THREE.EdgesHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23134. THREE.EdgesHelper.prototype.constructor = THREE.EdgesHelper;
  23135. // File:src/extras/helpers/FaceNormalsHelper.js
  23136. /**
  23137. * @author mrdoob / http://mrdoob.com/
  23138. * @author WestLangley / http://github.com/WestLangley
  23139. */
  23140. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  23141. // FaceNormalsHelper only supports THREE.Geometry
  23142. this.object = object;
  23143. this.size = ( size !== undefined ) ? size : 1;
  23144. var color = ( hex !== undefined ) ? hex : 0xffff00;
  23145. var width = ( linewidth !== undefined ) ? linewidth : 1;
  23146. //
  23147. var nNormals = 0;
  23148. var objGeometry = this.object.geometry;
  23149. if ( objGeometry instanceof THREE.Geometry ) {
  23150. nNormals = objGeometry.faces.length;
  23151. } else {
  23152. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  23153. }
  23154. //
  23155. var geometry = new THREE.BufferGeometry();
  23156. var positions = new THREE.Float32Attribute( nNormals * 2 * 3, 3 );
  23157. geometry.addAttribute( 'position', positions );
  23158. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) );
  23159. //
  23160. this.matrixAutoUpdate = false;
  23161. this.update();
  23162. };
  23163. THREE.FaceNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23164. THREE.FaceNormalsHelper.prototype.constructor = THREE.FaceNormalsHelper;
  23165. THREE.FaceNormalsHelper.prototype.update = ( function () {
  23166. var v1 = new THREE.Vector3();
  23167. var v2 = new THREE.Vector3();
  23168. var normalMatrix = new THREE.Matrix3();
  23169. return function update() {
  23170. this.object.updateMatrixWorld( true );
  23171. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  23172. var matrixWorld = this.object.matrixWorld;
  23173. var position = this.geometry.attributes.position;
  23174. //
  23175. var objGeometry = this.object.geometry;
  23176. var vertices = objGeometry.vertices;
  23177. var faces = objGeometry.faces;
  23178. var idx = 0;
  23179. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23180. var face = faces[ i ];
  23181. var normal = face.normal;
  23182. v1.copy( vertices[ face.a ] )
  23183. .add( vertices[ face.b ] )
  23184. .add( vertices[ face.c ] )
  23185. .divideScalar( 3 )
  23186. .applyMatrix4( matrixWorld );
  23187. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  23188. position.setXYZ( idx, v1.x, v1.y, v1.z );
  23189. idx = idx + 1;
  23190. position.setXYZ( idx, v2.x, v2.y, v2.z );
  23191. idx = idx + 1;
  23192. }
  23193. position.needsUpdate = true;
  23194. return this;
  23195. }
  23196. }() );
  23197. // File:src/extras/helpers/GridHelper.js
  23198. /**
  23199. * @author mrdoob / http://mrdoob.com/
  23200. */
  23201. THREE.GridHelper = function ( size, step ) {
  23202. var geometry = new THREE.Geometry();
  23203. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  23204. this.color1 = new THREE.Color( 0x444444 );
  23205. this.color2 = new THREE.Color( 0x888888 );
  23206. for ( var i = - size; i <= size; i += step ) {
  23207. geometry.vertices.push(
  23208. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  23209. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  23210. );
  23211. var color = i === 0 ? this.color1 : this.color2;
  23212. geometry.colors.push( color, color, color, color );
  23213. }
  23214. THREE.LineSegments.call( this, geometry, material );
  23215. };
  23216. THREE.GridHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23217. THREE.GridHelper.prototype.constructor = THREE.GridHelper;
  23218. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  23219. this.color1.set( colorCenterLine );
  23220. this.color2.set( colorGrid );
  23221. this.geometry.colorsNeedUpdate = true;
  23222. };
  23223. // File:src/extras/helpers/HemisphereLightHelper.js
  23224. /**
  23225. * @author alteredq / http://alteredqualia.com/
  23226. * @author mrdoob / http://mrdoob.com/
  23227. */
  23228. THREE.HemisphereLightHelper = function ( light, sphereSize ) {
  23229. THREE.Object3D.call( this );
  23230. this.light = light;
  23231. this.light.updateMatrixWorld();
  23232. this.matrix = light.matrixWorld;
  23233. this.matrixAutoUpdate = false;
  23234. this.colors = [ new THREE.Color(), new THREE.Color() ];
  23235. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  23236. geometry.rotateX( - Math.PI / 2 );
  23237. for ( var i = 0, il = 8; i < il; i ++ ) {
  23238. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  23239. }
  23240. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  23241. this.lightSphere = new THREE.Mesh( geometry, material );
  23242. this.add( this.lightSphere );
  23243. this.update();
  23244. };
  23245. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  23246. THREE.HemisphereLightHelper.prototype.constructor = THREE.HemisphereLightHelper;
  23247. THREE.HemisphereLightHelper.prototype.dispose = function () {
  23248. this.lightSphere.geometry.dispose();
  23249. this.lightSphere.material.dispose();
  23250. };
  23251. THREE.HemisphereLightHelper.prototype.update = function () {
  23252. var vector = new THREE.Vector3();
  23253. return function () {
  23254. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  23255. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  23256. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  23257. this.lightSphere.geometry.colorsNeedUpdate = true;
  23258. }
  23259. }();
  23260. // File:src/extras/helpers/PointLightHelper.js
  23261. /**
  23262. * @author alteredq / http://alteredqualia.com/
  23263. * @author mrdoob / http://mrdoob.com/
  23264. */
  23265. THREE.PointLightHelper = function ( light, sphereSize ) {
  23266. this.light = light;
  23267. this.light.updateMatrixWorld();
  23268. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  23269. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  23270. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23271. THREE.Mesh.call( this, geometry, material );
  23272. this.matrix = this.light.matrixWorld;
  23273. this.matrixAutoUpdate = false;
  23274. /*
  23275. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  23276. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  23277. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  23278. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  23279. var d = light.distance;
  23280. if ( d === 0.0 ) {
  23281. this.lightDistance.visible = false;
  23282. } else {
  23283. this.lightDistance.scale.set( d, d, d );
  23284. }
  23285. this.add( this.lightDistance );
  23286. */
  23287. };
  23288. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  23289. THREE.PointLightHelper.prototype.constructor = THREE.PointLightHelper;
  23290. THREE.PointLightHelper.prototype.dispose = function () {
  23291. this.geometry.dispose();
  23292. this.material.dispose();
  23293. };
  23294. THREE.PointLightHelper.prototype.update = function () {
  23295. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23296. /*
  23297. var d = this.light.distance;
  23298. if ( d === 0.0 ) {
  23299. this.lightDistance.visible = false;
  23300. } else {
  23301. this.lightDistance.visible = true;
  23302. this.lightDistance.scale.set( d, d, d );
  23303. }
  23304. */
  23305. };
  23306. // File:src/extras/helpers/SkeletonHelper.js
  23307. /**
  23308. * @author Sean Griffin / http://twitter.com/sgrif
  23309. * @author Michael Guerrero / http://realitymeltdown.com
  23310. * @author mrdoob / http://mrdoob.com/
  23311. * @author ikerr / http://verold.com
  23312. */
  23313. THREE.SkeletonHelper = function ( object ) {
  23314. this.bones = this.getBoneList( object );
  23315. var geometry = new THREE.Geometry();
  23316. for ( var i = 0; i < this.bones.length; i ++ ) {
  23317. var bone = this.bones[ i ];
  23318. if ( bone.parent instanceof THREE.Bone ) {
  23319. geometry.vertices.push( new THREE.Vector3() );
  23320. geometry.vertices.push( new THREE.Vector3() );
  23321. geometry.colors.push( new THREE.Color( 0, 0, 1 ) );
  23322. geometry.colors.push( new THREE.Color( 0, 1, 0 ) );
  23323. }
  23324. }
  23325. geometry.dynamic = true;
  23326. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  23327. THREE.LineSegments.call( this, geometry, material );
  23328. this.root = object;
  23329. this.matrix = object.matrixWorld;
  23330. this.matrixAutoUpdate = false;
  23331. this.update();
  23332. };
  23333. THREE.SkeletonHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23334. THREE.SkeletonHelper.prototype.constructor = THREE.SkeletonHelper;
  23335. THREE.SkeletonHelper.prototype.getBoneList = function( object ) {
  23336. var boneList = [];
  23337. if ( object instanceof THREE.Bone ) {
  23338. boneList.push( object );
  23339. }
  23340. for ( var i = 0; i < object.children.length; i ++ ) {
  23341. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  23342. }
  23343. return boneList;
  23344. };
  23345. THREE.SkeletonHelper.prototype.update = function () {
  23346. var geometry = this.geometry;
  23347. var matrixWorldInv = new THREE.Matrix4().getInverse( this.root.matrixWorld );
  23348. var boneMatrix = new THREE.Matrix4();
  23349. var j = 0;
  23350. for ( var i = 0; i < this.bones.length; i ++ ) {
  23351. var bone = this.bones[ i ];
  23352. if ( bone.parent instanceof THREE.Bone ) {
  23353. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  23354. geometry.vertices[ j ].setFromMatrixPosition( boneMatrix );
  23355. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  23356. geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix );
  23357. j += 2;
  23358. }
  23359. }
  23360. geometry.verticesNeedUpdate = true;
  23361. geometry.computeBoundingSphere();
  23362. };
  23363. // File:src/extras/helpers/SpotLightHelper.js
  23364. /**
  23365. * @author alteredq / http://alteredqualia.com/
  23366. * @author mrdoob / http://mrdoob.com/
  23367. * @author WestLangley / http://github.com/WestLangley
  23368. */
  23369. THREE.SpotLightHelper = function ( light ) {
  23370. THREE.Object3D.call( this );
  23371. this.light = light;
  23372. this.light.updateMatrixWorld();
  23373. this.matrix = light.matrixWorld;
  23374. this.matrixAutoUpdate = false;
  23375. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  23376. geometry.translate( 0, - 0.5, 0 );
  23377. geometry.rotateX( - Math.PI / 2 );
  23378. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  23379. this.cone = new THREE.Mesh( geometry, material );
  23380. this.add( this.cone );
  23381. this.update();
  23382. };
  23383. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  23384. THREE.SpotLightHelper.prototype.constructor = THREE.SpotLightHelper;
  23385. THREE.SpotLightHelper.prototype.dispose = function () {
  23386. this.cone.geometry.dispose();
  23387. this.cone.material.dispose();
  23388. };
  23389. THREE.SpotLightHelper.prototype.update = function () {
  23390. var vector = new THREE.Vector3();
  23391. var vector2 = new THREE.Vector3();
  23392. return function () {
  23393. var coneLength = this.light.distance ? this.light.distance : 10000;
  23394. var coneWidth = coneLength * Math.tan( this.light.angle );
  23395. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  23396. vector.setFromMatrixPosition( this.light.matrixWorld );
  23397. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  23398. this.cone.lookAt( vector2.sub( vector ) );
  23399. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23400. };
  23401. }();
  23402. // File:src/extras/helpers/VertexNormalsHelper.js
  23403. /**
  23404. * @author mrdoob / http://mrdoob.com/
  23405. * @author WestLangley / http://github.com/WestLangley
  23406. */
  23407. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  23408. this.object = object;
  23409. this.size = ( size !== undefined ) ? size : 1;
  23410. var color = ( hex !== undefined ) ? hex : 0xff0000;
  23411. var width = ( linewidth !== undefined ) ? linewidth : 1;
  23412. //
  23413. var nNormals = 0;
  23414. var objGeometry = this.object.geometry;
  23415. if ( objGeometry instanceof THREE.Geometry ) {
  23416. nNormals = objGeometry.faces.length * 3;
  23417. } else if ( objGeometry instanceof THREE.BufferGeometry ) {
  23418. nNormals = objGeometry.attributes.normal.count
  23419. }
  23420. //
  23421. var geometry = new THREE.BufferGeometry();
  23422. var positions = new THREE.Float32Attribute( nNormals * 2 * 3, 3 );
  23423. geometry.addAttribute( 'position', positions );
  23424. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) );
  23425. //
  23426. this.matrixAutoUpdate = false;
  23427. this.update();
  23428. };
  23429. THREE.VertexNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23430. THREE.VertexNormalsHelper.prototype.constructor = THREE.VertexNormalsHelper;
  23431. THREE.VertexNormalsHelper.prototype.update = ( function () {
  23432. var v1 = new THREE.Vector3();
  23433. var v2 = new THREE.Vector3();
  23434. var normalMatrix = new THREE.Matrix3();
  23435. return function update() {
  23436. var keys = [ 'a', 'b', 'c' ];
  23437. this.object.updateMatrixWorld( true );
  23438. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  23439. var matrixWorld = this.object.matrixWorld;
  23440. var position = this.geometry.attributes.position;
  23441. //
  23442. var objGeometry = this.object.geometry;
  23443. if ( objGeometry instanceof THREE.Geometry ) {
  23444. var vertices = objGeometry.vertices;
  23445. var faces = objGeometry.faces;
  23446. var idx = 0;
  23447. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23448. var face = faces[ i ];
  23449. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  23450. var vertex = vertices[ face[ keys[ j ] ] ];
  23451. var normal = face.vertexNormals[ j ];
  23452. v1.copy( vertex ).applyMatrix4( matrixWorld );
  23453. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  23454. position.setXYZ( idx, v1.x, v1.y, v1.z );
  23455. idx = idx + 1;
  23456. position.setXYZ( idx, v2.x, v2.y, v2.z );
  23457. idx = idx + 1;
  23458. }
  23459. }
  23460. } else if ( objGeometry instanceof THREE.BufferGeometry ) {
  23461. var objPos = objGeometry.attributes.position;
  23462. var objNorm = objGeometry.attributes.normal;
  23463. var idx = 0;
  23464. // for simplicity, ignore index and drawcalls, and render every normal
  23465. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  23466. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  23467. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  23468. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  23469. position.setXYZ( idx, v1.x, v1.y, v1.z );
  23470. idx = idx + 1;
  23471. position.setXYZ( idx, v2.x, v2.y, v2.z );
  23472. idx = idx + 1;
  23473. }
  23474. }
  23475. position.needsUpdate = true;
  23476. return this;
  23477. }
  23478. }() );
  23479. // File:src/extras/helpers/WireframeHelper.js
  23480. /**
  23481. * @author mrdoob / http://mrdoob.com/
  23482. */
  23483. THREE.WireframeHelper = function ( object, hex ) {
  23484. var color = ( hex !== undefined ) ? hex : 0xffffff;
  23485. THREE.LineSegments.call( this, new THREE.WireframeGeometry( object.geometry ), new THREE.LineBasicMaterial( { color: color } ) );
  23486. this.matrix = object.matrixWorld;
  23487. this.matrixAutoUpdate = false;
  23488. };
  23489. THREE.WireframeHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23490. THREE.WireframeHelper.prototype.constructor = THREE.WireframeHelper;
  23491. // File:src/extras/objects/ImmediateRenderObject.js
  23492. /**
  23493. * @author alteredq / http://alteredqualia.com/
  23494. */
  23495. THREE.ImmediateRenderObject = function ( material ) {
  23496. THREE.Object3D.call( this );
  23497. this.material = material;
  23498. this.render = function ( renderCallback ) {};
  23499. };
  23500. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  23501. THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject;
  23502. // File:src/extras/objects/MorphBlendMesh.js
  23503. /**
  23504. * @author alteredq / http://alteredqualia.com/
  23505. */
  23506. THREE.MorphBlendMesh = function( geometry, material ) {
  23507. THREE.Mesh.call( this, geometry, material );
  23508. this.animationsMap = {};
  23509. this.animationsList = [];
  23510. // prepare default animation
  23511. // (all frames played together in 1 second)
  23512. var numFrames = this.geometry.morphTargets.length;
  23513. var name = "__default";
  23514. var startFrame = 0;
  23515. var endFrame = numFrames - 1;
  23516. var fps = numFrames / 1;
  23517. this.createAnimation( name, startFrame, endFrame, fps );
  23518. this.setAnimationWeight( name, 1 );
  23519. };
  23520. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  23521. THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh;
  23522. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  23523. var animation = {
  23524. start: start,
  23525. end: end,
  23526. length: end - start + 1,
  23527. fps: fps,
  23528. duration: ( end - start ) / fps,
  23529. lastFrame: 0,
  23530. currentFrame: 0,
  23531. active: false,
  23532. time: 0,
  23533. direction: 1,
  23534. weight: 1,
  23535. directionBackwards: false,
  23536. mirroredLoop: false
  23537. };
  23538. this.animationsMap[ name ] = animation;
  23539. this.animationsList.push( animation );
  23540. };
  23541. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  23542. var pattern = /([a-z]+)_?(\d+)/;
  23543. var firstAnimation, frameRanges = {};
  23544. var geometry = this.geometry;
  23545. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  23546. var morph = geometry.morphTargets[ i ];
  23547. var chunks = morph.name.match( pattern );
  23548. if ( chunks && chunks.length > 1 ) {
  23549. var name = chunks[ 1 ];
  23550. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  23551. var range = frameRanges[ name ];
  23552. if ( i < range.start ) range.start = i;
  23553. if ( i > range.end ) range.end = i;
  23554. if ( ! firstAnimation ) firstAnimation = name;
  23555. }
  23556. }
  23557. for ( var name in frameRanges ) {
  23558. var range = frameRanges[ name ];
  23559. this.createAnimation( name, range.start, range.end, fps );
  23560. }
  23561. this.firstAnimation = firstAnimation;
  23562. };
  23563. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  23564. var animation = this.animationsMap[ name ];
  23565. if ( animation ) {
  23566. animation.direction = 1;
  23567. animation.directionBackwards = false;
  23568. }
  23569. };
  23570. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  23571. var animation = this.animationsMap[ name ];
  23572. if ( animation ) {
  23573. animation.direction = - 1;
  23574. animation.directionBackwards = true;
  23575. }
  23576. };
  23577. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  23578. var animation = this.animationsMap[ name ];
  23579. if ( animation ) {
  23580. animation.fps = fps;
  23581. animation.duration = ( animation.end - animation.start ) / animation.fps;
  23582. }
  23583. };
  23584. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  23585. var animation = this.animationsMap[ name ];
  23586. if ( animation ) {
  23587. animation.duration = duration;
  23588. animation.fps = ( animation.end - animation.start ) / animation.duration;
  23589. }
  23590. };
  23591. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  23592. var animation = this.animationsMap[ name ];
  23593. if ( animation ) {
  23594. animation.weight = weight;
  23595. }
  23596. };
  23597. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  23598. var animation = this.animationsMap[ name ];
  23599. if ( animation ) {
  23600. animation.time = time;
  23601. }
  23602. };
  23603. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  23604. var time = 0;
  23605. var animation = this.animationsMap[ name ];
  23606. if ( animation ) {
  23607. time = animation.time;
  23608. }
  23609. return time;
  23610. };
  23611. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  23612. var duration = - 1;
  23613. var animation = this.animationsMap[ name ];
  23614. if ( animation ) {
  23615. duration = animation.duration;
  23616. }
  23617. return duration;
  23618. };
  23619. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  23620. var animation = this.animationsMap[ name ];
  23621. if ( animation ) {
  23622. animation.time = 0;
  23623. animation.active = true;
  23624. } else {
  23625. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  23626. }
  23627. };
  23628. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  23629. var animation = this.animationsMap[ name ];
  23630. if ( animation ) {
  23631. animation.active = false;
  23632. }
  23633. };
  23634. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  23635. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  23636. var animation = this.animationsList[ i ];
  23637. if ( ! animation.active ) continue;
  23638. var frameTime = animation.duration / animation.length;
  23639. animation.time += animation.direction * delta;
  23640. if ( animation.mirroredLoop ) {
  23641. if ( animation.time > animation.duration || animation.time < 0 ) {
  23642. animation.direction *= - 1;
  23643. if ( animation.time > animation.duration ) {
  23644. animation.time = animation.duration;
  23645. animation.directionBackwards = true;
  23646. }
  23647. if ( animation.time < 0 ) {
  23648. animation.time = 0;
  23649. animation.directionBackwards = false;
  23650. }
  23651. }
  23652. } else {
  23653. animation.time = animation.time % animation.duration;
  23654. if ( animation.time < 0 ) animation.time += animation.duration;
  23655. }
  23656. var keyframe = animation.start + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  23657. var weight = animation.weight;
  23658. if ( keyframe !== animation.currentFrame ) {
  23659. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  23660. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  23661. this.morphTargetInfluences[ keyframe ] = 0;
  23662. animation.lastFrame = animation.currentFrame;
  23663. animation.currentFrame = keyframe;
  23664. }
  23665. var mix = ( animation.time % frameTime ) / frameTime;
  23666. if ( animation.directionBackwards ) mix = 1 - mix;
  23667. if ( animation.currentFrame !== animation.lastFrame ) {
  23668. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  23669. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  23670. } else {
  23671. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  23672. }
  23673. }
  23674. };