ThreeExtras.js 304 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743
  1. // ThreeExtras.js - http://github.com/mrdoob/three.js
  2. /**
  3. * @author alteredq / http://alteredqualia.com/
  4. */
  5. THREE.ColorUtils = {
  6. adjustHSV : function ( color, h, s, v ) {
  7. var hsv = THREE.ColorUtils.__hsv;
  8. THREE.ColorUtils.rgbToHsv( color, hsv );
  9. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  10. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  11. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  12. color.setHSV( hsv.h, hsv.s, hsv.v );
  13. },
  14. // based on MochiKit implementation by Bob Ippolito
  15. rgbToHsv : function ( color, hsv ) {
  16. var r = color.r;
  17. var g = color.g;
  18. var b = color.b;
  19. var max = Math.max( Math.max( r, g ), b );
  20. var min = Math.min( Math.min( r, g ), b );
  21. var hue;
  22. var saturation;
  23. var value = max;
  24. if ( min === max ) {
  25. hue = 0;
  26. saturation = 0;
  27. } else {
  28. var delta = ( max - min );
  29. saturation = delta / max;
  30. if ( r === max ) {
  31. hue = ( g - b ) / delta;
  32. } else if ( g === max ) {
  33. hue = 2 + ( ( b - r ) / delta );
  34. } else {
  35. hue = 4 + ( ( r - g ) / delta );
  36. }
  37. hue /= 6;
  38. if ( hue < 0 ) {
  39. hue += 1;
  40. }
  41. if ( hue > 1 ) {
  42. hue -= 1;
  43. }
  44. }
  45. if ( hsv === undefined ) {
  46. hsv = { h: 0, s: 0, v: 0 };
  47. }
  48. hsv.h = hue;
  49. hsv.s = saturation;
  50. hsv.v = value;
  51. return hsv;
  52. }
  53. };
  54. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  55. * @author mrdoob / http://mrdoob.com/
  56. * @author alteredq / http://alteredqualia.com/
  57. */
  58. THREE.GeometryUtils = {
  59. // Merge two geometries or geometry and geometry from object (using object's transform)
  60. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  61. var matrix, matrixRotation,
  62. vertexOffset = geometry1.vertices.length,
  63. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  64. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  65. vertices1 = geometry1.vertices,
  66. vertices2 = geometry2.vertices,
  67. faces1 = geometry1.faces,
  68. faces2 = geometry2.faces,
  69. uvs1 = geometry1.faceVertexUvs[ 0 ],
  70. uvs2 = geometry2.faceVertexUvs[ 0 ];
  71. var geo1MaterialsMap = {};
  72. for ( var i = 0; i < geometry1.materials.length; i ++ ) {
  73. var id = geometry1.materials[ i ].id;
  74. geo1MaterialsMap[ id ] = i;
  75. }
  76. if ( object2 instanceof THREE.Mesh ) {
  77. object2.matrixAutoUpdate && object2.updateMatrix();
  78. matrix = object2.matrix;
  79. matrixRotation = new THREE.Matrix4();
  80. matrixRotation.extractRotation( matrix, object2.scale );
  81. }
  82. // vertices
  83. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  84. var vertex = vertices2[ i ];
  85. var vertexCopy = vertex.clone();
  86. if ( matrix ) matrix.multiplyVector3( vertexCopy );
  87. vertices1.push( vertexCopy );
  88. }
  89. // faces
  90. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  91. var face = faces2[ i ], faceCopy, normal, color,
  92. faceVertexNormals = face.vertexNormals,
  93. faceVertexColors = face.vertexColors;
  94. if ( face instanceof THREE.Face3 ) {
  95. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  96. } else if ( face instanceof THREE.Face4 ) {
  97. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  98. }
  99. faceCopy.normal.copy( face.normal );
  100. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  101. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  102. normal = faceVertexNormals[ j ].clone();
  103. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  104. faceCopy.vertexNormals.push( normal );
  105. }
  106. faceCopy.color.copy( face.color );
  107. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  108. color = faceVertexColors[ j ];
  109. faceCopy.vertexColors.push( color.clone() );
  110. }
  111. if ( face.materialIndex !== undefined ) {
  112. var material2 = geometry2.materials[ face.materialIndex ];
  113. var materialId2 = material2.id;
  114. var materialIndex = geo1MaterialsMap[ materialId2 ];
  115. if ( materialIndex === undefined ) {
  116. materialIndex = geometry1.materials.length;
  117. geo1MaterialsMap[ materialId2 ] = materialIndex;
  118. geometry1.materials.push( material2 );
  119. }
  120. faceCopy.materialIndex = materialIndex;
  121. }
  122. faceCopy.centroid.copy( face.centroid );
  123. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  124. faces1.push( faceCopy );
  125. }
  126. // uvs
  127. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  128. var uv = uvs2[ i ], uvCopy = [];
  129. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  130. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  131. }
  132. uvs1.push( uvCopy );
  133. }
  134. },
  135. clone: function ( geometry ) {
  136. var cloneGeo = new THREE.Geometry();
  137. var i, il;
  138. var vertices = geometry.vertices,
  139. faces = geometry.faces,
  140. uvs = geometry.faceVertexUvs[ 0 ];
  141. // materials
  142. if ( geometry.materials ) {
  143. cloneGeo.materials = geometry.materials.slice();
  144. }
  145. // vertices
  146. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  147. var vertex = vertices[ i ];
  148. cloneGeo.vertices.push( vertex.clone() );
  149. }
  150. // faces
  151. for ( i = 0, il = faces.length; i < il; i ++ ) {
  152. var face = faces[ i ];
  153. cloneGeo.faces.push( face.clone() );
  154. }
  155. // uvs
  156. for ( i = 0, il = uvs.length; i < il; i ++ ) {
  157. var uv = uvs[ i ], uvCopy = [];
  158. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  159. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  160. }
  161. cloneGeo.faceVertexUvs[ 0 ].push( uvCopy );
  162. }
  163. return cloneGeo;
  164. },
  165. // Get random point in triangle (via barycentric coordinates)
  166. // (uniform distribution)
  167. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  168. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  169. var a, b, c,
  170. point = new THREE.Vector3(),
  171. tmp = THREE.GeometryUtils.__v1;
  172. a = THREE.GeometryUtils.random();
  173. b = THREE.GeometryUtils.random();
  174. if ( ( a + b ) > 1 ) {
  175. a = 1 - a;
  176. b = 1 - b;
  177. }
  178. c = 1 - a - b;
  179. point.copy( vectorA );
  180. point.multiplyScalar( a );
  181. tmp.copy( vectorB );
  182. tmp.multiplyScalar( b );
  183. point.addSelf( tmp );
  184. tmp.copy( vectorC );
  185. tmp.multiplyScalar( c );
  186. point.addSelf( tmp );
  187. return point;
  188. },
  189. // Get random point in face (triangle / quad)
  190. // (uniform distribution)
  191. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  192. var vA, vB, vC, vD;
  193. if ( face instanceof THREE.Face3 ) {
  194. vA = geometry.vertices[ face.a ];
  195. vB = geometry.vertices[ face.b ];
  196. vC = geometry.vertices[ face.c ];
  197. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  198. } else if ( face instanceof THREE.Face4 ) {
  199. vA = geometry.vertices[ face.a ];
  200. vB = geometry.vertices[ face.b ];
  201. vC = geometry.vertices[ face.c ];
  202. vD = geometry.vertices[ face.d ];
  203. var area1, area2;
  204. if ( useCachedAreas ) {
  205. if ( face._area1 && face._area2 ) {
  206. area1 = face._area1;
  207. area2 = face._area2;
  208. } else {
  209. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  210. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  211. face._area1 = area1;
  212. face._area2 = area2;
  213. }
  214. } else {
  215. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  216. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  217. }
  218. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  219. if ( r < area1 ) {
  220. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  221. } else {
  222. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  223. }
  224. }
  225. },
  226. // Get uniformly distributed random points in mesh
  227. // - create array with cumulative sums of face areas
  228. // - pick random number from 0 to total area
  229. // - find corresponding place in area array by binary search
  230. // - get random point in face
  231. randomPointsInGeometry: function ( geometry, n ) {
  232. var face, i,
  233. faces = geometry.faces,
  234. vertices = geometry.vertices,
  235. il = faces.length,
  236. totalArea = 0,
  237. cumulativeAreas = [],
  238. vA, vB, vC, vD;
  239. // precompute face areas
  240. for ( i = 0; i < il; i ++ ) {
  241. face = faces[ i ];
  242. if ( face instanceof THREE.Face3 ) {
  243. vA = vertices[ face.a ];
  244. vB = vertices[ face.b ];
  245. vC = vertices[ face.c ];
  246. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  247. } else if ( face instanceof THREE.Face4 ) {
  248. vA = vertices[ face.a ];
  249. vB = vertices[ face.b ];
  250. vC = vertices[ face.c ];
  251. vD = vertices[ face.d ];
  252. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  253. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  254. face._area = face._area1 + face._area2;
  255. }
  256. totalArea += face._area;
  257. cumulativeAreas[ i ] = totalArea;
  258. }
  259. // binary search cumulative areas array
  260. function binarySearchIndices( value ) {
  261. function binarySearch( start, end ) {
  262. // return closest larger index
  263. // if exact number is not found
  264. if ( end < start )
  265. return start;
  266. var mid = start + Math.floor( ( end - start ) / 2 );
  267. if ( cumulativeAreas[ mid ] > value ) {
  268. return binarySearch( start, mid - 1 );
  269. } else if ( cumulativeAreas[ mid ] < value ) {
  270. return binarySearch( mid + 1, end );
  271. } else {
  272. return mid;
  273. }
  274. }
  275. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  276. return result;
  277. }
  278. // pick random face weighted by face area
  279. var r, index,
  280. result = [];
  281. var stats = {};
  282. for ( i = 0; i < n; i ++ ) {
  283. r = THREE.GeometryUtils.random() * totalArea;
  284. index = binarySearchIndices( r );
  285. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  286. if ( ! stats[ index ] ) {
  287. stats[ index ] = 1;
  288. } else {
  289. stats[ index ] += 1;
  290. }
  291. }
  292. return result;
  293. },
  294. // Get triangle area (by Heron's formula)
  295. // http://en.wikipedia.org/wiki/Heron%27s_formula
  296. triangleArea: function ( vectorA, vectorB, vectorC ) {
  297. var s, a, b, c,
  298. tmp = THREE.GeometryUtils.__v1;
  299. tmp.sub( vectorA, vectorB );
  300. a = tmp.length();
  301. tmp.sub( vectorA, vectorC );
  302. b = tmp.length();
  303. tmp.sub( vectorB, vectorC );
  304. c = tmp.length();
  305. s = 0.5 * ( a + b + c );
  306. return Math.sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
  307. },
  308. // Center geometry so that 0,0,0 is in center of bounding box
  309. center: function ( geometry ) {
  310. geometry.computeBoundingBox();
  311. var bb = geometry.boundingBox;
  312. var offset = new THREE.Vector3();
  313. offset.add( bb.min, bb.max );
  314. offset.multiplyScalar( -0.5 );
  315. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  316. geometry.computeBoundingBox();
  317. return offset;
  318. },
  319. // Normalize UVs to be from <0,1>
  320. // (for now just the first set of UVs)
  321. normalizeUVs: function ( geometry ) {
  322. var uvSet = geometry.faceVertexUvs[ 0 ];
  323. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  324. var uvs = uvSet[ i ];
  325. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  326. // texture repeat
  327. if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
  328. if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );
  329. }
  330. }
  331. },
  332. triangulateQuads: function ( geometry ) {
  333. var i, il, j, jl;
  334. var faces = [];
  335. var faceUvs = [];
  336. var faceVertexUvs = [];
  337. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  338. faceUvs[ i ] = [];
  339. }
  340. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  341. faceVertexUvs[ i ] = [];
  342. }
  343. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  344. var face = geometry.faces[ i ];
  345. if ( face instanceof THREE.Face4 ) {
  346. var a = face.a;
  347. var b = face.b;
  348. var c = face.c;
  349. var d = face.d;
  350. var triA = new THREE.Face3();
  351. var triB = new THREE.Face3();
  352. triA.color.copy( face.color );
  353. triB.color.copy( face.color );
  354. triA.materialIndex = face.materialIndex;
  355. triB.materialIndex = face.materialIndex;
  356. triA.a = a;
  357. triA.b = b;
  358. triA.c = d;
  359. triB.a = b;
  360. triB.b = c;
  361. triB.c = d;
  362. if ( face.vertexColors.length === 4 ) {
  363. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  364. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  365. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  366. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  367. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  368. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  369. }
  370. faces.push( triA, triB );
  371. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  372. if ( geometry.faceVertexUvs[ j ].length ) {
  373. var uvs = geometry.faceVertexUvs[ j ][ i ];
  374. var uvA = uvs[ 0 ];
  375. var uvB = uvs[ 1 ];
  376. var uvC = uvs[ 2 ];
  377. var uvD = uvs[ 3 ];
  378. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  379. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  380. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  381. }
  382. }
  383. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  384. if ( geometry.faceUvs[ j ].length ) {
  385. var faceUv = geometry.faceUvs[ j ][ i ];
  386. faceUvs[ j ].push( faceUv, faceUv );
  387. }
  388. }
  389. } else {
  390. faces.push( face );
  391. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  392. faceUvs[ j ].push( geometry.faceUvs[ j ] );
  393. }
  394. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  395. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ] );
  396. }
  397. }
  398. }
  399. geometry.faces = faces;
  400. geometry.faceUvs = faceUvs;
  401. geometry.faceVertexUvs = faceVertexUvs;
  402. geometry.computeCentroids();
  403. geometry.computeFaceNormals();
  404. geometry.computeVertexNormals();
  405. if ( geometry.hasTangents ) geometry.computeTangents();
  406. },
  407. // Make all faces use unique vertices
  408. // so that each face can be separated from others
  409. explode: function( geometry ) {
  410. var vertices = [];
  411. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  412. var n = vertices.length;
  413. var face = geometry.faces[ i ];
  414. if ( face instanceof THREE.Face4 ) {
  415. var a = face.a;
  416. var b = face.b;
  417. var c = face.c;
  418. var d = face.d;
  419. var va = geometry.vertices[ a ];
  420. var vb = geometry.vertices[ b ];
  421. var vc = geometry.vertices[ c ];
  422. var vd = geometry.vertices[ d ];
  423. vertices.push( va.clone() );
  424. vertices.push( vb.clone() );
  425. vertices.push( vc.clone() );
  426. vertices.push( vd.clone() );
  427. face.a = n;
  428. face.b = n + 1;
  429. face.c = n + 2;
  430. face.d = n + 3;
  431. } else {
  432. var a = face.a;
  433. var b = face.b;
  434. var c = face.c;
  435. var va = geometry.vertices[ a ];
  436. var vb = geometry.vertices[ b ];
  437. var vc = geometry.vertices[ c ];
  438. vertices.push( va.clone() );
  439. vertices.push( vb.clone() );
  440. vertices.push( vc.clone() );
  441. face.a = n;
  442. face.b = n + 1;
  443. face.c = n + 2;
  444. }
  445. }
  446. geometry.vertices = vertices;
  447. delete geometry.__tmpVertices;
  448. },
  449. // Break faces with edges longer than maxEdgeLength
  450. // - not recursive
  451. tessellate: function ( geometry, maxEdgeLength ) {
  452. var i, il, face,
  453. a, b, c, d,
  454. va, vb, vc, vd,
  455. dab, dbc, dac, dcd, dad,
  456. m, m1, m2,
  457. vm, vm1, vm2,
  458. vnm, vnm1, vnm2,
  459. vcm, vcm1, vcm2,
  460. triA, triB,
  461. quadA, quadB,
  462. edge;
  463. var faces = [];
  464. var faceVertexUvs = [];
  465. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  466. faceVertexUvs[ i ] = [];
  467. }
  468. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  469. face = geometry.faces[ i ];
  470. if ( face instanceof THREE.Face3 ) {
  471. a = face.a;
  472. b = face.b;
  473. c = face.c;
  474. va = geometry.vertices[ a ];
  475. vb = geometry.vertices[ b ];
  476. vc = geometry.vertices[ c ];
  477. dab = va.distanceTo( vb );
  478. dbc = vb.distanceTo( vc );
  479. dac = va.distanceTo( vc );
  480. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  481. m = geometry.vertices.length;
  482. triA = face.clone();
  483. triB = face.clone();
  484. if ( dab >= dbc && dab >= dac ) {
  485. vm = va.clone();
  486. vm.lerpSelf( vb, 0.5 );
  487. triA.a = a;
  488. triA.b = m;
  489. triA.c = c;
  490. triB.a = m;
  491. triB.b = b;
  492. triB.c = c;
  493. if ( face.vertexNormals.length === 3 ) {
  494. vnm = face.vertexNormals[ 0 ].clone();
  495. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  496. triA.vertexNormals[ 1 ].copy( vnm );
  497. triB.vertexNormals[ 0 ].copy( vnm );
  498. }
  499. if ( face.vertexColors.length === 3 ) {
  500. vcm = face.vertexColors[ 0 ].clone();
  501. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  502. triA.vertexColors[ 1 ].copy( vcm );
  503. triB.vertexColors[ 0 ].copy( vcm );
  504. }
  505. edge = 0;
  506. } else if ( dbc >= dab && dbc >= dac ) {
  507. vm = vb.clone();
  508. vm.lerpSelf( vc, 0.5 );
  509. triA.a = a;
  510. triA.b = b;
  511. triA.c = m;
  512. triB.a = m;
  513. triB.b = c;
  514. triB.c = a;
  515. if ( face.vertexNormals.length === 3 ) {
  516. vnm = face.vertexNormals[ 1 ].clone();
  517. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  518. triA.vertexNormals[ 2 ].copy( vnm );
  519. triB.vertexNormals[ 0 ].copy( vnm );
  520. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  521. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  522. }
  523. if ( face.vertexColors.length === 3 ) {
  524. vcm = face.vertexColors[ 1 ].clone();
  525. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  526. triA.vertexColors[ 2 ].copy( vcm );
  527. triB.vertexColors[ 0 ].copy( vcm );
  528. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  529. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  530. }
  531. edge = 1;
  532. } else {
  533. vm = va.clone();
  534. vm.lerpSelf( vc, 0.5 );
  535. triA.a = a;
  536. triA.b = b;
  537. triA.c = m;
  538. triB.a = m;
  539. triB.b = b;
  540. triB.c = c;
  541. if ( face.vertexNormals.length === 3 ) {
  542. vnm = face.vertexNormals[ 0 ].clone();
  543. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  544. triA.vertexNormals[ 2 ].copy( vnm );
  545. triB.vertexNormals[ 0 ].copy( vnm );
  546. }
  547. if ( face.vertexColors.length === 3 ) {
  548. vcm = face.vertexColors[ 0 ].clone();
  549. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  550. triA.vertexColors[ 2 ].copy( vcm );
  551. triB.vertexColors[ 0 ].copy( vcm );
  552. }
  553. edge = 2;
  554. }
  555. faces.push( triA, triB );
  556. geometry.vertices.push( vm );
  557. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  558. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  559. if ( geometry.faceVertexUvs[ j ].length ) {
  560. uvs = geometry.faceVertexUvs[ j ][ i ];
  561. uvA = uvs[ 0 ];
  562. uvB = uvs[ 1 ];
  563. uvC = uvs[ 2 ];
  564. // AB
  565. if ( edge === 0 ) {
  566. uvM = uvA.clone();
  567. uvM.lerpSelf( uvB, 0.5 );
  568. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  569. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  570. // BC
  571. } else if ( edge === 1 ) {
  572. uvM = uvB.clone();
  573. uvM.lerpSelf( uvC, 0.5 );
  574. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  575. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  576. // AC
  577. } else {
  578. uvM = uvA.clone();
  579. uvM.lerpSelf( uvC, 0.5 );
  580. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  581. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  582. }
  583. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  584. }
  585. }
  586. } else {
  587. faces.push( face );
  588. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  589. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  590. }
  591. }
  592. } else {
  593. a = face.a;
  594. b = face.b;
  595. c = face.c;
  596. d = face.d;
  597. va = geometry.vertices[ a ];
  598. vb = geometry.vertices[ b ];
  599. vc = geometry.vertices[ c ];
  600. vd = geometry.vertices[ d ];
  601. dab = va.distanceTo( vb );
  602. dbc = vb.distanceTo( vc );
  603. dcd = vc.distanceTo( vd );
  604. dad = va.distanceTo( vd );
  605. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  606. m1 = geometry.vertices.length;
  607. m2 = geometry.vertices.length + 1;
  608. quadA = face.clone();
  609. quadB = face.clone();
  610. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  611. vm1 = va.clone();
  612. vm1.lerpSelf( vb, 0.5 );
  613. vm2 = vc.clone();
  614. vm2.lerpSelf( vd, 0.5 );
  615. quadA.a = a;
  616. quadA.b = m1;
  617. quadA.c = m2;
  618. quadA.d = d;
  619. quadB.a = m1;
  620. quadB.b = b;
  621. quadB.c = c;
  622. quadB.d = m2;
  623. if ( face.vertexNormals.length === 4 ) {
  624. vnm1 = face.vertexNormals[ 0 ].clone();
  625. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  626. vnm2 = face.vertexNormals[ 2 ].clone();
  627. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  628. quadA.vertexNormals[ 1 ].copy( vnm1 );
  629. quadA.vertexNormals[ 2 ].copy( vnm2 );
  630. quadB.vertexNormals[ 0 ].copy( vnm1 );
  631. quadB.vertexNormals[ 3 ].copy( vnm2 );
  632. }
  633. if ( face.vertexColors.length === 4 ) {
  634. vcm1 = face.vertexColors[ 0 ].clone();
  635. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  636. vcm2 = face.vertexColors[ 2 ].clone();
  637. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  638. quadA.vertexColors[ 1 ].copy( vcm1 );
  639. quadA.vertexColors[ 2 ].copy( vcm2 );
  640. quadB.vertexColors[ 0 ].copy( vcm1 );
  641. quadB.vertexColors[ 3 ].copy( vcm2 );
  642. }
  643. edge = 0;
  644. } else {
  645. vm1 = vb.clone();
  646. vm1.lerpSelf( vc, 0.5 );
  647. vm2 = vd.clone();
  648. vm2.lerpSelf( va, 0.5 );
  649. quadA.a = a;
  650. quadA.b = b;
  651. quadA.c = m1;
  652. quadA.d = m2;
  653. quadB.a = m2;
  654. quadB.b = m1;
  655. quadB.c = c;
  656. quadB.d = d;
  657. if ( face.vertexNormals.length === 4 ) {
  658. vnm1 = face.vertexNormals[ 1 ].clone();
  659. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  660. vnm2 = face.vertexNormals[ 3 ].clone();
  661. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  662. quadA.vertexNormals[ 2 ].copy( vnm1 );
  663. quadA.vertexNormals[ 3 ].copy( vnm2 );
  664. quadB.vertexNormals[ 0 ].copy( vnm2 );
  665. quadB.vertexNormals[ 1 ].copy( vnm1 );
  666. }
  667. if ( face.vertexColors.length === 4 ) {
  668. vcm1 = face.vertexColors[ 1 ].clone();
  669. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  670. vcm2 = face.vertexColors[ 3 ].clone();
  671. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  672. quadA.vertexColors[ 2 ].copy( vcm1 );
  673. quadA.vertexColors[ 3 ].copy( vcm2 );
  674. quadB.vertexColors[ 0 ].copy( vcm2 );
  675. quadB.vertexColors[ 1 ].copy( vcm1 );
  676. }
  677. edge = 1;
  678. }
  679. faces.push( quadA, quadB );
  680. geometry.vertices.push( vm1, vm2 );
  681. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  682. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  683. if ( geometry.faceVertexUvs[ j ].length ) {
  684. uvs = geometry.faceVertexUvs[ j ][ i ];
  685. uvA = uvs[ 0 ];
  686. uvB = uvs[ 1 ];
  687. uvC = uvs[ 2 ];
  688. uvD = uvs[ 3 ];
  689. // AB + CD
  690. if ( edge === 0 ) {
  691. uvM1 = uvA.clone();
  692. uvM1.lerpSelf( uvB, 0.5 );
  693. uvM2 = uvC.clone();
  694. uvM2.lerpSelf( uvD, 0.5 );
  695. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  696. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  697. // BC + AD
  698. } else {
  699. uvM1 = uvB.clone();
  700. uvM1.lerpSelf( uvC, 0.5 );
  701. uvM2 = uvD.clone();
  702. uvM2.lerpSelf( uvA, 0.5 );
  703. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  704. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  705. }
  706. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  707. }
  708. }
  709. } else {
  710. faces.push( face );
  711. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  712. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  713. }
  714. }
  715. }
  716. }
  717. geometry.faces = faces;
  718. geometry.faceVertexUvs = faceVertexUvs;
  719. }
  720. };
  721. THREE.GeometryUtils.random = THREE.Math.random16;
  722. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  723. /**
  724. * @author alteredq / http://alteredqualia.com/
  725. * @author mrdoob / http://mrdoob.com/
  726. */
  727. THREE.ImageUtils = {
  728. crossOrigin: 'anonymous',
  729. loadTexture: function ( url, mapping, onLoad, onError ) {
  730. var texture = new THREE.Texture( undefined, mapping );
  731. var loader = new THREE.ImageLoader();
  732. loader.addEventListener( 'load', function ( event ) {
  733. texture.image = event.content;
  734. texture.needsUpdate = true;
  735. if ( onLoad ) onLoad( texture );
  736. } );
  737. loader.addEventListener( 'error', function ( event ) {
  738. if ( onError ) onError( event.message );
  739. } );
  740. loader.crossOrigin = this.crossOrigin;
  741. loader.load( url );
  742. return texture;
  743. },
  744. loadTextureCube: function ( array, mapping, onLoad ) {
  745. var i, l, images = [];
  746. var texture = new THREE.Texture( images, mapping );
  747. texture.flipY = false;
  748. images.loadCount = 0;
  749. for ( i = 0, l = array.length; i < l; ++ i ) {
  750. images[ i ] = new Image();
  751. images[ i ].onload = function () {
  752. images.loadCount += 1;
  753. if ( images.loadCount === 6 ) {
  754. texture.needsUpdate = true;
  755. if ( onLoad ) onLoad();
  756. }
  757. };
  758. images[ i ].crossOrigin = this.crossOrigin;
  759. images[ i ].src = array[ i ];
  760. }
  761. return texture;
  762. },
  763. getNormalMap: function ( image, depth ) {
  764. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  765. var cross = function ( a, b ) {
  766. return [ a[ 1 ] * b[ 2 ] - a[ 2 ] * b[ 1 ], a[ 2 ] * b[ 0 ] - a[ 0 ] * b[ 2 ], a[ 0 ] * b[ 1 ] - a[ 1 ] * b[ 0 ] ];
  767. }
  768. var subtract = function ( a, b ) {
  769. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  770. }
  771. var normalize = function ( a ) {
  772. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  773. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  774. }
  775. depth = depth | 1;
  776. var width = image.width;
  777. var height = image.height;
  778. var canvas = document.createElement( 'canvas' );
  779. canvas.width = width;
  780. canvas.height = height;
  781. var context = canvas.getContext( '2d' );
  782. context.drawImage( image, 0, 0 );
  783. var data = context.getImageData( 0, 0, width, height ).data;
  784. var imageData = context.createImageData( width, height );
  785. var output = imageData.data;
  786. for ( var x = 0; x < width; x ++ ) {
  787. for ( var y = 0; y < height; y ++ ) {
  788. var ly = y - 1 < 0 ? 0 : y - 1;
  789. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  790. var lx = x - 1 < 0 ? 0 : x - 1;
  791. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  792. var points = [];
  793. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  794. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  795. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  796. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  797. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  798. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  799. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  800. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  801. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  802. var normals = [];
  803. var num_points = points.length;
  804. for ( var i = 0; i < num_points; i ++ ) {
  805. var v1 = points[ i ];
  806. var v2 = points[ ( i + 1 ) % num_points ];
  807. v1 = subtract( v1, origin );
  808. v2 = subtract( v2, origin );
  809. normals.push( normalize( cross( v1, v2 ) ) );
  810. }
  811. var normal = [ 0, 0, 0 ];
  812. for ( var i = 0; i < normals.length; i ++ ) {
  813. normal[ 0 ] += normals[ i ][ 0 ];
  814. normal[ 1 ] += normals[ i ][ 1 ];
  815. normal[ 2 ] += normals[ i ][ 2 ];
  816. }
  817. normal[ 0 ] /= normals.length;
  818. normal[ 1 ] /= normals.length;
  819. normal[ 2 ] /= normals.length;
  820. var idx = ( y * width + x ) * 4;
  821. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  822. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  823. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  824. output[ idx + 3 ] = 255;
  825. }
  826. }
  827. context.putImageData( imageData, 0, 0 );
  828. return canvas;
  829. },
  830. generateDataTexture: function ( width, height, color ) {
  831. var size = width * height;
  832. var data = new Uint8Array( 3 * size );
  833. var r = Math.floor( color.r * 255 );
  834. var g = Math.floor( color.g * 255 );
  835. var b = Math.floor( color.b * 255 );
  836. for ( var i = 0; i < size; i ++ ) {
  837. data[ i * 3 ] = r;
  838. data[ i * 3 + 1 ] = g;
  839. data[ i * 3 + 2 ] = b;
  840. }
  841. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  842. texture.needsUpdate = true;
  843. return texture;
  844. }
  845. };
  846. /**
  847. * @author alteredq / http://alteredqualia.com/
  848. */
  849. THREE.SceneUtils = {
  850. showHierarchy : function ( root, visible ) {
  851. THREE.SceneUtils.traverseHierarchy( root, function( node ) { node.visible = visible; } );
  852. },
  853. traverseHierarchy : function ( root, callback ) {
  854. var n, i, l = root.children.length;
  855. for ( i = 0; i < l; i ++ ) {
  856. n = root.children[ i ];
  857. callback( n );
  858. THREE.SceneUtils.traverseHierarchy( n, callback );
  859. }
  860. },
  861. createMultiMaterialObject : function ( geometry, materials ) {
  862. var i, il = materials.length,
  863. group = new THREE.Object3D();
  864. for ( i = 0; i < il; i ++ ) {
  865. var object = new THREE.Mesh( geometry, materials[ i ] );
  866. group.add( object );
  867. }
  868. return group;
  869. },
  870. cloneObject: function ( source ) {
  871. var object;
  872. // subclass specific properties
  873. // (must process in order from more specific subclasses to more abstract classes)
  874. if ( source instanceof THREE.MorphAnimMesh ) {
  875. object = new THREE.MorphAnimMesh( source.geometry, source.material );
  876. object.duration = source.duration;
  877. object.mirroredLoop = source.mirroredLoop;
  878. object.time = source.time;
  879. object.lastKeyframe = source.lastKeyframe;
  880. object.currentKeyframe = source.currentKeyframe;
  881. object.direction = source.direction;
  882. object.directionBackwards = source.directionBackwards;
  883. } else if ( source instanceof THREE.SkinnedMesh ) {
  884. object = new THREE.SkinnedMesh( source.geometry, source.material );
  885. } else if ( source instanceof THREE.Mesh ) {
  886. object = new THREE.Mesh( source.geometry, source.material );
  887. } else if ( source instanceof THREE.Line ) {
  888. object = new THREE.Line( source.geometry, source.material, source.type );
  889. } else if ( source instanceof THREE.Ribbon ) {
  890. object = new THREE.Ribbon( source.geometry, source.material );
  891. } else if ( source instanceof THREE.ParticleSystem ) {
  892. object = new THREE.ParticleSystem( source.geometry, source.material );
  893. object.sortParticles = source.sortParticles;
  894. } else if ( source instanceof THREE.Particle ) {
  895. object = new THREE.Particle( source.material );
  896. } else if ( source instanceof THREE.Sprite ) {
  897. object = new THREE.Sprite( {} );
  898. object.color.copy( source.color );
  899. object.map = source.map;
  900. object.blending = source.blending;
  901. object.useScreenCoordinates = source.useScreenCoordinates;
  902. object.mergeWith3D = source.mergeWith3D;
  903. object.affectedByDistance = source.affectedByDistance;
  904. object.scaleByViewport = source.scaleByViewport;
  905. object.alignment = source.alignment;
  906. object.rotation3d.copy( source.rotation3d );
  907. object.rotation = source.rotation;
  908. object.opacity = source.opacity;
  909. object.uvOffset.copy( source.uvOffset );
  910. object.uvScale.copy( source.uvScale);
  911. } else if ( source instanceof THREE.LOD ) {
  912. object = new THREE.LOD();
  913. /*
  914. } else if ( source instanceof THREE.MarchingCubes ) {
  915. object = new THREE.MarchingCubes( source.resolution, source.material );
  916. object.field.set( source.field );
  917. object.isolation = source.isolation;
  918. */
  919. } else if ( source instanceof THREE.Object3D ) {
  920. object = new THREE.Object3D();
  921. }
  922. // base class properties
  923. object.name = source.name;
  924. object.parent = source.parent;
  925. object.up.copy( source.up );
  926. object.position.copy( source.position );
  927. // because of Sprite madness
  928. if ( object.rotation instanceof THREE.Vector3 )
  929. object.rotation.copy( source.rotation );
  930. object.eulerOrder = source.eulerOrder;
  931. object.scale.copy( source.scale );
  932. object.dynamic = source.dynamic;
  933. object.doubleSided = source.doubleSided;
  934. object.flipSided = source.flipSided;
  935. object.renderDepth = source.renderDepth;
  936. object.rotationAutoUpdate = source.rotationAutoUpdate;
  937. object.matrix.copy( source.matrix );
  938. object.matrixWorld.copy( source.matrixWorld );
  939. object.matrixRotationWorld.copy( source.matrixRotationWorld );
  940. object.matrixAutoUpdate = source.matrixAutoUpdate;
  941. object.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  942. object.quaternion.copy( source.quaternion );
  943. object.useQuaternion = source.useQuaternion;
  944. object.boundRadius = source.boundRadius;
  945. object.boundRadiusScale = source.boundRadiusScale;
  946. object.visible = source.visible;
  947. object.castShadow = source.castShadow;
  948. object.receiveShadow = source.receiveShadow;
  949. object.frustumCulled = source.frustumCulled;
  950. // children
  951. for ( var i = 0; i < source.children.length; i ++ ) {
  952. var child = THREE.SceneUtils.cloneObject( source.children[ i ] );
  953. object.children[ i ] = child;
  954. child.parent = object;
  955. }
  956. // LODs need to be patched separately to use cloned children
  957. if ( source instanceof THREE.LOD ) {
  958. for ( var i = 0; i < source.LODs.length; i ++ ) {
  959. var lod = source.LODs[ i ];
  960. object.LODs[ i ] = { visibleAtDistance: lod.visibleAtDistance, object3D: object.children[ i ] };
  961. }
  962. }
  963. return object;
  964. },
  965. detach : function ( child, parent, scene ) {
  966. child.applyMatrix( parent.matrixWorld );
  967. parent.remove( child );
  968. scene.add( child );
  969. },
  970. attach: function ( child, scene, parent ) {
  971. var matrixWorldInverse = new THREE.Matrix4();
  972. matrixWorldInverse.getInverse( parent.matrixWorld );
  973. child.applyMatrix( matrixWorldInverse );
  974. scene.remove( child );
  975. parent.add( child );
  976. }
  977. };
  978. /**
  979. * @author alteredq / http://alteredqualia.com/
  980. * @author mr.doob / http://mrdoob.com/
  981. *
  982. * ShaderUtils currently contains:
  983. *
  984. * fresnel
  985. * normal
  986. * cube
  987. *
  988. */
  989. if ( THREE.WebGLRenderer ) {
  990. THREE.ShaderUtils = {
  991. lib: {
  992. /* -------------------------------------------------------------------------
  993. // Fresnel shader
  994. // - based on Nvidia Cg tutorial
  995. ------------------------------------------------------------------------- */
  996. 'fresnel': {
  997. uniforms: {
  998. "mRefractionRatio": { type: "f", value: 1.02 },
  999. "mFresnelBias": { type: "f", value: 0.1 },
  1000. "mFresnelPower": { type: "f", value: 2.0 },
  1001. "mFresnelScale": { type: "f", value: 1.0 },
  1002. "tCube": { type: "t", value: 1, texture: null }
  1003. },
  1004. fragmentShader: [
  1005. "uniform samplerCube tCube;",
  1006. "varying vec3 vReflect;",
  1007. "varying vec3 vRefract[3];",
  1008. "varying float vReflectionFactor;",
  1009. "void main() {",
  1010. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  1011. "vec4 refractedColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
  1012. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  1013. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  1014. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  1015. "refractedColor.a = 1.0;",
  1016. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  1017. "}"
  1018. ].join("\n"),
  1019. vertexShader: [
  1020. "uniform float mRefractionRatio;",
  1021. "uniform float mFresnelBias;",
  1022. "uniform float mFresnelScale;",
  1023. "uniform float mFresnelPower;",
  1024. "varying vec3 vReflect;",
  1025. "varying vec3 vRefract[3];",
  1026. "varying float vReflectionFactor;",
  1027. "void main() {",
  1028. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  1029. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  1030. "vec3 nWorld = normalize ( mat3( objectMatrix[0].xyz, objectMatrix[1].xyz, objectMatrix[2].xyz ) * normal );",
  1031. "vec3 I = mPosition.xyz - cameraPosition;",
  1032. "vReflect = reflect( I, nWorld );",
  1033. "vRefract[0] = refract( normalize( I ), nWorld, mRefractionRatio );",
  1034. "vRefract[1] = refract( normalize( I ), nWorld, mRefractionRatio * 0.99 );",
  1035. "vRefract[2] = refract( normalize( I ), nWorld, mRefractionRatio * 0.98 );",
  1036. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), nWorld ), mFresnelPower );",
  1037. "gl_Position = projectionMatrix * mvPosition;",
  1038. "}"
  1039. ].join("\n")
  1040. },
  1041. /* -------------------------------------------------------------------------
  1042. // Normal map shader
  1043. // - Blinn-Phong
  1044. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  1045. // - point and directional lights (use with "lights: true" material option)
  1046. ------------------------------------------------------------------------- */
  1047. 'normal' : {
  1048. uniforms: THREE.UniformsUtils.merge( [
  1049. THREE.UniformsLib[ "fog" ],
  1050. THREE.UniformsLib[ "lights" ],
  1051. THREE.UniformsLib[ "shadowmap" ],
  1052. {
  1053. "enableAO" : { type: "i", value: 0 },
  1054. "enableDiffuse" : { type: "i", value: 0 },
  1055. "enableSpecular" : { type: "i", value: 0 },
  1056. "enableReflection": { type: "i", value: 0 },
  1057. "tDiffuse" : { type: "t", value: 0, texture: null },
  1058. "tCube" : { type: "t", value: 1, texture: null },
  1059. "tNormal" : { type: "t", value: 2, texture: null },
  1060. "tSpecular" : { type: "t", value: 3, texture: null },
  1061. "tAO" : { type: "t", value: 4, texture: null },
  1062. "tDisplacement": { type: "t", value: 5, texture: null },
  1063. "uNormalScale": { type: "f", value: 1.0 },
  1064. "uDisplacementBias": { type: "f", value: 0.0 },
  1065. "uDisplacementScale": { type: "f", value: 1.0 },
  1066. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  1067. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  1068. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  1069. "uShininess": { type: "f", value: 30 },
  1070. "uOpacity": { type: "f", value: 1 },
  1071. "uReflectivity": { type: "f", value: 0.5 },
  1072. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  1073. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  1074. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  1075. }
  1076. ] ),
  1077. fragmentShader: [
  1078. "uniform vec3 uAmbientColor;",
  1079. "uniform vec3 uDiffuseColor;",
  1080. "uniform vec3 uSpecularColor;",
  1081. "uniform float uShininess;",
  1082. "uniform float uOpacity;",
  1083. "uniform bool enableDiffuse;",
  1084. "uniform bool enableSpecular;",
  1085. "uniform bool enableAO;",
  1086. "uniform bool enableReflection;",
  1087. "uniform sampler2D tDiffuse;",
  1088. "uniform sampler2D tNormal;",
  1089. "uniform sampler2D tSpecular;",
  1090. "uniform sampler2D tAO;",
  1091. "uniform samplerCube tCube;",
  1092. "uniform float uNormalScale;",
  1093. "uniform float uReflectivity;",
  1094. "varying vec3 vTangent;",
  1095. "varying vec3 vBinormal;",
  1096. "varying vec3 vNormal;",
  1097. "varying vec2 vUv;",
  1098. "uniform vec3 ambientLightColor;",
  1099. "#if MAX_DIR_LIGHTS > 0",
  1100. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  1101. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  1102. "#endif",
  1103. "#if MAX_POINT_LIGHTS > 0",
  1104. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  1105. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  1106. "#endif",
  1107. "#if MAX_SPOT_LIGHTS > 0",
  1108. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  1109. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  1110. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  1111. "uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
  1112. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  1113. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  1114. "varying vec3 vWorldPosition;",
  1115. "#endif",
  1116. "#ifdef WRAP_AROUND",
  1117. "uniform vec3 wrapRGB;",
  1118. "#endif",
  1119. "varying vec3 vViewPosition;",
  1120. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  1121. THREE.ShaderChunk[ "fog_pars_fragment" ],
  1122. "void main() {",
  1123. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  1124. "vec3 specularTex = vec3( 1.0 );",
  1125. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  1126. "normalTex.xy *= uNormalScale;",
  1127. "normalTex = normalize( normalTex );",
  1128. "if( enableDiffuse ) {",
  1129. "#ifdef GAMMA_INPUT",
  1130. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  1131. "texelColor.xyz *= texelColor.xyz;",
  1132. "gl_FragColor = gl_FragColor * texelColor;",
  1133. "#else",
  1134. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  1135. "#endif",
  1136. "}",
  1137. "if( enableAO ) {",
  1138. "#ifdef GAMMA_INPUT",
  1139. "vec4 aoColor = texture2D( tAO, vUv );",
  1140. "aoColor.xyz *= aoColor.xyz;",
  1141. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  1142. "#else",
  1143. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  1144. "#endif",
  1145. "}",
  1146. "if( enableSpecular )",
  1147. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  1148. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  1149. "vec3 finalNormal = tsb * normalTex;",
  1150. "vec3 normal = normalize( finalNormal );",
  1151. "vec3 viewPosition = normalize( vViewPosition );",
  1152. // point lights
  1153. "#if MAX_POINT_LIGHTS > 0",
  1154. "vec3 pointDiffuse = vec3( 0.0 );",
  1155. "vec3 pointSpecular = vec3( 0.0 );",
  1156. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  1157. "vec3 pointVector = normalize( vPointLight[ i ].xyz );",
  1158. "float pointDistance = vPointLight[ i ].w;",
  1159. // diffuse
  1160. "#ifdef WRAP_AROUND",
  1161. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  1162. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  1163. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  1164. "#else",
  1165. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  1166. "#endif",
  1167. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  1168. // specular
  1169. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  1170. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  1171. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  1172. "#ifdef PHYSICALLY_BASED_SHADING",
  1173. // 2.0 => 2.0001 is hack to work around ANGLE bug
  1174. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  1175. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  1176. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  1177. "#else",
  1178. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  1179. "#endif",
  1180. "}",
  1181. "#endif",
  1182. // spot lights
  1183. "#if MAX_SPOT_LIGHTS > 0",
  1184. "vec3 spotDiffuse = vec3( 0.0 );",
  1185. "vec3 spotSpecular = vec3( 0.0 );",
  1186. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  1187. "vec3 spotVector = normalize( vSpotLight[ i ].xyz );",
  1188. "float spotDistance = vSpotLight[ i ].w;",
  1189. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  1190. "if ( spotEffect > spotLightAngle[ i ] ) {",
  1191. "spotEffect = pow( spotEffect, spotLightExponent[ i ] );",
  1192. // diffuse
  1193. "#ifdef WRAP_AROUND",
  1194. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  1195. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  1196. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  1197. "#else",
  1198. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  1199. "#endif",
  1200. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  1201. // specular
  1202. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  1203. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  1204. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  1205. "#ifdef PHYSICALLY_BASED_SHADING",
  1206. // 2.0 => 2.0001 is hack to work around ANGLE bug
  1207. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  1208. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  1209. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  1210. "#else",
  1211. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  1212. "#endif",
  1213. "}",
  1214. "}",
  1215. "#endif",
  1216. // directional lights
  1217. "#if MAX_DIR_LIGHTS > 0",
  1218. "vec3 dirDiffuse = vec3( 0.0 );",
  1219. "vec3 dirSpecular = vec3( 0.0 );",
  1220. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  1221. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  1222. "vec3 dirVector = normalize( lDirection.xyz );",
  1223. // diffuse
  1224. "#ifdef WRAP_AROUND",
  1225. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  1226. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  1227. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  1228. "#else",
  1229. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  1230. "#endif",
  1231. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  1232. // specular
  1233. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  1234. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  1235. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  1236. "#ifdef PHYSICALLY_BASED_SHADING",
  1237. // 2.0 => 2.0001 is hack to work around ANGLE bug
  1238. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  1239. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  1240. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  1241. "#else",
  1242. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  1243. "#endif",
  1244. "}",
  1245. "#endif",
  1246. // all lights contribution summation
  1247. "vec3 totalDiffuse = vec3( 0.0 );",
  1248. "vec3 totalSpecular = vec3( 0.0 );",
  1249. "#if MAX_DIR_LIGHTS > 0",
  1250. "totalDiffuse += dirDiffuse;",
  1251. "totalSpecular += dirSpecular;",
  1252. "#endif",
  1253. "#if MAX_POINT_LIGHTS > 0",
  1254. "totalDiffuse += pointDiffuse;",
  1255. "totalSpecular += pointSpecular;",
  1256. "#endif",
  1257. "#if MAX_SPOT_LIGHTS > 0",
  1258. "totalDiffuse += spotDiffuse;",
  1259. "totalSpecular += spotSpecular;",
  1260. "#endif",
  1261. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor) + totalSpecular;",
  1262. "if ( enableReflection ) {",
  1263. "vec3 wPos = cameraPosition - vViewPosition;",
  1264. "vec3 vReflect = reflect( normalize( wPos ), normal );",
  1265. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  1266. "#ifdef GAMMA_INPUT",
  1267. "cubeColor.xyz *= cubeColor.xyz;",
  1268. "#endif",
  1269. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  1270. "}",
  1271. THREE.ShaderChunk[ "shadowmap_fragment" ],
  1272. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  1273. THREE.ShaderChunk[ "fog_fragment" ],
  1274. "}"
  1275. ].join("\n"),
  1276. vertexShader: [
  1277. "attribute vec4 tangent;",
  1278. "uniform vec2 uOffset;",
  1279. "uniform vec2 uRepeat;",
  1280. "#ifdef VERTEX_TEXTURES",
  1281. "uniform sampler2D tDisplacement;",
  1282. "uniform float uDisplacementScale;",
  1283. "uniform float uDisplacementBias;",
  1284. "#endif",
  1285. "varying vec3 vTangent;",
  1286. "varying vec3 vBinormal;",
  1287. "varying vec3 vNormal;",
  1288. "varying vec2 vUv;",
  1289. "#if MAX_POINT_LIGHTS > 0",
  1290. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  1291. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  1292. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  1293. "#endif",
  1294. "#if MAX_SPOT_LIGHTS > 0",
  1295. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  1296. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  1297. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  1298. "varying vec3 vWorldPosition;",
  1299. "#endif",
  1300. "varying vec3 vViewPosition;",
  1301. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  1302. "void main() {",
  1303. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  1304. "vViewPosition = -mvPosition.xyz;",
  1305. // normal, tangent and binormal vectors
  1306. "vNormal = normalMatrix * normal;",
  1307. "vTangent = normalMatrix * tangent.xyz;",
  1308. "vBinormal = cross( vNormal, vTangent ) * tangent.w;",
  1309. "vUv = uv * uRepeat + uOffset;",
  1310. // point lights
  1311. "#if MAX_POINT_LIGHTS > 0",
  1312. "for( int i = 0; i < MAX_POINT_LIGHTS; i++ ) {",
  1313. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  1314. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  1315. "float lDistance = 1.0;",
  1316. "if ( pointLightDistance[ i ] > 0.0 )",
  1317. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  1318. "lVector = normalize( lVector );",
  1319. "vPointLight[ i ] = vec4( lVector, lDistance );",
  1320. "}",
  1321. "#endif",
  1322. // spot lights
  1323. "#if MAX_SPOT_LIGHTS > 0",
  1324. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  1325. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  1326. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  1327. "float lDistance = 1.0;",
  1328. "if ( spotLightDistance[ i ] > 0.0 )",
  1329. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  1330. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  1331. "}",
  1332. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  1333. "vWorldPosition = mPosition.xyz;",
  1334. "#endif",
  1335. // displacement mapping
  1336. "#ifdef VERTEX_TEXTURES",
  1337. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  1338. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  1339. "vec4 displacedPosition = vec4( normalize( vNormal.xyz ) * df, 0.0 ) + mvPosition;",
  1340. "gl_Position = projectionMatrix * displacedPosition;",
  1341. "#else",
  1342. "gl_Position = projectionMatrix * mvPosition;",
  1343. "#endif",
  1344. THREE.ShaderChunk[ "shadowmap_vertex" ],
  1345. "}"
  1346. ].join("\n")
  1347. },
  1348. /* -------------------------------------------------------------------------
  1349. // Cube map shader
  1350. ------------------------------------------------------------------------- */
  1351. 'cube': {
  1352. uniforms: { "tCube": { type: "t", value: 1, texture: null },
  1353. "tFlip": { type: "f", value: -1 } },
  1354. vertexShader: [
  1355. "varying vec3 vViewPosition;",
  1356. "void main() {",
  1357. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  1358. "vViewPosition = cameraPosition - mPosition.xyz;",
  1359. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  1360. "}"
  1361. ].join("\n"),
  1362. fragmentShader: [
  1363. "uniform samplerCube tCube;",
  1364. "uniform float tFlip;",
  1365. "varying vec3 vViewPosition;",
  1366. "void main() {",
  1367. "vec3 wPos = cameraPosition - vViewPosition;",
  1368. "gl_FragColor = textureCube( tCube, vec3( tFlip * wPos.x, wPos.yz ) );",
  1369. "}"
  1370. ].join("\n")
  1371. }
  1372. }
  1373. };
  1374. };/**
  1375. * @author zz85 / http://www.lab4games.net/zz85/blog
  1376. * @author alteredq / http://alteredqualia.com/
  1377. *
  1378. * For Text operations in three.js (See TextGeometry)
  1379. *
  1380. * It uses techniques used in:
  1381. *
  1382. * typeface.js and canvastext
  1383. * For converting fonts and rendering with javascript
  1384. * http://typeface.neocracy.org
  1385. *
  1386. * Triangulation ported from AS3
  1387. * Simple Polygon Triangulation
  1388. * http://actionsnippet.com/?p=1462
  1389. *
  1390. * A Method to triangulate shapes with holes
  1391. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  1392. *
  1393. */
  1394. THREE.FontUtils = {
  1395. faces : {},
  1396. // Just for now. face[weight][style]
  1397. face : "helvetiker",
  1398. weight: "normal",
  1399. style : "normal",
  1400. size : 150,
  1401. divisions : 10,
  1402. getFace : function() {
  1403. return this.faces[ this.face ][ this.weight ][ this.style ];
  1404. },
  1405. loadFace : function( data ) {
  1406. var family = data.familyName.toLowerCase();
  1407. var ThreeFont = this;
  1408. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  1409. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  1410. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  1411. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  1412. return data;
  1413. },
  1414. drawText : function( text ) {
  1415. var characterPts = [], allPts = [];
  1416. // RenderText
  1417. var i, p,
  1418. face = this.getFace(),
  1419. scale = this.size / face.resolution,
  1420. offset = 0,
  1421. chars = String( text ).split( '' ),
  1422. length = chars.length;
  1423. var fontPaths = [];
  1424. for ( i = 0; i < length; i ++ ) {
  1425. var path = new THREE.Path();
  1426. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  1427. offset += ret.offset;
  1428. fontPaths.push( ret.path );
  1429. }
  1430. // get the width
  1431. var width = offset / 2;
  1432. //
  1433. // for ( p = 0; p < allPts.length; p++ ) {
  1434. //
  1435. // allPts[ p ].x -= width;
  1436. //
  1437. // }
  1438. //var extract = this.extractPoints( allPts, characterPts );
  1439. //extract.contour = allPts;
  1440. //extract.paths = fontPaths;
  1441. //extract.offset = width;
  1442. return { paths : fontPaths, offset : width };
  1443. },
  1444. extractGlyphPoints : function( c, face, scale, offset, path ) {
  1445. var pts = [];
  1446. var i, i2, divisions,
  1447. outline, action, length,
  1448. scaleX, scaleY,
  1449. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  1450. laste,
  1451. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  1452. if ( !glyph ) return;
  1453. if ( glyph.o ) {
  1454. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  1455. length = outline.length;
  1456. scaleX = scale;
  1457. scaleY = scale;
  1458. for ( i = 0; i < length; ) {
  1459. action = outline[ i ++ ];
  1460. //console.log( action );
  1461. switch( action ) {
  1462. case 'm':
  1463. // Move To
  1464. x = outline[ i++ ] * scaleX + offset;
  1465. y = outline[ i++ ] * scaleY;
  1466. path.moveTo( x, y );
  1467. break;
  1468. case 'l':
  1469. // Line To
  1470. x = outline[ i++ ] * scaleX + offset;
  1471. y = outline[ i++ ] * scaleY;
  1472. path.lineTo(x,y);
  1473. break;
  1474. case 'q':
  1475. // QuadraticCurveTo
  1476. cpx = outline[ i++ ] * scaleX + offset;
  1477. cpy = outline[ i++ ] * scaleY;
  1478. cpx1 = outline[ i++ ] * scaleX + offset;
  1479. cpy1 = outline[ i++ ] * scaleY;
  1480. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  1481. laste = pts[ pts.length - 1 ];
  1482. if ( laste ) {
  1483. cpx0 = laste.x;
  1484. cpy0 = laste.y;
  1485. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  1486. var t = i2 / divisions;
  1487. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  1488. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  1489. }
  1490. }
  1491. break;
  1492. case 'b':
  1493. // Cubic Bezier Curve
  1494. cpx = outline[ i++ ] * scaleX + offset;
  1495. cpy = outline[ i++ ] * scaleY;
  1496. cpx1 = outline[ i++ ] * scaleX + offset;
  1497. cpy1 = outline[ i++ ] * -scaleY;
  1498. cpx2 = outline[ i++ ] * scaleX + offset;
  1499. cpy2 = outline[ i++ ] * -scaleY;
  1500. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  1501. laste = pts[ pts.length - 1 ];
  1502. if ( laste ) {
  1503. cpx0 = laste.x;
  1504. cpy0 = laste.y;
  1505. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  1506. var t = i2 / divisions;
  1507. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  1508. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  1509. }
  1510. }
  1511. break;
  1512. }
  1513. }
  1514. }
  1515. return { offset: glyph.ha*scale, path:path};
  1516. }
  1517. };
  1518. THREE.FontUtils.generateShapes = function( text, parameters ) {
  1519. // Parameters
  1520. parameters = parameters || {};
  1521. var size = parameters.size !== undefined ? parameters.size : 100;
  1522. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  1523. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  1524. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  1525. var style = parameters.style !== undefined ? parameters.style : "normal";
  1526. THREE.FontUtils.size = size;
  1527. THREE.FontUtils.divisions = curveSegments;
  1528. THREE.FontUtils.face = font;
  1529. THREE.FontUtils.weight = weight;
  1530. THREE.FontUtils.style = style;
  1531. // Get a Font data json object
  1532. var data = THREE.FontUtils.drawText( text );
  1533. var paths = data.paths;
  1534. var shapes = [];
  1535. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  1536. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  1537. }
  1538. return shapes;
  1539. };
  1540. /**
  1541. * This code is a quick port of code written in C++ which was submitted to
  1542. * flipcode.com by John W. Ratcliff // July 22, 2000
  1543. * See original code and more information here:
  1544. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  1545. *
  1546. * ported to actionscript by Zevan Rosser
  1547. * www.actionsnippet.com
  1548. *
  1549. * ported to javascript by Joshua Koo
  1550. * http://www.lab4games.net/zz85/blog
  1551. *
  1552. */
  1553. ( function( namespace ) {
  1554. var EPSILON = 0.0000000001;
  1555. // takes in an contour array and returns
  1556. var process = function( contour, indices ) {
  1557. var n = contour.length;
  1558. if ( n < 3 ) return null;
  1559. var result = [],
  1560. verts = [],
  1561. vertIndices = [];
  1562. /* we want a counter-clockwise polygon in verts */
  1563. var u, v, w;
  1564. if ( area( contour ) > 0.0 ) {
  1565. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  1566. } else {
  1567. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  1568. }
  1569. var nv = n;
  1570. /* remove nv - 2 vertices, creating 1 triangle every time */
  1571. var count = 2 * nv; /* error detection */
  1572. for( v = nv - 1; nv > 2; ) {
  1573. /* if we loop, it is probably a non-simple polygon */
  1574. if ( ( count-- ) <= 0 ) {
  1575. //** Triangulate: ERROR - probable bad polygon!
  1576. //throw ( "Warning, unable to triangulate polygon!" );
  1577. //return null;
  1578. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  1579. console.log( "Warning, unable to triangulate polygon!" );
  1580. if ( indices ) return vertIndices;
  1581. return result;
  1582. }
  1583. /* three consecutive vertices in current polygon, <u,v,w> */
  1584. u = v; if ( nv <= u ) u = 0; /* previous */
  1585. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  1586. w = v + 1; if ( nv <= w ) w = 0; /* next */
  1587. if ( snip( contour, u, v, w, nv, verts ) ) {
  1588. var a, b, c, s, t;
  1589. /* true names of the vertices */
  1590. a = verts[ u ];
  1591. b = verts[ v ];
  1592. c = verts[ w ];
  1593. /* output Triangle */
  1594. /*
  1595. result.push( contour[ a ] );
  1596. result.push( contour[ b ] );
  1597. result.push( contour[ c ] );
  1598. */
  1599. result.push( [ contour[ a ],
  1600. contour[ b ],
  1601. contour[ c ] ] );
  1602. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  1603. /* remove v from the remaining polygon */
  1604. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  1605. verts[ s ] = verts[ t ];
  1606. }
  1607. nv--;
  1608. /* reset error detection counter */
  1609. count = 2 * nv;
  1610. }
  1611. }
  1612. if ( indices ) return vertIndices;
  1613. return result;
  1614. };
  1615. // calculate area of the contour polygon
  1616. var area = function ( contour ) {
  1617. var n = contour.length;
  1618. var a = 0.0;
  1619. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  1620. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  1621. }
  1622. return a * 0.5;
  1623. };
  1624. // see if p is inside triangle abc
  1625. var insideTriangle = function( ax, ay,
  1626. bx, by,
  1627. cx, cy,
  1628. px, py ) {
  1629. var aX, aY, bX, bY;
  1630. var cX, cY, apx, apy;
  1631. var bpx, bpy, cpx, cpy;
  1632. var cCROSSap, bCROSScp, aCROSSbp;
  1633. aX = cx - bx; aY = cy - by;
  1634. bX = ax - cx; bY = ay - cy;
  1635. cX = bx - ax; cY = by - ay;
  1636. apx= px -ax; apy= py - ay;
  1637. bpx= px - bx; bpy= py - by;
  1638. cpx= px - cx; cpy= py - cy;
  1639. aCROSSbp = aX*bpy - aY*bpx;
  1640. cCROSSap = cX*apy - cY*apx;
  1641. bCROSScp = bX*cpy - bY*cpx;
  1642. return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
  1643. };
  1644. var snip = function ( contour, u, v, w, n, verts ) {
  1645. var p;
  1646. var ax, ay, bx, by;
  1647. var cx, cy, px, py;
  1648. ax = contour[ verts[ u ] ].x;
  1649. ay = contour[ verts[ u ] ].y;
  1650. bx = contour[ verts[ v ] ].x;
  1651. by = contour[ verts[ v ] ].y;
  1652. cx = contour[ verts[ w ] ].x;
  1653. cy = contour[ verts[ w ] ].y;
  1654. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  1655. for ( p = 0; p < n; p++ ) {
  1656. if( (p == u) || (p == v) || (p == w) ) continue;
  1657. px = contour[ verts[ p ] ].x
  1658. py = contour[ verts[ p ] ].y
  1659. if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;
  1660. }
  1661. return true;
  1662. };
  1663. namespace.Triangulate = process;
  1664. namespace.Triangulate.area = area;
  1665. return namespace;
  1666. })(THREE.FontUtils);
  1667. // To use the typeface.js face files, hook up the API
  1668. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  1669. * @author alteredq / http://alteredqualia.com/
  1670. */
  1671. THREE.BufferGeometry = function () {
  1672. this.id = THREE.GeometryCount ++;
  1673. // attributes
  1674. this.attributes = {};
  1675. // attributes typed arrays are kept only if dynamic flag is set
  1676. this.dynamic = false;
  1677. // boundings
  1678. this.boundingBox = null;
  1679. this.boundingSphere = null;
  1680. this.hasTangents = false;
  1681. // for compatibility
  1682. this.morphTargets = [];
  1683. };
  1684. THREE.BufferGeometry.prototype = {
  1685. constructor : THREE.BufferGeometry,
  1686. applyMatrix: function ( matrix ) {
  1687. var positionArray;
  1688. var normalArray;
  1689. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  1690. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  1691. if ( positionArray !== undefined ) {
  1692. matrix.multiplyVector3Array( positionArray );
  1693. this.verticesNeedUpdate = true;
  1694. }
  1695. if ( normalArray !== undefined ) {
  1696. var matrixRotation = new THREE.Matrix4();
  1697. matrixRotation.extractRotation( matrix );
  1698. matrixRotation.multiplyVector3Array( normalArray );
  1699. this.normalsNeedUpdate = true;
  1700. }
  1701. },
  1702. computeBoundingBox: function () {
  1703. if ( ! this.boundingBox ) {
  1704. this.boundingBox = {
  1705. min: new THREE.Vector3( Infinity, Infinity, Infinity ),
  1706. max: new THREE.Vector3( -Infinity, -Infinity, -Infinity )
  1707. };
  1708. }
  1709. var positions = this.attributes[ "position" ].array;
  1710. if ( positions ) {
  1711. var bb = this.boundingBox;
  1712. var x, y, z;
  1713. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  1714. x = positions[ i ];
  1715. y = positions[ i + 1 ];
  1716. z = positions[ i + 2 ];
  1717. // bounding box
  1718. if ( x < bb.min.x ) {
  1719. bb.min.x = x;
  1720. } else if ( x > bb.max.x ) {
  1721. bb.max.x = x;
  1722. }
  1723. if ( y < bb.min.y ) {
  1724. bb.min.y = y;
  1725. } else if ( y > bb.max.y ) {
  1726. bb.max.y = y;
  1727. }
  1728. if ( z < bb.min.z ) {
  1729. bb.min.z = z;
  1730. } else if ( z > bb.max.z ) {
  1731. bb.max.z = z;
  1732. }
  1733. }
  1734. }
  1735. if ( positions === undefined || positions.length === 0 ) {
  1736. this.boundingBox.min.set( 0, 0, 0 );
  1737. this.boundingBox.max.set( 0, 0, 0 );
  1738. }
  1739. },
  1740. computeBoundingSphere: function () {
  1741. if ( ! this.boundingSphere ) this.boundingSphere = { radius: 0 };
  1742. var positions = this.attributes[ "position" ].array;
  1743. if ( positions ) {
  1744. var radius, maxRadius = 0;
  1745. var x, y, z;
  1746. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  1747. x = positions[ i ];
  1748. y = positions[ i + 1 ];
  1749. z = positions[ i + 2 ];
  1750. radius = Math.sqrt( x * x + y * y + z * z );
  1751. if ( radius > maxRadius ) maxRadius = radius;
  1752. }
  1753. this.boundingSphere.radius = maxRadius;
  1754. }
  1755. },
  1756. computeVertexNormals: function () {
  1757. if ( this.attributes[ "position" ] && this.attributes[ "index" ] ) {
  1758. var i, il;
  1759. var j, jl;
  1760. var nVertexElements = this.attributes[ "position" ].array.length;
  1761. if ( this.attributes[ "normal" ] === undefined ) {
  1762. this.attributes[ "normal" ] = {
  1763. itemSize: 3,
  1764. array: new Float32Array( nVertexElements ),
  1765. numItems: nVertexElements
  1766. };
  1767. } else {
  1768. // reset existing normals to zero
  1769. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  1770. this.attributes[ "normal" ].array[ i ] = 0;
  1771. }
  1772. }
  1773. var offsets = this.offsets;
  1774. var indices = this.attributes[ "index" ].array;
  1775. var positions = this.attributes[ "position" ].array;
  1776. var normals = this.attributes[ "normal" ].array;
  1777. var vA, vB, vC, x, y, z,
  1778. pA = new THREE.Vector3(),
  1779. pB = new THREE.Vector3(),
  1780. pC = new THREE.Vector3(),
  1781. cb = new THREE.Vector3(),
  1782. ab = new THREE.Vector3();
  1783. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  1784. var start = offsets[ j ].start;
  1785. var count = offsets[ j ].count;
  1786. var index = offsets[ j ].index;
  1787. for ( i = start, il = start + count; i < il; i += 3 ) {
  1788. vA = index + indices[ i ];
  1789. vB = index + indices[ i + 1 ];
  1790. vC = index + indices[ i + 2 ];
  1791. x = positions[ vA * 3 ];
  1792. y = positions[ vA * 3 + 1 ];
  1793. z = positions[ vA * 3 + 2 ];
  1794. pA.set( x, y, z );
  1795. x = positions[ vB * 3 ];
  1796. y = positions[ vB * 3 + 1 ];
  1797. z = positions[ vB * 3 + 2 ];
  1798. pB.set( x, y, z );
  1799. x = positions[ vC * 3 ];
  1800. y = positions[ vC * 3 + 1 ];
  1801. z = positions[ vC * 3 + 2 ];
  1802. pC.set( x, y, z );
  1803. cb.sub( pC, pB );
  1804. ab.sub( pA, pB );
  1805. cb.crossSelf( ab );
  1806. normals[ vA * 3 ] += cb.x;
  1807. normals[ vA * 3 + 1 ] += cb.y;
  1808. normals[ vA * 3 + 2 ] += cb.z;
  1809. normals[ vB * 3 ] += cb.x;
  1810. normals[ vB * 3 + 1 ] += cb.y;
  1811. normals[ vB * 3 + 2 ] += cb.z;
  1812. normals[ vC * 3 ] += cb.x;
  1813. normals[ vC * 3 + 1 ] += cb.y;
  1814. normals[ vC * 3 + 2 ] += cb.z;
  1815. }
  1816. }
  1817. // normalize normals
  1818. for ( i = 0, il = normals.length; i < il; i += 3 ) {
  1819. x = normals[ i ];
  1820. y = normals[ i + 1 ];
  1821. z = normals[ i + 2 ];
  1822. var n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  1823. normals[ i ] *= n;
  1824. normals[ i + 1 ] *= n;
  1825. normals[ i + 2 ] *= n;
  1826. }
  1827. this.normalsNeedUpdate = true;
  1828. }
  1829. },
  1830. computeTangents: function () {
  1831. // based on http://www.terathon.com/code/tangent.html
  1832. // (per vertex tangents)
  1833. if ( this.attributes[ "index" ] === undefined ||
  1834. this.attributes[ "position" ] === undefined ||
  1835. this.attributes[ "normal" ] === undefined ||
  1836. this.attributes[ "uv" ] === undefined ) {
  1837. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  1838. return;
  1839. }
  1840. var indices = this.attributes[ "index" ].array;
  1841. var positions = this.attributes[ "position" ].array;
  1842. var normals = this.attributes[ "normal" ].array;
  1843. var uvs = this.attributes[ "uv" ].array;
  1844. var nVertices = positions.length / 3;
  1845. if ( this.attributes[ "tangent" ] === undefined ) {
  1846. var nTangentElements = 4 * nVertices;
  1847. this.attributes[ "tangent" ] = {
  1848. itemSize: 4,
  1849. array: new Float32Array( nTangentElements ),
  1850. numItems: nTangentElements
  1851. };
  1852. }
  1853. var tangents = this.attributes[ "tangent" ].array;
  1854. var tan1 = [], tan2 = [];
  1855. for ( var k = 0; k < nVertices; k ++ ) {
  1856. tan1[ k ] = new THREE.Vector3();
  1857. tan2[ k ] = new THREE.Vector3();
  1858. }
  1859. var xA, yA, zA,
  1860. xB, yB, zB,
  1861. xC, yC, zC,
  1862. uA, vA,
  1863. uB, vB,
  1864. uC, vC,
  1865. x1, x2, y1, y2, z1, z2,
  1866. s1, s2, t1, t2, r;
  1867. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  1868. function handleTriangle( a, b, c ) {
  1869. xA = positions[ a * 3 ];
  1870. yA = positions[ a * 3 + 1 ];
  1871. zA = positions[ a * 3 + 2 ];
  1872. xB = positions[ b * 3 ];
  1873. yB = positions[ b * 3 + 1 ];
  1874. zB = positions[ b * 3 + 2 ];
  1875. xC = positions[ c * 3 ];
  1876. yC = positions[ c * 3 + 1 ];
  1877. zC = positions[ c * 3 + 2 ];
  1878. uA = uvs[ a * 2 ];
  1879. vA = uvs[ a * 2 + 1 ];
  1880. uB = uvs[ b * 2 ];
  1881. vB = uvs[ b * 2 + 1 ];
  1882. uC = uvs[ c * 2 ];
  1883. vC = uvs[ c * 2 + 1 ];
  1884. x1 = xB - xA;
  1885. x2 = xC - xA;
  1886. y1 = yB - yA;
  1887. y2 = yC - yA;
  1888. z1 = zB - zA;
  1889. z2 = zC - zA;
  1890. s1 = uB - uA;
  1891. s2 = uC - uA;
  1892. t1 = vB - vA;
  1893. t2 = vC - vA;
  1894. r = 1.0 / ( s1 * t2 - s2 * t1 );
  1895. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  1896. ( t2 * y1 - t1 * y2 ) * r,
  1897. ( t2 * z1 - t1 * z2 ) * r );
  1898. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  1899. ( s1 * y2 - s2 * y1 ) * r,
  1900. ( s1 * z2 - s2 * z1 ) * r );
  1901. tan1[ a ].addSelf( sdir );
  1902. tan1[ b ].addSelf( sdir );
  1903. tan1[ c ].addSelf( sdir );
  1904. tan2[ a ].addSelf( tdir );
  1905. tan2[ b ].addSelf( tdir );
  1906. tan2[ c ].addSelf( tdir );
  1907. }
  1908. var i, il;
  1909. var j, jl;
  1910. var iA, iB, iC;
  1911. var offsets = this.offsets;
  1912. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  1913. var start = offsets[ j ].start;
  1914. var count = offsets[ j ].count;
  1915. var index = offsets[ j ].index;
  1916. for ( i = start, il = start + count; i < il; i += 3 ) {
  1917. iA = index + indices[ i ];
  1918. iB = index + indices[ i + 1 ];
  1919. iC = index + indices[ i + 2 ];
  1920. handleTriangle( iA, iB, iC );
  1921. }
  1922. }
  1923. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  1924. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  1925. var w, t, test;
  1926. var nx, ny, nz;
  1927. function handleVertex( v ) {
  1928. n.x = normals[ v * 3 ];
  1929. n.y = normals[ v * 3 + 1 ];
  1930. n.z = normals[ v * 3 + 2 ];
  1931. n2.copy( n );
  1932. t = tan1[ v ];
  1933. // Gram-Schmidt orthogonalize
  1934. tmp.copy( t );
  1935. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  1936. // Calculate handedness
  1937. tmp2.cross( n2, t );
  1938. test = tmp2.dot( tan2[ v ] );
  1939. w = ( test < 0.0 ) ? -1.0 : 1.0;
  1940. tangents[ v * 4 ] = tmp.x;
  1941. tangents[ v * 4 + 1 ] = tmp.y;
  1942. tangents[ v * 4 + 2 ] = tmp.z;
  1943. tangents[ v * 4 + 3 ] = w;
  1944. }
  1945. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  1946. var start = offsets[ j ].start;
  1947. var count = offsets[ j ].count;
  1948. var index = offsets[ j ].index;
  1949. for ( i = start, il = start + count; i < il; i += 3 ) {
  1950. iA = index + indices[ i ];
  1951. iB = index + indices[ i + 1 ];
  1952. iC = index + indices[ i + 2 ];
  1953. handleVertex( iA );
  1954. handleVertex( iB );
  1955. handleVertex( iC );
  1956. }
  1957. }
  1958. this.hasTangents = true;
  1959. this.tangentsNeedUpdate = true;
  1960. }
  1961. };
  1962. /**
  1963. * @author zz85 / http://www.lab4games.net/zz85/blog
  1964. * Extensible curve object
  1965. *
  1966. * Some common of Curve methods
  1967. * .getPoint(t), getTangent(t)
  1968. * .getPointAt(u), getTagentAt(u)
  1969. * .getPoints(), .getSpacedPoints()
  1970. * .getLength()
  1971. * .updateArcLengths()
  1972. *
  1973. * This file contains following classes:
  1974. *
  1975. * -- 2d classes --
  1976. * THREE.Curve
  1977. * THREE.LineCurve
  1978. * THREE.QuadraticBezierCurve
  1979. * THREE.CubicBezierCurve
  1980. * THREE.SplineCurve
  1981. * THREE.ArcCurve
  1982. *
  1983. * -- 3d classes --
  1984. * THREE.LineCurve3
  1985. * THREE.QuadraticBezierCurve3
  1986. * THREE.CubicBezierCurve3
  1987. * THREE.SplineCurve3
  1988. * THREE.ClosedSplineCurve3
  1989. *
  1990. * A series of curves can be represented as a THREE.CurvePath
  1991. *
  1992. **/
  1993. /**************************************************************
  1994. * Abstract Curve base class
  1995. **************************************************************/
  1996. THREE.Curve = function () {
  1997. };
  1998. // Virtual base class method to overwrite and implement in subclasses
  1999. // - t [0 .. 1]
  2000. THREE.Curve.prototype.getPoint = function ( t ) {
  2001. console.log( "Warning, getPoint() not implemented!" );
  2002. return null;
  2003. };
  2004. // Get point at relative position in curve according to arc length
  2005. // - u [0 .. 1]
  2006. THREE.Curve.prototype.getPointAt = function ( u ) {
  2007. var t = this.getUtoTmapping( u );
  2008. return this.getPoint( t );
  2009. };
  2010. // Get sequence of points using getPoint( t )
  2011. THREE.Curve.prototype.getPoints = function ( divisions ) {
  2012. if ( !divisions ) divisions = 5;
  2013. var d, pts = [];
  2014. for ( d = 0; d <= divisions; d ++ ) {
  2015. pts.push( this.getPoint( d / divisions ) );
  2016. }
  2017. return pts;
  2018. };
  2019. // Get sequence of points using getPointAt( u )
  2020. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  2021. if ( !divisions ) divisions = 5;
  2022. var d, pts = [];
  2023. for ( d = 0; d <= divisions; d ++ ) {
  2024. pts.push( this.getPointAt( d / divisions ) );
  2025. }
  2026. return pts;
  2027. };
  2028. // Get total curve arc length
  2029. THREE.Curve.prototype.getLength = function () {
  2030. var lengths = this.getLengths();
  2031. return lengths[ lengths.length - 1 ];
  2032. };
  2033. // Get list of cumulative segment lengths
  2034. THREE.Curve.prototype.getLengths = function ( divisions ) {
  2035. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  2036. if ( this.cacheArcLengths
  2037. && ( this.cacheArcLengths.length == divisions + 1 )
  2038. && !this.needsUpdate) {
  2039. //console.log( "cached", this.cacheArcLengths );
  2040. return this.cacheArcLengths;
  2041. }
  2042. this.needsUpdate = false;
  2043. var cache = [];
  2044. var current, last = this.getPoint( 0 );
  2045. var p, sum = 0;
  2046. cache.push( 0 );
  2047. for ( p = 1; p <= divisions; p ++ ) {
  2048. current = this.getPoint ( p / divisions );
  2049. sum += current.distanceTo( last );
  2050. cache.push( sum );
  2051. last = current;
  2052. }
  2053. this.cacheArcLengths = cache;
  2054. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  2055. };
  2056. THREE.Curve.prototype.updateArcLengths = function() {
  2057. this.needsUpdate = true;
  2058. this.getLengths();
  2059. };
  2060. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  2061. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  2062. var arcLengths = this.getLengths();
  2063. var i = 0, il = arcLengths.length;
  2064. var targetArcLength; // The targeted u distance value to get
  2065. if ( distance ) {
  2066. targetArcLength = distance;
  2067. } else {
  2068. targetArcLength = u * arcLengths[ il - 1 ];
  2069. }
  2070. //var time = Date.now();
  2071. // binary search for the index with largest value smaller than target u distance
  2072. var low = 0, high = il - 1, comparison;
  2073. while ( low <= high ) {
  2074. 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
  2075. comparison = arcLengths[ i ] - targetArcLength;
  2076. if ( comparison < 0 ) {
  2077. low = i + 1;
  2078. continue;
  2079. } else if ( comparison > 0 ) {
  2080. high = i - 1;
  2081. continue;
  2082. } else {
  2083. high = i;
  2084. break;
  2085. // DONE
  2086. }
  2087. }
  2088. i = high;
  2089. //console.log('b' , i, low, high, Date.now()- time);
  2090. if ( arcLengths[ i ] == targetArcLength ) {
  2091. var t = i / ( il - 1 );
  2092. return t;
  2093. }
  2094. // we could get finer grain at lengths, or use simple interpolatation between two points
  2095. var lengthBefore = arcLengths[ i ];
  2096. var lengthAfter = arcLengths[ i + 1 ];
  2097. var segmentLength = lengthAfter - lengthBefore;
  2098. // determine where we are between the 'before' and 'after' points
  2099. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  2100. // add that fractional amount to t
  2101. var t = ( i + segmentFraction ) / ( il -1 );
  2102. return t;
  2103. };
  2104. // In 2D space, there are actually 2 normal vectors,
  2105. // and in 3D space, infinte
  2106. // TODO this should be depreciated.
  2107. THREE.Curve.prototype.getNormalVector = function( t ) {
  2108. var vec = this.getTangent( t );
  2109. return new THREE.Vector2( -vec.y , vec.x );
  2110. };
  2111. // Returns a unit vector tangent at t
  2112. // In case any sub curve does not implement its tangent / normal finding,
  2113. // we get 2 points with a small delta and find a gradient of the 2 points
  2114. // which seems to make a reasonable approximation
  2115. THREE.Curve.prototype.getTangent = function( t ) {
  2116. var delta = 0.0001;
  2117. var t1 = t - delta;
  2118. var t2 = t + delta;
  2119. // Capping in case of danger
  2120. if ( t1 < 0 ) t1 = 0;
  2121. if ( t2 > 1 ) t2 = 1;
  2122. var pt1 = this.getPoint( t1 );
  2123. var pt2 = this.getPoint( t2 );
  2124. var vec = pt2.clone().subSelf(pt1);
  2125. return vec.normalize();
  2126. };
  2127. THREE.Curve.prototype.getTangentAt = function ( u ) {
  2128. var t = this.getUtoTmapping( u );
  2129. return this.getTangent( t );
  2130. };
  2131. /**************************************************************
  2132. * Line
  2133. **************************************************************/
  2134. THREE.LineCurve = function ( v1, v2 ) {
  2135. this.v1 = v1;
  2136. this.v2 = v2;
  2137. };
  2138. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  2139. THREE.LineCurve.prototype.getPoint = function ( t ) {
  2140. var point = this.v2.clone().subSelf(this.v1);
  2141. point.multiplyScalar( t ).addSelf( this.v1 );
  2142. return point;
  2143. };
  2144. // Line curve is linear, so we can overwrite default getPointAt
  2145. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  2146. return this.getPoint( u );
  2147. };
  2148. THREE.LineCurve.prototype.getTangent = function( t ) {
  2149. var tangent = this.v2.clone().subSelf(this.v1);
  2150. return tangent.normalize();
  2151. };
  2152. /**************************************************************
  2153. * Quadratic Bezier curve
  2154. **************************************************************/
  2155. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  2156. this.v0 = v0;
  2157. this.v1 = v1;
  2158. this.v2 = v2;
  2159. };
  2160. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  2161. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  2162. var tx, ty;
  2163. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  2164. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  2165. return new THREE.Vector2( tx, ty );
  2166. };
  2167. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  2168. var tx, ty;
  2169. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  2170. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  2171. // returns unit vector
  2172. var tangent = new THREE.Vector2( tx, ty );
  2173. tangent.normalize();
  2174. return tangent;
  2175. };
  2176. /**************************************************************
  2177. * Cubic Bezier curve
  2178. **************************************************************/
  2179. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  2180. this.v0 = v0;
  2181. this.v1 = v1;
  2182. this.v2 = v2;
  2183. this.v3 = v3;
  2184. };
  2185. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  2186. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  2187. var tx, ty;
  2188. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  2189. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  2190. return new THREE.Vector2( tx, ty );
  2191. };
  2192. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  2193. var tx, ty;
  2194. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  2195. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  2196. var tangent = new THREE.Vector2( tx, ty );
  2197. tangent.normalize();
  2198. return tangent;
  2199. };
  2200. /**************************************************************
  2201. * Spline curve
  2202. **************************************************************/
  2203. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  2204. this.points = (points == undefined) ? [] : points;
  2205. };
  2206. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  2207. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  2208. var v = new THREE.Vector2();
  2209. var c = [];
  2210. var points = this.points, point, intPoint, weight;
  2211. point = ( points.length - 1 ) * t;
  2212. intPoint = Math.floor( point );
  2213. weight = point - intPoint;
  2214. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  2215. c[ 1 ] = intPoint;
  2216. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  2217. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  2218. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  2219. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  2220. return v;
  2221. };
  2222. /**************************************************************
  2223. * Ellipse curve
  2224. **************************************************************/
  2225. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  2226. aStartAngle, aEndAngle,
  2227. aClockwise ) {
  2228. this.aX = aX;
  2229. this.aY = aY;
  2230. this.xRadius = xRadius;
  2231. this.yRadius = yRadius;
  2232. this.aStartAngle = aStartAngle;
  2233. this.aEndAngle = aEndAngle;
  2234. this.aClockwise = aClockwise;
  2235. };
  2236. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  2237. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  2238. var deltaAngle = this.aEndAngle - this.aStartAngle;
  2239. if ( !this.aClockwise ) {
  2240. t = 1 - t;
  2241. }
  2242. var angle = this.aStartAngle + t * deltaAngle;
  2243. var tx = this.aX + this.xRadius * Math.cos( angle );
  2244. var ty = this.aY + this.yRadius * Math.sin( angle );
  2245. return new THREE.Vector2( tx, ty );
  2246. };
  2247. /**************************************************************
  2248. * Arc curve
  2249. **************************************************************/
  2250. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  2251. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  2252. };
  2253. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  2254. /**************************************************************
  2255. * Utils
  2256. **************************************************************/
  2257. THREE.Curve.Utils = {
  2258. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  2259. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  2260. },
  2261. // Puay Bing, thanks for helping with this derivative!
  2262. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  2263. return -3 * p0 * (1 - t) * (1 - t) +
  2264. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  2265. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  2266. 3 * t * t * p3;
  2267. },
  2268. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  2269. // To check if my formulas are correct
  2270. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  2271. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  2272. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  2273. var h11 = 3 * t * t - 2 * t; // t3 − t2
  2274. return h00 + h10 + h01 + h11;
  2275. },
  2276. // Catmull-Rom
  2277. interpolate: function( p0, p1, p2, p3, t ) {
  2278. var v0 = ( p2 - p0 ) * 0.5;
  2279. var v1 = ( p3 - p1 ) * 0.5;
  2280. var t2 = t * t;
  2281. var t3 = t * t2;
  2282. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  2283. }
  2284. };
  2285. // TODO: Transformation for Curves?
  2286. /**************************************************************
  2287. * 3D Curves
  2288. **************************************************************/
  2289. // A Factory method for creating new curve subclasses
  2290. THREE.Curve.create = function ( constructor, getPointFunc ) {
  2291. constructor.prototype = Object.create( THREE.Curve.prototype );
  2292. constructor.prototype.getPoint = getPointFunc;
  2293. return constructor;
  2294. };
  2295. /**************************************************************
  2296. * Line3D
  2297. **************************************************************/
  2298. THREE.LineCurve3 = THREE.Curve.create(
  2299. function ( v1, v2 ) {
  2300. this.v1 = v1;
  2301. this.v2 = v2;
  2302. },
  2303. function ( t ) {
  2304. var r = new THREE.Vector3();
  2305. r.sub( this.v2, this.v1 ); // diff
  2306. r.multiplyScalar( t );
  2307. r.addSelf( this.v1 );
  2308. return r;
  2309. }
  2310. );
  2311. /**************************************************************
  2312. * Quadratic Bezier 3D curve
  2313. **************************************************************/
  2314. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  2315. function ( v0, v1, v2 ) {
  2316. this.v0 = v0;
  2317. this.v1 = v1;
  2318. this.v2 = v2;
  2319. },
  2320. function ( t ) {
  2321. var tx, ty, tz;
  2322. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  2323. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  2324. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  2325. return new THREE.Vector3( tx, ty, tz );
  2326. }
  2327. );
  2328. /**************************************************************
  2329. * Cubic Bezier 3D curve
  2330. **************************************************************/
  2331. THREE.CubicBezierCurve3 = THREE.Curve.create(
  2332. function ( v0, v1, v2, v3 ) {
  2333. this.v0 = v0;
  2334. this.v1 = v1;
  2335. this.v2 = v2;
  2336. this.v3 = v3;
  2337. },
  2338. function ( t ) {
  2339. var tx, ty, tz;
  2340. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  2341. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  2342. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  2343. return new THREE.Vector3( tx, ty, tz );
  2344. }
  2345. );
  2346. /**************************************************************
  2347. * Spline 3D curve
  2348. **************************************************************/
  2349. THREE.SplineCurve3 = THREE.Curve.create(
  2350. function ( points /* array of Vector3 */) {
  2351. this.points = (points == undefined) ? [] : points;
  2352. },
  2353. function ( t ) {
  2354. var v = new THREE.Vector3();
  2355. var c = [];
  2356. var points = this.points, point, intPoint, weight;
  2357. point = ( points.length - 1 ) * t;
  2358. intPoint = Math.floor( point );
  2359. weight = point - intPoint;
  2360. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  2361. c[ 1 ] = intPoint;
  2362. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  2363. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  2364. var pt0 = points[ c[0] ],
  2365. pt1 = points[ c[1] ],
  2366. pt2 = points[ c[2] ],
  2367. pt3 = points[ c[3] ];
  2368. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  2369. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  2370. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  2371. return v;
  2372. }
  2373. );
  2374. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  2375. // var v = new THREE.Vector3();
  2376. // var c = [];
  2377. // var points = this.points, point, intPoint, weight;
  2378. // point = ( points.length - 1 ) * t;
  2379. // intPoint = Math.floor( point );
  2380. // weight = point - intPoint;
  2381. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  2382. // c[ 1 ] = intPoint;
  2383. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  2384. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  2385. // var pt0 = points[ c[0] ],
  2386. // pt1 = points[ c[1] ],
  2387. // pt2 = points[ c[2] ],
  2388. // pt3 = points[ c[3] ];
  2389. // // t = weight;
  2390. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  2391. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  2392. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  2393. // return v;
  2394. // }
  2395. /**************************************************************
  2396. * Closed Spline 3D curve
  2397. **************************************************************/
  2398. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  2399. function ( points /* array of Vector3 */) {
  2400. this.points = (points == undefined) ? [] : points;
  2401. },
  2402. function ( t ) {
  2403. var v = new THREE.Vector3();
  2404. var c = [];
  2405. var points = this.points, point, intPoint, weight;
  2406. point = ( points.length - 0 ) * t;
  2407. // This needs to be from 0-length +1
  2408. intPoint = Math.floor( point );
  2409. weight = point - intPoint;
  2410. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  2411. c[ 0 ] = ( intPoint - 1 ) % points.length;
  2412. c[ 1 ] = ( intPoint ) % points.length;
  2413. c[ 2 ] = ( intPoint + 1 ) % points.length;
  2414. c[ 3 ] = ( intPoint + 2 ) % points.length;
  2415. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  2416. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  2417. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  2418. return v;
  2419. }
  2420. );
  2421. /**
  2422. * @author zz85 / http://www.lab4games.net/zz85/blog
  2423. *
  2424. **/
  2425. /**************************************************************
  2426. * Curved Path - a curve path is simply a array of connected
  2427. * curves, but retains the api of a curve
  2428. **************************************************************/
  2429. THREE.CurvePath = function () {
  2430. this.curves = [];
  2431. this.bends = [];
  2432. this.autoClose = false; // Automatically closes the path
  2433. };
  2434. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  2435. THREE.CurvePath.prototype.add = function ( curve ) {
  2436. this.curves.push( curve );
  2437. };
  2438. THREE.CurvePath.prototype.checkConnection = function() {
  2439. // TODO
  2440. // If the ending of curve is not connected to the starting
  2441. // or the next curve, then, this is not a real path
  2442. };
  2443. THREE.CurvePath.prototype.closePath = function() {
  2444. // TODO Test
  2445. // and verify for vector3 (needs to implement equals)
  2446. // Add a line curve if start and end of lines are not connected
  2447. var startPoint = this.curves[0].getPoint(0);
  2448. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  2449. if (!startPoint.equals(endPoint)) {
  2450. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  2451. }
  2452. };
  2453. // To get accurate point with reference to
  2454. // entire path distance at time t,
  2455. // following has to be done:
  2456. // 1. Length of each sub path have to be known
  2457. // 2. Locate and identify type of curve
  2458. // 3. Get t for the curve
  2459. // 4. Return curve.getPointAt(t')
  2460. THREE.CurvePath.prototype.getPoint = function( t ) {
  2461. var d = t * this.getLength();
  2462. var curveLengths = this.getCurveLengths();
  2463. var i = 0, diff, curve;
  2464. // To think about boundaries points.
  2465. while ( i < curveLengths.length ) {
  2466. if ( curveLengths[ i ] >= d ) {
  2467. diff = curveLengths[ i ] - d;
  2468. curve = this.curves[ i ];
  2469. var u = 1 - diff / curve.getLength();
  2470. return curve.getPointAt( u );
  2471. break;
  2472. }
  2473. i ++;
  2474. }
  2475. return null;
  2476. // loop where sum != 0, sum > d , sum+1 <d
  2477. };
  2478. /*
  2479. THREE.CurvePath.prototype.getTangent = function( t ) {
  2480. };*/
  2481. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  2482. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  2483. // getPoint() depends on getLength
  2484. THREE.CurvePath.prototype.getLength = function() {
  2485. var lens = this.getCurveLengths();
  2486. return lens[ lens.length - 1 ];
  2487. };
  2488. // Compute lengths and cache them
  2489. // We cannot overwrite getLengths() because UtoT mapping uses it.
  2490. THREE.CurvePath.prototype.getCurveLengths = function() {
  2491. // We use cache values if curves and cache array are same length
  2492. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  2493. return this.cacheLengths;
  2494. };
  2495. // Get length of subsurve
  2496. // Push sums into cached array
  2497. var lengths = [], sums = 0;
  2498. var i, il = this.curves.length;
  2499. for ( i = 0; i < il; i ++ ) {
  2500. sums += this.curves[ i ].getLength();
  2501. lengths.push( sums );
  2502. }
  2503. this.cacheLengths = lengths;
  2504. return lengths;
  2505. };
  2506. // Returns min and max coordinates, as well as centroid
  2507. THREE.CurvePath.prototype.getBoundingBox = function () {
  2508. var points = this.getPoints();
  2509. var maxX, maxY;
  2510. var minX, minY;
  2511. maxX = maxY = Number.NEGATIVE_INFINITY;
  2512. minX = minY = Number.POSITIVE_INFINITY;
  2513. var p, i, il, sum;
  2514. sum = new THREE.Vector2();
  2515. for ( i = 0, il = points.length; i < il; i ++ ) {
  2516. p = points[ i ];
  2517. if ( p.x > maxX ) maxX = p.x;
  2518. else if ( p.x < minX ) minX = p.x;
  2519. if ( p.y > maxY ) maxY = p.y;
  2520. else if ( p.y < minY ) minY = p.y;
  2521. sum.addSelf( p.x, p.y );
  2522. }
  2523. return {
  2524. minX: minX,
  2525. minY: minY,
  2526. maxX: maxX,
  2527. maxY: maxY,
  2528. centroid: sum.divideScalar( il )
  2529. };
  2530. };
  2531. /**************************************************************
  2532. * Create Geometries Helpers
  2533. **************************************************************/
  2534. /// Generate geometry from path points (for Line or ParticleSystem objects)
  2535. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  2536. var pts = this.getPoints( divisions, true );
  2537. return this.createGeometry( pts );
  2538. };
  2539. // Generate geometry from equidistance sampling along the path
  2540. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  2541. var pts = this.getSpacedPoints( divisions, true );
  2542. return this.createGeometry( pts );
  2543. };
  2544. THREE.CurvePath.prototype.createGeometry = function( points ) {
  2545. var geometry = new THREE.Geometry();
  2546. for ( var i = 0; i < points.length; i ++ ) {
  2547. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, 0 ) );
  2548. }
  2549. return geometry;
  2550. };
  2551. /**************************************************************
  2552. * Bend / Wrap Helper Methods
  2553. **************************************************************/
  2554. // Wrap path / Bend modifiers?
  2555. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  2556. this.bends.push( bendpath );
  2557. };
  2558. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  2559. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  2560. var i, il;
  2561. if ( !bends ) {
  2562. bends = this.bends;
  2563. }
  2564. for ( i = 0, il = bends.length; i < il; i ++ ) {
  2565. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  2566. }
  2567. return oldPts;
  2568. };
  2569. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  2570. var oldPts = this.getSpacedPoints( segments );
  2571. var i, il;
  2572. if ( !bends ) {
  2573. bends = this.bends;
  2574. }
  2575. for ( i = 0, il = bends.length; i < il; i ++ ) {
  2576. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  2577. }
  2578. return oldPts;
  2579. };
  2580. // This returns getPoints() bend/wrapped around the contour of a path.
  2581. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  2582. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  2583. var bounds = this.getBoundingBox();
  2584. var i, il, p, oldX, oldY, xNorm;
  2585. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  2586. p = oldPts[ i ];
  2587. oldX = p.x;
  2588. oldY = p.y;
  2589. xNorm = oldX / bounds.maxX;
  2590. // If using actual distance, for length > path, requires line extrusions
  2591. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  2592. xNorm = path.getUtoTmapping( xNorm, oldX );
  2593. // check for out of bounds?
  2594. var pathPt = path.getPoint( xNorm );
  2595. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  2596. p.x = pathPt.x + normal.x;
  2597. p.y = pathPt.y + normal.y;
  2598. }
  2599. return oldPts;
  2600. };
  2601. /**
  2602. * @author alteredq / http://alteredqualia.com/
  2603. */
  2604. THREE.Gyroscope = function () {
  2605. THREE.Object3D.call( this );
  2606. };
  2607. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  2608. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  2609. this.matrixAutoUpdate && this.updateMatrix();
  2610. // update matrixWorld
  2611. if ( this.matrixWorldNeedsUpdate || force ) {
  2612. if ( this.parent ) {
  2613. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  2614. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  2615. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  2616. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  2617. } else {
  2618. this.matrixWorld.copy( this.matrix );
  2619. }
  2620. this.matrixWorldNeedsUpdate = false;
  2621. force = true;
  2622. }
  2623. // update children
  2624. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2625. this.children[ i ].updateMatrixWorld( force );
  2626. }
  2627. };
  2628. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  2629. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  2630. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  2631. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  2632. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  2633. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  2634. /**
  2635. * @author zz85 / http://www.lab4games.net/zz85/blog
  2636. * Creates free form 2d path using series of points, lines or curves.
  2637. *
  2638. **/
  2639. THREE.Path = function ( points ) {
  2640. THREE.CurvePath.call(this);
  2641. this.actions = [];
  2642. if ( points ) {
  2643. this.fromPoints( points );
  2644. }
  2645. };
  2646. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  2647. THREE.PathActions = {
  2648. MOVE_TO: 'moveTo',
  2649. LINE_TO: 'lineTo',
  2650. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  2651. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  2652. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  2653. ARC: 'arc', // Circle
  2654. ELLIPSE: 'ellipse'
  2655. };
  2656. // TODO Clean up PATH API
  2657. // Create path using straight lines to connect all points
  2658. // - vectors: array of Vector2
  2659. THREE.Path.prototype.fromPoints = function ( vectors ) {
  2660. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  2661. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  2662. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  2663. };
  2664. };
  2665. // startPath() endPath()?
  2666. THREE.Path.prototype.moveTo = function ( x, y ) {
  2667. var args = Array.prototype.slice.call( arguments );
  2668. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  2669. };
  2670. THREE.Path.prototype.lineTo = function ( x, y ) {
  2671. var args = Array.prototype.slice.call( arguments );
  2672. var lastargs = this.actions[ this.actions.length - 1 ].args;
  2673. var x0 = lastargs[ lastargs.length - 2 ];
  2674. var y0 = lastargs[ lastargs.length - 1 ];
  2675. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  2676. this.curves.push( curve );
  2677. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  2678. };
  2679. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  2680. var args = Array.prototype.slice.call( arguments );
  2681. var lastargs = this.actions[ this.actions.length - 1 ].args;
  2682. var x0 = lastargs[ lastargs.length - 2 ];
  2683. var y0 = lastargs[ lastargs.length - 1 ];
  2684. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  2685. new THREE.Vector2( aCPx, aCPy ),
  2686. new THREE.Vector2( aX, aY ) );
  2687. this.curves.push( curve );
  2688. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  2689. };
  2690. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  2691. aCP2x, aCP2y,
  2692. aX, aY ) {
  2693. var args = Array.prototype.slice.call( arguments );
  2694. var lastargs = this.actions[ this.actions.length - 1 ].args;
  2695. var x0 = lastargs[ lastargs.length - 2 ];
  2696. var y0 = lastargs[ lastargs.length - 1 ];
  2697. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  2698. new THREE.Vector2( aCP1x, aCP1y ),
  2699. new THREE.Vector2( aCP2x, aCP2y ),
  2700. new THREE.Vector2( aX, aY ) );
  2701. this.curves.push( curve );
  2702. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  2703. };
  2704. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  2705. var args = Array.prototype.slice.call( arguments );
  2706. var lastargs = this.actions[ this.actions.length - 1 ].args;
  2707. var x0 = lastargs[ lastargs.length - 2 ];
  2708. var y0 = lastargs[ lastargs.length - 1 ];
  2709. //---
  2710. var npts = [ new THREE.Vector2( x0, y0 ) ];
  2711. Array.prototype.push.apply( npts, pts );
  2712. var curve = new THREE.SplineCurve( npts );
  2713. this.curves.push( curve );
  2714. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  2715. };
  2716. // FUTURE: Change the API or follow canvas API?
  2717. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  2718. aStartAngle, aEndAngle, aClockwise ) {
  2719. var laste = this.actions[ this.actions.length - 1];
  2720. this.absellipse(laste.x + aX, laste.y + aY, xRadius, yRadius,
  2721. aStartAngle, aEndAngle, aClockwise );
  2722. };
  2723. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  2724. aStartAngle, aEndAngle, aClockwise ) {
  2725. var laste = this.actions[ this.actions.length - 1];
  2726. this.absarc(laste.x + aX, laste.y + aY, aRadius,
  2727. aStartAngle, aEndAngle, aClockwise );
  2728. };
  2729. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  2730. aStartAngle, aEndAngle, aClockwise ) {
  2731. var args = Array.prototype.slice.call( arguments );
  2732. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  2733. aStartAngle, aEndAngle, aClockwise );
  2734. this.curves.push( curve );
  2735. // All of the other actions look to the last two elements in the list to
  2736. // find the ending point, so we need to append them.
  2737. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  2738. args.push(lastPoint.x);
  2739. args.push(lastPoint.y);
  2740. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  2741. };
  2742. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  2743. aStartAngle, aEndAngle, aClockwise ) {
  2744. this.absellipse(aX, aY, aRadius, aRadius,
  2745. aStartAngle, aEndAngle, aClockwise);
  2746. };
  2747. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  2748. if ( ! divisions ) divisions = 40;
  2749. var points = [];
  2750. for ( var i = 0; i < divisions; i ++ ) {
  2751. points.push( this.getPoint( i / divisions ) );
  2752. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  2753. }
  2754. // if ( closedPath ) {
  2755. //
  2756. // points.push( points[ 0 ] );
  2757. //
  2758. // }
  2759. return points;
  2760. };
  2761. /* Return an array of vectors based on contour of the path */
  2762. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  2763. if (this.useSpacedPoints) {
  2764. console.log('tata');
  2765. return this.getSpacedPoints( divisions, closedPath );
  2766. }
  2767. divisions = divisions || 12;
  2768. var points = [];
  2769. var i, il, item, action, args;
  2770. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  2771. laste, j,
  2772. t, tx, ty;
  2773. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  2774. item = this.actions[ i ];
  2775. action = item.action;
  2776. args = item.args;
  2777. switch( action ) {
  2778. case THREE.PathActions.MOVE_TO:
  2779. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  2780. break;
  2781. case THREE.PathActions.LINE_TO:
  2782. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  2783. break;
  2784. case THREE.PathActions.QUADRATIC_CURVE_TO:
  2785. cpx = args[ 2 ];
  2786. cpy = args[ 3 ];
  2787. cpx1 = args[ 0 ];
  2788. cpy1 = args[ 1 ];
  2789. if ( points.length > 0 ) {
  2790. laste = points[ points.length - 1 ];
  2791. cpx0 = laste.x;
  2792. cpy0 = laste.y;
  2793. } else {
  2794. laste = this.actions[ i - 1 ].args;
  2795. cpx0 = laste[ laste.length - 2 ];
  2796. cpy0 = laste[ laste.length - 1 ];
  2797. }
  2798. for ( j = 1; j <= divisions; j ++ ) {
  2799. t = j / divisions;
  2800. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  2801. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  2802. points.push( new THREE.Vector2( tx, ty ) );
  2803. }
  2804. break;
  2805. case THREE.PathActions.BEZIER_CURVE_TO:
  2806. cpx = args[ 4 ];
  2807. cpy = args[ 5 ];
  2808. cpx1 = args[ 0 ];
  2809. cpy1 = args[ 1 ];
  2810. cpx2 = args[ 2 ];
  2811. cpy2 = args[ 3 ];
  2812. if ( points.length > 0 ) {
  2813. laste = points[ points.length - 1 ];
  2814. cpx0 = laste.x;
  2815. cpy0 = laste.y;
  2816. } else {
  2817. laste = this.actions[ i - 1 ].args;
  2818. cpx0 = laste[ laste.length - 2 ];
  2819. cpy0 = laste[ laste.length - 1 ];
  2820. }
  2821. for ( j = 1; j <= divisions; j ++ ) {
  2822. t = j / divisions;
  2823. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  2824. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  2825. points.push( new THREE.Vector2( tx, ty ) );
  2826. }
  2827. break;
  2828. case THREE.PathActions.CSPLINE_THRU:
  2829. laste = this.actions[ i - 1 ].args;
  2830. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  2831. var spts = [ last ];
  2832. var n = divisions * args[ 0 ].length;
  2833. spts = spts.concat( args[ 0 ] );
  2834. var spline = new THREE.SplineCurve( spts );
  2835. for ( j = 1; j <= n; j ++ ) {
  2836. points.push( spline.getPointAt( j / n ) ) ;
  2837. }
  2838. break;
  2839. case THREE.PathActions.ARC:
  2840. var aX = args[ 0 ], aY = args[ 1 ],
  2841. aRadius = args[ 2 ],
  2842. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  2843. aClockwise = !!args[ 5 ];
  2844. var deltaAngle = aEndAngle - aStartAngle;
  2845. var angle;
  2846. var tdivisions = divisions * 2;
  2847. for ( j = 1; j <= tdivisions; j ++ ) {
  2848. t = j / tdivisions;
  2849. if ( ! aClockwise ) {
  2850. t = 1 - t;
  2851. }
  2852. angle = aStartAngle + t * deltaAngle;
  2853. tx = aX + aRadius * Math.cos( angle );
  2854. ty = aY + aRadius * Math.sin( angle );
  2855. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  2856. points.push( new THREE.Vector2( tx, ty ) );
  2857. }
  2858. //console.log(points);
  2859. break;
  2860. case THREE.PathActions.ELLIPSE:
  2861. var aX = args[ 0 ], aY = args[ 1 ],
  2862. xRadius = args[ 2 ],
  2863. yRadius = args[3]
  2864. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  2865. aClockwise = !!args[ 6 ];
  2866. var deltaAngle = aEndAngle - aStartAngle;
  2867. var angle;
  2868. var tdivisions = divisions * 2;
  2869. for ( j = 1; j <= tdivisions; j ++ ) {
  2870. t = j / tdivisions;
  2871. if ( ! aClockwise ) {
  2872. t = 1 - t;
  2873. }
  2874. angle = aStartAngle + t * deltaAngle;
  2875. tx = aX + xRadius * Math.cos( angle );
  2876. ty = aY + yRadius * Math.sin( angle );
  2877. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  2878. points.push( new THREE.Vector2( tx, ty ) );
  2879. }
  2880. //console.log(points);
  2881. break;
  2882. } // end switch
  2883. }
  2884. // Normalize to remove the closing point by default.
  2885. var lastPoint = points[ points.length - 1];
  2886. var EPSILON = 0.0000000001;
  2887. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  2888. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  2889. points.splice( points.length - 1, 1);
  2890. if ( closedPath ) {
  2891. points.push( points[ 0 ] );
  2892. }
  2893. return points;
  2894. };
  2895. // Breaks path into shapes
  2896. THREE.Path.prototype.toShapes = function() {
  2897. var i, il, item, action, args;
  2898. var subPaths = [], lastPath = new THREE.Path();
  2899. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  2900. item = this.actions[ i ];
  2901. args = item.args;
  2902. action = item.action;
  2903. if ( action == THREE.PathActions.MOVE_TO ) {
  2904. if ( lastPath.actions.length != 0 ) {
  2905. subPaths.push( lastPath );
  2906. lastPath = new THREE.Path();
  2907. }
  2908. }
  2909. lastPath[ action ].apply( lastPath, args );
  2910. }
  2911. if ( lastPath.actions.length != 0 ) {
  2912. subPaths.push( lastPath );
  2913. }
  2914. // console.log(subPaths);
  2915. if ( subPaths.length == 0 ) return [];
  2916. var tmpPath, tmpShape, shapes = [];
  2917. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  2918. // console.log("Holes first", holesFirst);
  2919. if ( subPaths.length == 1) {
  2920. tmpPath = subPaths[0];
  2921. tmpShape = new THREE.Shape();
  2922. tmpShape.actions = tmpPath.actions;
  2923. tmpShape.curves = tmpPath.curves;
  2924. shapes.push( tmpShape );
  2925. return shapes;
  2926. };
  2927. if ( holesFirst ) {
  2928. tmpShape = new THREE.Shape();
  2929. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  2930. tmpPath = subPaths[ i ];
  2931. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  2932. tmpShape.actions = tmpPath.actions;
  2933. tmpShape.curves = tmpPath.curves;
  2934. shapes.push( tmpShape );
  2935. tmpShape = new THREE.Shape();
  2936. //console.log('cw', i);
  2937. } else {
  2938. tmpShape.holes.push( tmpPath );
  2939. //console.log('ccw', i);
  2940. }
  2941. }
  2942. } else {
  2943. // Shapes first
  2944. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  2945. tmpPath = subPaths[ i ];
  2946. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  2947. if ( tmpShape ) shapes.push( tmpShape );
  2948. tmpShape = new THREE.Shape();
  2949. tmpShape.actions = tmpPath.actions;
  2950. tmpShape.curves = tmpPath.curves;
  2951. } else {
  2952. tmpShape.holes.push( tmpPath );
  2953. }
  2954. }
  2955. shapes.push( tmpShape );
  2956. }
  2957. //console.log("shape", shapes);
  2958. return shapes;
  2959. };
  2960. /**
  2961. * @author zz85 / http://www.lab4games.net/zz85/blog
  2962. * Defines a 2d shape plane using paths.
  2963. **/
  2964. // STEP 1 Create a path.
  2965. // STEP 2 Turn path into shape.
  2966. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  2967. // STEP 3a - Extract points from each shape, turn to vertices
  2968. // STEP 3b - Triangulate each shape, add faces.
  2969. THREE.Shape = function ( ) {
  2970. THREE.Path.apply( this, arguments );
  2971. this.holes = [];
  2972. };
  2973. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  2974. // Convenience method to return ExtrudeGeometry
  2975. THREE.Shape.prototype.extrude = function ( options ) {
  2976. var extruded = new THREE.ExtrudeGeometry( this, options );
  2977. return extruded;
  2978. };
  2979. // Get points of holes
  2980. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  2981. var i, il = this.holes.length, holesPts = [];
  2982. for ( i = 0; i < il; i ++ ) {
  2983. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  2984. }
  2985. return holesPts;
  2986. };
  2987. // Get points of holes (spaced by regular distance)
  2988. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  2989. var i, il = this.holes.length, holesPts = [];
  2990. for ( i = 0; i < il; i ++ ) {
  2991. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  2992. }
  2993. return holesPts;
  2994. };
  2995. // Get points of shape and holes (keypoints based on segments parameter)
  2996. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  2997. return {
  2998. shape: this.getTransformedPoints( divisions ),
  2999. holes: this.getPointsHoles( divisions )
  3000. };
  3001. };
  3002. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  3003. if (this.useSpacedPoints) {
  3004. return this.extractAllSpacedPoints(divisions);
  3005. }
  3006. return this.extractAllPoints(divisions);
  3007. };
  3008. //
  3009. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  3010. //
  3011. // return {
  3012. //
  3013. // shape: this.transform( bend, divisions ),
  3014. // holes: this.getPointsHoles( divisions, bend )
  3015. //
  3016. // };
  3017. //
  3018. // };
  3019. // Get points of shape and holes (spaced by regular distance)
  3020. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  3021. return {
  3022. shape: this.getTransformedSpacedPoints( divisions ),
  3023. holes: this.getSpacedPointsHoles( divisions )
  3024. };
  3025. };
  3026. /**************************************************************
  3027. * Utils
  3028. **************************************************************/
  3029. THREE.Shape.Utils = {
  3030. /*
  3031. contour - array of vector2 for contour
  3032. holes - array of array of vector2
  3033. */
  3034. removeHoles: function ( contour, holes ) {
  3035. var shape = contour.concat(); // work on this shape
  3036. var allpoints = shape.concat();
  3037. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  3038. var prevShapeVert, nextShapeVert,
  3039. prevHoleVert, nextHoleVert,
  3040. holeIndex, shapeIndex,
  3041. shapeId, shapeGroup,
  3042. h, h2,
  3043. hole, shortest, d,
  3044. p, pts1, pts2,
  3045. tmpShape1, tmpShape2,
  3046. tmpHole1, tmpHole2,
  3047. verts = [];
  3048. for ( h = 0; h < holes.length; h ++ ) {
  3049. hole = holes[ h ];
  3050. /*
  3051. shapeholes[ h ].concat(); // preserves original
  3052. holes.push( hole );
  3053. */
  3054. Array.prototype.push.apply( allpoints, hole );
  3055. shortest = Number.POSITIVE_INFINITY;
  3056. // Find the shortest pair of pts between shape and hole
  3057. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  3058. // Using distanceToSquared() intead of distanceTo() should speed a little
  3059. // since running square roots operations are reduced.
  3060. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  3061. pts1 = hole[ h2 ];
  3062. var dist = [];
  3063. for ( p = 0; p < shape.length; p++ ) {
  3064. pts2 = shape[ p ];
  3065. d = pts1.distanceToSquared( pts2 );
  3066. dist.push( d );
  3067. if ( d < shortest ) {
  3068. shortest = d;
  3069. holeIndex = h2;
  3070. shapeIndex = p;
  3071. }
  3072. }
  3073. }
  3074. //console.log("shortest", shortest, dist);
  3075. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  3076. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  3077. var areaapts = [
  3078. hole[ holeIndex ],
  3079. shape[ shapeIndex ],
  3080. shape[ prevShapeVert ]
  3081. ];
  3082. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  3083. var areabpts = [
  3084. hole[ holeIndex ],
  3085. hole[ prevHoleVert ],
  3086. shape[ shapeIndex ]
  3087. ];
  3088. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  3089. var shapeOffset = 1;
  3090. var holeOffset = -1;
  3091. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  3092. shapeIndex += shapeOffset;
  3093. holeIndex += holeOffset;
  3094. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  3095. shapeIndex %= shape.length;
  3096. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  3097. holeIndex %= hole.length;
  3098. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  3099. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  3100. areaapts = [
  3101. hole[ holeIndex ],
  3102. shape[ shapeIndex ],
  3103. shape[ prevShapeVert ]
  3104. ];
  3105. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  3106. areabpts = [
  3107. hole[ holeIndex ],
  3108. hole[ prevHoleVert ],
  3109. shape[ shapeIndex ]
  3110. ];
  3111. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  3112. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  3113. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  3114. // In case areas are not correct.
  3115. //console.log("USE THIS");
  3116. shapeIndex = oldShapeIndex;
  3117. holeIndex = oldHoleIndex ;
  3118. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  3119. shapeIndex %= shape.length;
  3120. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  3121. holeIndex %= hole.length;
  3122. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  3123. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  3124. } else {
  3125. //console.log("USE THAT ")
  3126. }
  3127. tmpShape1 = shape.slice( 0, shapeIndex );
  3128. tmpShape2 = shape.slice( shapeIndex );
  3129. tmpHole1 = hole.slice( holeIndex );
  3130. tmpHole2 = hole.slice( 0, holeIndex );
  3131. // Should check orders here again?
  3132. var trianglea = [
  3133. hole[ holeIndex ],
  3134. shape[ shapeIndex ],
  3135. shape[ prevShapeVert ]
  3136. ];
  3137. var triangleb = [
  3138. hole[ holeIndex ] ,
  3139. hole[ prevHoleVert ],
  3140. shape[ shapeIndex ]
  3141. ];
  3142. verts.push( trianglea );
  3143. verts.push( triangleb );
  3144. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  3145. }
  3146. return {
  3147. shape:shape, /* shape with no holes */
  3148. isolatedPts: verts, /* isolated faces */
  3149. allpoints: allpoints
  3150. }
  3151. },
  3152. triangulateShape: function ( contour, holes ) {
  3153. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  3154. var shape = shapeWithoutHoles.shape,
  3155. allpoints = shapeWithoutHoles.allpoints,
  3156. isolatedPts = shapeWithoutHoles.isolatedPts;
  3157. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  3158. // 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.
  3159. //console.log( "triangles",triangles, triangles.length );
  3160. //console.log( "allpoints",allpoints, allpoints.length );
  3161. var i, il, f, face,
  3162. key, index,
  3163. allPointsMap = {},
  3164. isolatedPointsMap = {};
  3165. // prepare all points map
  3166. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  3167. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  3168. if ( allPointsMap[ key ] !== undefined ) {
  3169. console.log( "Duplicate point", key );
  3170. }
  3171. allPointsMap[ key ] = i;
  3172. }
  3173. // check all face vertices against all points map
  3174. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  3175. face = triangles[ i ];
  3176. for ( f = 0; f < 3; f ++ ) {
  3177. key = face[ f ].x + ":" + face[ f ].y;
  3178. index = allPointsMap[ key ];
  3179. if ( index !== undefined ) {
  3180. face[ f ] = index;
  3181. }
  3182. }
  3183. }
  3184. // check isolated points vertices against all points map
  3185. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  3186. face = isolatedPts[ i ];
  3187. for ( f = 0; f < 3; f ++ ) {
  3188. key = face[ f ].x + ":" + face[ f ].y;
  3189. index = allPointsMap[ key ];
  3190. if ( index !== undefined ) {
  3191. face[ f ] = index;
  3192. }
  3193. }
  3194. }
  3195. return triangles.concat( isolatedPts );
  3196. }, // end triangulate shapes
  3197. /*
  3198. triangulate2 : function( pts, holes ) {
  3199. // For use with Poly2Tri.js
  3200. var allpts = pts.concat();
  3201. var shape = [];
  3202. for (var p in pts) {
  3203. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  3204. }
  3205. var swctx = new js.poly2tri.SweepContext(shape);
  3206. for (var h in holes) {
  3207. var aHole = holes[h];
  3208. var newHole = []
  3209. for (i in aHole) {
  3210. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  3211. allpts.push(aHole[i]);
  3212. }
  3213. swctx.AddHole(newHole);
  3214. }
  3215. var find;
  3216. var findIndexForPt = function (pt) {
  3217. find = new THREE.Vector2(pt.x, pt.y);
  3218. var p;
  3219. for (p=0, pl = allpts.length; p<pl; p++) {
  3220. if (allpts[p].equals(find)) return p;
  3221. }
  3222. return -1;
  3223. };
  3224. // triangulate
  3225. js.poly2tri.sweep.Triangulate(swctx);
  3226. var triangles = swctx.GetTriangles();
  3227. var tr ;
  3228. var facesPts = [];
  3229. for (var t in triangles) {
  3230. tr = triangles[t];
  3231. facesPts.push([
  3232. findIndexForPt(tr.GetPoint(0)),
  3233. findIndexForPt(tr.GetPoint(1)),
  3234. findIndexForPt(tr.GetPoint(2))
  3235. ]);
  3236. }
  3237. // console.log(facesPts);
  3238. // console.log("triangles", triangles.length, triangles);
  3239. // Returns array of faces with 3 element each
  3240. return facesPts;
  3241. },
  3242. */
  3243. isClockWise: function ( pts ) {
  3244. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  3245. },
  3246. // Bezier Curves formulas obtained from
  3247. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  3248. // Quad Bezier Functions
  3249. b2p0: function ( t, p ) {
  3250. var k = 1 - t;
  3251. return k * k * p;
  3252. },
  3253. b2p1: function ( t, p ) {
  3254. return 2 * ( 1 - t ) * t * p;
  3255. },
  3256. b2p2: function ( t, p ) {
  3257. return t * t * p;
  3258. },
  3259. b2: function ( t, p0, p1, p2 ) {
  3260. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  3261. },
  3262. // Cubic Bezier Functions
  3263. b3p0: function ( t, p ) {
  3264. var k = 1 - t;
  3265. return k * k * k * p;
  3266. },
  3267. b3p1: function ( t, p ) {
  3268. var k = 1 - t;
  3269. return 3 * k * k * t * p;
  3270. },
  3271. b3p2: function ( t, p ) {
  3272. var k = 1 - t;
  3273. return 3 * k * t * t * p;
  3274. },
  3275. b3p3: function ( t, p ) {
  3276. return t * t * t * p;
  3277. },
  3278. b3: function ( t, p0, p1, p2, p3 ) {
  3279. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  3280. }
  3281. };
  3282. /**
  3283. * @author mikael emtinger / http://gomo.se/
  3284. */
  3285. THREE.AnimationHandler = (function() {
  3286. var playing = [];
  3287. var library = {};
  3288. var that = {};
  3289. //--- update ---
  3290. that.update = function( deltaTimeMS ) {
  3291. for( var i = 0; i < playing.length; i ++ )
  3292. playing[ i ].update( deltaTimeMS );
  3293. };
  3294. //--- add ---
  3295. that.addToUpdate = function( animation ) {
  3296. if ( playing.indexOf( animation ) === -1 )
  3297. playing.push( animation );
  3298. };
  3299. //--- remove ---
  3300. that.removeFromUpdate = function( animation ) {
  3301. var index = playing.indexOf( animation );
  3302. if( index !== -1 )
  3303. playing.splice( index, 1 );
  3304. };
  3305. //--- add ---
  3306. that.add = function( data ) {
  3307. if ( library[ data.name ] !== undefined )
  3308. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  3309. library[ data.name ] = data;
  3310. initData( data );
  3311. };
  3312. //--- get ---
  3313. that.get = function( name ) {
  3314. if ( typeof name === "string" ) {
  3315. if ( library[ name ] ) {
  3316. return library[ name ];
  3317. } else {
  3318. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  3319. return null;
  3320. }
  3321. } else {
  3322. // todo: add simple tween library
  3323. }
  3324. };
  3325. //--- parse ---
  3326. that.parse = function( root ) {
  3327. // setup hierarchy
  3328. var hierarchy = [];
  3329. if ( root instanceof THREE.SkinnedMesh ) {
  3330. for( var b = 0; b < root.bones.length; b++ ) {
  3331. hierarchy.push( root.bones[ b ] );
  3332. }
  3333. } else {
  3334. parseRecurseHierarchy( root, hierarchy );
  3335. }
  3336. return hierarchy;
  3337. };
  3338. var parseRecurseHierarchy = function( root, hierarchy ) {
  3339. hierarchy.push( root );
  3340. for( var c = 0; c < root.children.length; c++ )
  3341. parseRecurseHierarchy( root.children[ c ], hierarchy );
  3342. }
  3343. //--- init data ---
  3344. var initData = function( data ) {
  3345. if( data.initialized === true )
  3346. return;
  3347. // loop through all keys
  3348. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  3349. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  3350. // remove minus times
  3351. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  3352. data.hierarchy[ h ].keys[ k ].time = 0;
  3353. // create quaternions
  3354. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  3355. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  3356. var quat = data.hierarchy[ h ].keys[ k ].rot;
  3357. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  3358. }
  3359. }
  3360. // prepare morph target keys
  3361. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  3362. // get all used
  3363. var usedMorphTargets = {};
  3364. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  3365. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  3366. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  3367. usedMorphTargets[ morphTargetName ] = -1;
  3368. }
  3369. }
  3370. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  3371. // set all used on all frames
  3372. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  3373. var influences = {};
  3374. for ( var morphTargetName in usedMorphTargets ) {
  3375. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  3376. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  3377. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  3378. break;
  3379. }
  3380. }
  3381. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  3382. influences[ morphTargetName ] = 0;
  3383. }
  3384. }
  3385. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  3386. }
  3387. }
  3388. // remove all keys that are on the same time
  3389. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  3390. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  3391. data.hierarchy[ h ].keys.splice( k, 1 );
  3392. k --;
  3393. }
  3394. }
  3395. // set index
  3396. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  3397. data.hierarchy[ h ].keys[ k ].index = k;
  3398. }
  3399. }
  3400. // JIT
  3401. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  3402. data.JIT = {};
  3403. data.JIT.hierarchy = [];
  3404. for( var h = 0; h < data.hierarchy.length; h ++ )
  3405. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  3406. // done
  3407. data.initialized = true;
  3408. };
  3409. // interpolation types
  3410. that.LINEAR = 0;
  3411. that.CATMULLROM = 1;
  3412. that.CATMULLROM_FORWARD = 2;
  3413. return that;
  3414. }());
  3415. /**
  3416. * @author mikael emtinger / http://gomo.se/
  3417. * @author mrdoob / http://mrdoob.com/
  3418. * @author alteredq / http://alteredqualia.com/
  3419. */
  3420. THREE.Animation = function ( root, name, interpolationType ) {
  3421. this.root = root;
  3422. this.data = THREE.AnimationHandler.get( name );
  3423. this.hierarchy = THREE.AnimationHandler.parse( root );
  3424. this.currentTime = 0;
  3425. this.timeScale = 1;
  3426. this.isPlaying = false;
  3427. this.isPaused = true;
  3428. this.loop = true;
  3429. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  3430. this.points = [];
  3431. this.target = new THREE.Vector3();
  3432. };
  3433. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  3434. if ( this.isPlaying === false ) {
  3435. this.isPlaying = true;
  3436. this.loop = loop !== undefined ? loop : true;
  3437. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  3438. // reset key cache
  3439. var h, hl = this.hierarchy.length,
  3440. object;
  3441. for ( h = 0; h < hl; h ++ ) {
  3442. object = this.hierarchy[ h ];
  3443. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  3444. object.useQuaternion = true;
  3445. }
  3446. object.matrixAutoUpdate = true;
  3447. if ( object.animationCache === undefined ) {
  3448. object.animationCache = {};
  3449. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  3450. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  3451. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  3452. }
  3453. var prevKey = object.animationCache.prevKey;
  3454. var nextKey = object.animationCache.nextKey;
  3455. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  3456. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  3457. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  3458. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  3459. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  3460. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  3461. }
  3462. this.update( 0 );
  3463. }
  3464. this.isPaused = false;
  3465. THREE.AnimationHandler.addToUpdate( this );
  3466. };
  3467. THREE.Animation.prototype.pause = function() {
  3468. if ( this.isPaused === true ) {
  3469. THREE.AnimationHandler.addToUpdate( this );
  3470. } else {
  3471. THREE.AnimationHandler.removeFromUpdate( this );
  3472. }
  3473. this.isPaused = !this.isPaused;
  3474. };
  3475. THREE.Animation.prototype.stop = function() {
  3476. this.isPlaying = false;
  3477. this.isPaused = false;
  3478. THREE.AnimationHandler.removeFromUpdate( this );
  3479. };
  3480. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  3481. // early out
  3482. if ( this.isPlaying === false ) return;
  3483. // vars
  3484. var types = [ "pos", "rot", "scl" ];
  3485. var type;
  3486. var scale;
  3487. var vector;
  3488. var prevXYZ, nextXYZ;
  3489. var prevKey, nextKey;
  3490. var object;
  3491. var animationCache;
  3492. var frame;
  3493. var JIThierarchy = this.data.JIT.hierarchy;
  3494. var currentTime, unloopedCurrentTime;
  3495. var currentPoint, forwardPoint, angle;
  3496. this.currentTime += deltaTimeMS * this.timeScale;
  3497. unloopedCurrentTime = this.currentTime;
  3498. currentTime = this.currentTime = this.currentTime % this.data.length;
  3499. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  3500. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  3501. object = this.hierarchy[ h ];
  3502. animationCache = object.animationCache;
  3503. // loop through pos/rot/scl
  3504. for ( var t = 0; t < 3; t ++ ) {
  3505. // get keys
  3506. type = types[ t ];
  3507. prevKey = animationCache.prevKey[ type ];
  3508. nextKey = animationCache.nextKey[ type ];
  3509. // switch keys?
  3510. if ( nextKey.time <= unloopedCurrentTime ) {
  3511. // did we loop?
  3512. if ( currentTime < unloopedCurrentTime ) {
  3513. if ( this.loop ) {
  3514. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  3515. nextKey = this.getNextKeyWith( type, h, 1 );
  3516. while( nextKey.time < currentTime ) {
  3517. prevKey = nextKey;
  3518. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  3519. }
  3520. } else {
  3521. this.stop();
  3522. return;
  3523. }
  3524. } else {
  3525. do {
  3526. prevKey = nextKey;
  3527. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  3528. } while( nextKey.time < currentTime )
  3529. }
  3530. animationCache.prevKey[ type ] = prevKey;
  3531. animationCache.nextKey[ type ] = nextKey;
  3532. }
  3533. object.matrixAutoUpdate = true;
  3534. object.matrixWorldNeedsUpdate = true;
  3535. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  3536. prevXYZ = prevKey[ type ];
  3537. nextXYZ = nextKey[ type ];
  3538. // check scale error
  3539. if ( scale < 0 || scale > 1 ) {
  3540. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  3541. scale = scale < 0 ? 0 : 1;
  3542. }
  3543. // interpolate
  3544. if ( type === "pos" ) {
  3545. vector = object.position;
  3546. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  3547. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  3548. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  3549. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  3550. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  3551. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  3552. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  3553. this.points[ 1 ] = prevXYZ;
  3554. this.points[ 2 ] = nextXYZ;
  3555. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  3556. scale = scale * 0.33 + 0.33;
  3557. currentPoint = this.interpolateCatmullRom( this.points, scale );
  3558. vector.x = currentPoint[ 0 ];
  3559. vector.y = currentPoint[ 1 ];
  3560. vector.z = currentPoint[ 2 ];
  3561. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  3562. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  3563. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  3564. this.target.subSelf( vector );
  3565. this.target.y = 0;
  3566. this.target.normalize();
  3567. angle = Math.atan2( this.target.x, this.target.z );
  3568. object.rotation.set( 0, angle, 0 );
  3569. }
  3570. }
  3571. } else if ( type === "rot" ) {
  3572. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  3573. } else if ( type === "scl" ) {
  3574. vector = object.scale;
  3575. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  3576. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  3577. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  3578. }
  3579. }
  3580. }
  3581. };
  3582. // Catmull-Rom spline
  3583. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  3584. var c = [], v3 = [],
  3585. point, intPoint, weight, w2, w3,
  3586. pa, pb, pc, pd;
  3587. point = ( points.length - 1 ) * scale;
  3588. intPoint = Math.floor( point );
  3589. weight = point - intPoint;
  3590. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3591. c[ 1 ] = intPoint;
  3592. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  3593. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  3594. pa = points[ c[ 0 ] ];
  3595. pb = points[ c[ 1 ] ];
  3596. pc = points[ c[ 2 ] ];
  3597. pd = points[ c[ 3 ] ];
  3598. w2 = weight * weight;
  3599. w3 = weight * w2;
  3600. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  3601. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  3602. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  3603. return v3;
  3604. };
  3605. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  3606. var v0 = ( p2 - p0 ) * 0.5,
  3607. v1 = ( p3 - p1 ) * 0.5;
  3608. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3609. };
  3610. // Get next key with
  3611. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  3612. var keys = this.data.hierarchy[ h ].keys;
  3613. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  3614. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  3615. key = key < keys.length - 1 ? key : keys.length - 1;
  3616. } else {
  3617. key = key % keys.length;
  3618. }
  3619. for ( ; key < keys.length; key++ ) {
  3620. if ( keys[ key ][ type ] !== undefined ) {
  3621. return keys[ key ];
  3622. }
  3623. }
  3624. return this.data.hierarchy[ h ].keys[ 0 ];
  3625. };
  3626. // Get previous key with
  3627. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  3628. var keys = this.data.hierarchy[ h ].keys;
  3629. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  3630. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  3631. key = key > 0 ? key : 0;
  3632. } else {
  3633. key = key >= 0 ? key : key + keys.length;
  3634. }
  3635. for ( ; key >= 0; key -- ) {
  3636. if ( keys[ key ][ type ] !== undefined ) {
  3637. return keys[ key ];
  3638. }
  3639. }
  3640. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  3641. };
  3642. /**
  3643. * @author mikael emtinger / http://gomo.se/
  3644. * @author mrdoob / http://mrdoob.com/
  3645. * @author alteredq / http://alteredqualia.com/
  3646. * @author khang duong
  3647. * @author erik kitson
  3648. */
  3649. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  3650. this.root = root;
  3651. this.data = THREE.AnimationHandler.get( data );
  3652. this.hierarchy = THREE.AnimationHandler.parse( root );
  3653. this.currentTime = 0;
  3654. this.timeScale = 0.001;
  3655. this.isPlaying = false;
  3656. this.isPaused = true;
  3657. this.loop = true;
  3658. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  3659. // initialize to first keyframes
  3660. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  3661. var keys = this.data.hierarchy[h].keys,
  3662. sids = this.data.hierarchy[h].sids,
  3663. obj = this.hierarchy[h];
  3664. if ( keys.length && sids ) {
  3665. for ( var s = 0; s < sids.length; s++ ) {
  3666. var sid = sids[ s ],
  3667. next = this.getNextKeyWith( sid, h, 0 );
  3668. if ( next ) {
  3669. next.apply( sid );
  3670. }
  3671. }
  3672. obj.matrixAutoUpdate = false;
  3673. this.data.hierarchy[h].node.updateMatrix();
  3674. obj.matrixWorldNeedsUpdate = true;
  3675. }
  3676. }
  3677. };
  3678. // Play
  3679. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  3680. if( !this.isPlaying ) {
  3681. this.isPlaying = true;
  3682. this.loop = loop !== undefined ? loop : true;
  3683. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  3684. this.startTimeMs = startTimeMS;
  3685. this.startTime = 10000000;
  3686. this.endTime = -this.startTime;
  3687. // reset key cache
  3688. var h, hl = this.hierarchy.length,
  3689. object,
  3690. node;
  3691. for ( h = 0; h < hl; h++ ) {
  3692. object = this.hierarchy[ h ];
  3693. node = this.data.hierarchy[ h ];
  3694. object.useQuaternion = true;
  3695. if ( node.animationCache === undefined ) {
  3696. node.animationCache = {};
  3697. node.animationCache.prevKey = null;
  3698. node.animationCache.nextKey = null;
  3699. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  3700. }
  3701. var keys = this.data.hierarchy[h].keys;
  3702. if (keys.length) {
  3703. node.animationCache.prevKey = keys[ 0 ];
  3704. node.animationCache.nextKey = keys[ 1 ];
  3705. this.startTime = Math.min( keys[0].time, this.startTime );
  3706. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  3707. }
  3708. }
  3709. this.update( 0 );
  3710. }
  3711. this.isPaused = false;
  3712. THREE.AnimationHandler.addToUpdate( this );
  3713. };
  3714. // Pause
  3715. THREE.KeyFrameAnimation.prototype.pause = function() {
  3716. if( this.isPaused ) {
  3717. THREE.AnimationHandler.addToUpdate( this );
  3718. } else {
  3719. THREE.AnimationHandler.removeFromUpdate( this );
  3720. }
  3721. this.isPaused = !this.isPaused;
  3722. };
  3723. // Stop
  3724. THREE.KeyFrameAnimation.prototype.stop = function() {
  3725. this.isPlaying = false;
  3726. this.isPaused = false;
  3727. THREE.AnimationHandler.removeFromUpdate( this );
  3728. // reset JIT matrix and remove cache
  3729. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  3730. var obj = this.hierarchy[ h ];
  3731. var node = this.data.hierarchy[ h ];
  3732. if ( node.animationCache !== undefined ) {
  3733. var original = node.animationCache.originalMatrix;
  3734. if( obj instanceof THREE.Bone ) {
  3735. original.copy( obj.skinMatrix );
  3736. obj.skinMatrix = original;
  3737. } else {
  3738. original.copy( obj.matrix );
  3739. obj.matrix = original;
  3740. }
  3741. delete node.animationCache;
  3742. }
  3743. }
  3744. };
  3745. // Update
  3746. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  3747. // early out
  3748. if( !this.isPlaying ) return;
  3749. // vars
  3750. var prevKey, nextKey;
  3751. var object;
  3752. var node;
  3753. var frame;
  3754. var JIThierarchy = this.data.JIT.hierarchy;
  3755. var currentTime, unloopedCurrentTime;
  3756. var looped;
  3757. // update
  3758. this.currentTime += deltaTimeMS * this.timeScale;
  3759. unloopedCurrentTime = this.currentTime;
  3760. currentTime = this.currentTime = this.currentTime % this.data.length;
  3761. // if looped around, the current time should be based on the startTime
  3762. if ( currentTime < this.startTimeMs ) {
  3763. currentTime = this.currentTime = this.startTimeMs + currentTime;
  3764. }
  3765. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  3766. looped = currentTime < unloopedCurrentTime;
  3767. if ( looped && !this.loop ) {
  3768. // Set the animation to the last keyframes and stop
  3769. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  3770. var keys = this.data.hierarchy[h].keys,
  3771. sids = this.data.hierarchy[h].sids,
  3772. end = keys.length-1,
  3773. obj = this.hierarchy[h];
  3774. if ( keys.length ) {
  3775. for ( var s = 0; s < sids.length; s++ ) {
  3776. var sid = sids[ s ],
  3777. prev = this.getPrevKeyWith( sid, h, end );
  3778. if ( prev ) {
  3779. prev.apply( sid );
  3780. }
  3781. }
  3782. this.data.hierarchy[h].node.updateMatrix();
  3783. obj.matrixWorldNeedsUpdate = true;
  3784. }
  3785. }
  3786. this.stop();
  3787. return;
  3788. }
  3789. // check pre-infinity
  3790. if ( currentTime < this.startTime ) {
  3791. return;
  3792. }
  3793. // update
  3794. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  3795. object = this.hierarchy[ h ];
  3796. node = this.data.hierarchy[ h ];
  3797. var keys = node.keys,
  3798. animationCache = node.animationCache;
  3799. // use JIT?
  3800. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  3801. if( object instanceof THREE.Bone ) {
  3802. object.skinMatrix = JIThierarchy[ h ][ frame ];
  3803. object.matrixWorldNeedsUpdate = false;
  3804. } else {
  3805. object.matrix = JIThierarchy[ h ][ frame ];
  3806. object.matrixWorldNeedsUpdate = true;
  3807. }
  3808. // use interpolation
  3809. } else if ( keys.length ) {
  3810. // make sure so original matrix and not JIT matrix is set
  3811. if ( this.JITCompile && animationCache ) {
  3812. if( object instanceof THREE.Bone ) {
  3813. object.skinMatrix = animationCache.originalMatrix;
  3814. } else {
  3815. object.matrix = animationCache.originalMatrix;
  3816. }
  3817. }
  3818. prevKey = animationCache.prevKey;
  3819. nextKey = animationCache.nextKey;
  3820. if ( prevKey && nextKey ) {
  3821. // switch keys?
  3822. if ( nextKey.time <= unloopedCurrentTime ) {
  3823. // did we loop?
  3824. if ( looped && this.loop ) {
  3825. prevKey = keys[ 0 ];
  3826. nextKey = keys[ 1 ];
  3827. while ( nextKey.time < currentTime ) {
  3828. prevKey = nextKey;
  3829. nextKey = keys[ prevKey.index + 1 ];
  3830. }
  3831. } else if ( !looped ) {
  3832. var lastIndex = keys.length - 1;
  3833. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  3834. prevKey = nextKey;
  3835. nextKey = keys[ prevKey.index + 1 ];
  3836. }
  3837. }
  3838. animationCache.prevKey = prevKey;
  3839. animationCache.nextKey = nextKey;
  3840. }
  3841. if(nextKey.time >= currentTime)
  3842. prevKey.interpolate( nextKey, currentTime );
  3843. else
  3844. prevKey.interpolate( nextKey, nextKey.time);
  3845. }
  3846. this.data.hierarchy[h].node.updateMatrix();
  3847. object.matrixWorldNeedsUpdate = true;
  3848. }
  3849. }
  3850. // update JIT?
  3851. if ( this.JITCompile ) {
  3852. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  3853. this.hierarchy[ 0 ].updateMatrixWorld( true );
  3854. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  3855. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  3856. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  3857. } else {
  3858. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  3859. }
  3860. }
  3861. }
  3862. }
  3863. };
  3864. // Get next key with
  3865. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  3866. var keys = this.data.hierarchy[ h ].keys;
  3867. key = key % keys.length;
  3868. for ( ; key < keys.length; key++ ) {
  3869. if ( keys[ key ].hasTarget( sid ) ) {
  3870. return keys[ key ];
  3871. }
  3872. }
  3873. return keys[ 0 ];
  3874. };
  3875. // Get previous key with
  3876. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  3877. var keys = this.data.hierarchy[ h ].keys;
  3878. key = key >= 0 ? key : key + keys.length;
  3879. for ( ; key >= 0; key-- ) {
  3880. if ( keys[ key ].hasTarget( sid ) ) {
  3881. return keys[ key ];
  3882. }
  3883. }
  3884. return keys[ keys.length - 1 ];
  3885. };
  3886. /**
  3887. * Camera for rendering cube maps
  3888. * - renders scene into axis-aligned cube
  3889. *
  3890. * @author alteredq / http://alteredqualia.com/
  3891. */
  3892. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  3893. THREE.Object3D.call( this );
  3894. var fov = 90, aspect = 1;
  3895. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  3896. cameraPX.up.set( 0, -1, 0 );
  3897. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  3898. this.add( cameraPX );
  3899. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  3900. cameraNX.up.set( 0, -1, 0 );
  3901. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  3902. this.add( cameraNX );
  3903. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  3904. cameraPY.up.set( 0, 0, 1 );
  3905. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  3906. this.add( cameraPY );
  3907. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  3908. cameraNY.up.set( 0, 0, -1 );
  3909. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  3910. this.add( cameraNY );
  3911. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  3912. cameraPZ.up.set( 0, -1, 0 );
  3913. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  3914. this.add( cameraPZ );
  3915. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  3916. cameraNZ.up.set( 0, -1, 0 );
  3917. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  3918. this.add( cameraNZ );
  3919. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  3920. this.updateCubeMap = function ( renderer, scene ) {
  3921. var renderTarget = this.renderTarget;
  3922. var generateMipmaps = renderTarget.generateMipmaps;
  3923. renderTarget.generateMipmaps = false;
  3924. renderTarget.activeCubeFace = 0;
  3925. renderer.render( scene, cameraPX, renderTarget );
  3926. renderTarget.activeCubeFace = 1;
  3927. renderer.render( scene, cameraNX, renderTarget );
  3928. renderTarget.activeCubeFace = 2;
  3929. renderer.render( scene, cameraPY, renderTarget );
  3930. renderTarget.activeCubeFace = 3;
  3931. renderer.render( scene, cameraNY, renderTarget );
  3932. renderTarget.activeCubeFace = 4;
  3933. renderer.render( scene, cameraPZ, renderTarget );
  3934. renderTarget.generateMipmaps = generateMipmaps;
  3935. renderTarget.activeCubeFace = 5;
  3936. renderer.render( scene, cameraNZ, renderTarget );
  3937. };
  3938. };
  3939. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  3940. /*
  3941. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  3942. *
  3943. * A general perpose camera, for setting FOV, Lens Focal Length,
  3944. * and switching between perspective and orthographic views easily.
  3945. * Use this only if you do not wish to manage
  3946. * both a Orthographic and Perspective Camera
  3947. *
  3948. */
  3949. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  3950. THREE.Camera.call( this );
  3951. this.fov = fov;
  3952. this.left = -width / 2;
  3953. this.right = width / 2
  3954. this.top = height / 2;
  3955. this.bottom = -height / 2;
  3956. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  3957. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  3958. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  3959. this.zoom = 1;
  3960. this.toPerspective();
  3961. var aspect = width/height;
  3962. };
  3963. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  3964. THREE.CombinedCamera.prototype.toPerspective = function () {
  3965. // Switches to the Perspective Camera
  3966. this.near = this.cameraP.near;
  3967. this.far = this.cameraP.far;
  3968. this.cameraP.fov = this.fov / this.zoom ;
  3969. this.cameraP.updateProjectionMatrix();
  3970. this.projectionMatrix = this.cameraP.projectionMatrix;
  3971. this.inPerspectiveMode = true;
  3972. this.inOrthographicMode = false;
  3973. };
  3974. THREE.CombinedCamera.prototype.toOrthographic = function () {
  3975. // Switches to the Orthographic camera estimating viewport from Perspective
  3976. var fov = this.fov;
  3977. var aspect = this.cameraP.aspect;
  3978. var near = this.cameraP.near;
  3979. var far = this.cameraP.far;
  3980. // The size that we set is the mid plane of the viewing frustum
  3981. var hyperfocus = ( near + far ) / 2;
  3982. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  3983. var planeHeight = 2 * halfHeight;
  3984. var planeWidth = planeHeight * aspect;
  3985. var halfWidth = planeWidth / 2;
  3986. halfHeight /= this.zoom;
  3987. halfWidth /= this.zoom;
  3988. this.cameraO.left = -halfWidth;
  3989. this.cameraO.right = halfWidth;
  3990. this.cameraO.top = halfHeight;
  3991. this.cameraO.bottom = -halfHeight;
  3992. // this.cameraO.left = -farHalfWidth;
  3993. // this.cameraO.right = farHalfWidth;
  3994. // this.cameraO.top = farHalfHeight;
  3995. // this.cameraO.bottom = -farHalfHeight;
  3996. // this.cameraO.left = this.left / this.zoom;
  3997. // this.cameraO.right = this.right / this.zoom;
  3998. // this.cameraO.top = this.top / this.zoom;
  3999. // this.cameraO.bottom = this.bottom / this.zoom;
  4000. this.cameraO.updateProjectionMatrix();
  4001. this.near = this.cameraO.near;
  4002. this.far = this.cameraO.far;
  4003. this.projectionMatrix = this.cameraO.projectionMatrix;
  4004. this.inPerspectiveMode = false;
  4005. this.inOrthographicMode = true;
  4006. };
  4007. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  4008. this.cameraP.aspect = width / height;
  4009. this.left = -width / 2;
  4010. this.right = width / 2
  4011. this.top = height / 2;
  4012. this.bottom = -height / 2;
  4013. };
  4014. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  4015. this.fov = fov;
  4016. if ( this.inPerspectiveMode ) {
  4017. this.toPerspective();
  4018. } else {
  4019. this.toOrthographic();
  4020. }
  4021. };
  4022. // For mantaining similar API with PerspectiveCamera
  4023. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  4024. if ( this.inPerspectiveMode ) {
  4025. this.toPerspective();
  4026. } else {
  4027. this.toPerspective();
  4028. this.toOrthographic();
  4029. }
  4030. };
  4031. /*
  4032. * Uses Focal Length (in mm) to estimate and set FOV
  4033. * 35mm (fullframe) camera is used if frame size is not specified;
  4034. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  4035. */
  4036. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  4037. frameHeight = frameHeight !== undefined ? frameHeight : 24;
  4038. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  4039. this.setFov( fov );
  4040. return fov;
  4041. };
  4042. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  4043. this.zoom = zoom;
  4044. if ( this.inPerspectiveMode ) {
  4045. this.toPerspective();
  4046. } else {
  4047. this.toOrthographic();
  4048. }
  4049. };
  4050. THREE.CombinedCamera.prototype.toFrontView = function() {
  4051. this.rotation.x = 0;
  4052. this.rotation.y = 0;
  4053. this.rotation.z = 0;
  4054. // should we be modifing the matrix instead?
  4055. this.rotationAutoUpdate = false;
  4056. };
  4057. THREE.CombinedCamera.prototype.toBackView = function() {
  4058. this.rotation.x = 0;
  4059. this.rotation.y = Math.PI;
  4060. this.rotation.z = 0;
  4061. this.rotationAutoUpdate = false;
  4062. };
  4063. THREE.CombinedCamera.prototype.toLeftView = function() {
  4064. this.rotation.x = 0;
  4065. this.rotation.y = - Math.PI / 2;
  4066. this.rotation.z = 0;
  4067. this.rotationAutoUpdate = false;
  4068. };
  4069. THREE.CombinedCamera.prototype.toRightView = function() {
  4070. this.rotation.x = 0;
  4071. this.rotation.y = Math.PI / 2;
  4072. this.rotation.z = 0;
  4073. this.rotationAutoUpdate = false;
  4074. };
  4075. THREE.CombinedCamera.prototype.toTopView = function() {
  4076. this.rotation.x = - Math.PI / 2;
  4077. this.rotation.y = 0;
  4078. this.rotation.z = 0;
  4079. this.rotationAutoUpdate = false;
  4080. };
  4081. THREE.CombinedCamera.prototype.toBottomView = function() {
  4082. this.rotation.x = Math.PI / 2;
  4083. this.rotation.y = 0;
  4084. this.rotation.z = 0;
  4085. this.rotationAutoUpdate = false;
  4086. };
  4087. /**
  4088. * @author mrdoob / http://mrdoob.com/
  4089. * @author alteredq / http://alteredqualia.com/
  4090. * @author paulirish / http://paulirish.com/
  4091. */
  4092. THREE.FirstPersonControls = function ( object, domElement ) {
  4093. this.object = object;
  4094. this.target = new THREE.Vector3( 0, 0, 0 );
  4095. this.domElement = ( domElement !== undefined ) ? domElement : document;
  4096. this.movementSpeed = 1.0;
  4097. this.lookSpeed = 0.005;
  4098. this.lookVertical = true;
  4099. this.autoForward = false;
  4100. // this.invertVertical = false;
  4101. this.activeLook = true;
  4102. this.heightSpeed = false;
  4103. this.heightCoef = 1.0;
  4104. this.heightMin = 0.0;
  4105. this.heightMax = 1.0;
  4106. this.constrainVertical = false;
  4107. this.verticalMin = 0;
  4108. this.verticalMax = Math.PI;
  4109. this.autoSpeedFactor = 0.0;
  4110. this.mouseX = 0;
  4111. this.mouseY = 0;
  4112. this.lat = 0;
  4113. this.lon = 0;
  4114. this.phi = 0;
  4115. this.theta = 0;
  4116. this.moveForward = false;
  4117. this.moveBackward = false;
  4118. this.moveLeft = false;
  4119. this.moveRight = false;
  4120. this.freeze = false;
  4121. this.mouseDragOn = false;
  4122. this.viewHalfX = 0;
  4123. this.viewHalfY = 0;
  4124. if ( this.domElement !== document ) {
  4125. this.domElement.setAttribute( 'tabindex', -1 );
  4126. }
  4127. //
  4128. this.handleResize = function () {
  4129. if ( this.domElement === document ) {
  4130. this.viewHalfX = window.innerWidth / 2;
  4131. this.viewHalfY = window.innerHeight / 2;
  4132. } else {
  4133. this.viewHalfX = this.domElement.offsetWidth / 2;
  4134. this.viewHalfY = this.domElement.offsetHeight / 2;
  4135. }
  4136. };
  4137. this.onMouseDown = function ( event ) {
  4138. if ( this.domElement !== document ) {
  4139. this.domElement.focus();
  4140. }
  4141. event.preventDefault();
  4142. event.stopPropagation();
  4143. if ( this.activeLook ) {
  4144. switch ( event.button ) {
  4145. case 0: this.moveForward = true; break;
  4146. case 2: this.moveBackward = true; break;
  4147. }
  4148. }
  4149. this.mouseDragOn = true;
  4150. };
  4151. this.onMouseUp = function ( event ) {
  4152. event.preventDefault();
  4153. event.stopPropagation();
  4154. if ( this.activeLook ) {
  4155. switch ( event.button ) {
  4156. case 0: this.moveForward = false; break;
  4157. case 2: this.moveBackward = false; break;
  4158. }
  4159. }
  4160. this.mouseDragOn = false;
  4161. };
  4162. this.onMouseMove = function ( event ) {
  4163. if ( this.domElement === document ) {
  4164. this.mouseX = event.pageX - this.viewHalfX;
  4165. this.mouseY = event.pageY - this.viewHalfY;
  4166. } else {
  4167. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  4168. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  4169. }
  4170. };
  4171. this.onKeyDown = function ( event ) {
  4172. //event.preventDefault();
  4173. switch ( event.keyCode ) {
  4174. case 38: /*up*/
  4175. case 87: /*W*/ this.moveForward = true; break;
  4176. case 37: /*left*/
  4177. case 65: /*A*/ this.moveLeft = true; break;
  4178. case 40: /*down*/
  4179. case 83: /*S*/ this.moveBackward = true; break;
  4180. case 39: /*right*/
  4181. case 68: /*D*/ this.moveRight = true; break;
  4182. case 82: /*R*/ this.moveUp = true; break;
  4183. case 70: /*F*/ this.moveDown = true; break;
  4184. case 81: /*Q*/ this.freeze = !this.freeze; break;
  4185. }
  4186. };
  4187. this.onKeyUp = function ( event ) {
  4188. switch( event.keyCode ) {
  4189. case 38: /*up*/
  4190. case 87: /*W*/ this.moveForward = false; break;
  4191. case 37: /*left*/
  4192. case 65: /*A*/ this.moveLeft = false; break;
  4193. case 40: /*down*/
  4194. case 83: /*S*/ this.moveBackward = false; break;
  4195. case 39: /*right*/
  4196. case 68: /*D*/ this.moveRight = false; break;
  4197. case 82: /*R*/ this.moveUp = false; break;
  4198. case 70: /*F*/ this.moveDown = false; break;
  4199. }
  4200. };
  4201. this.update = function( delta ) {
  4202. var actualMoveSpeed = 0;
  4203. if ( this.freeze ) {
  4204. return;
  4205. } else {
  4206. if ( this.heightSpeed ) {
  4207. var y = THREE.Math.clamp( this.object.position.y, this.heightMin, this.heightMax );
  4208. var heightDelta = y - this.heightMin;
  4209. this.autoSpeedFactor = delta * ( heightDelta * this.heightCoef );
  4210. } else {
  4211. this.autoSpeedFactor = 0.0;
  4212. }
  4213. actualMoveSpeed = delta * this.movementSpeed;
  4214. if ( this.moveForward || ( this.autoForward && !this.moveBackward ) ) this.object.translateZ( - ( actualMoveSpeed + this.autoSpeedFactor ) );
  4215. if ( this.moveBackward ) this.object.translateZ( actualMoveSpeed );
  4216. if ( this.moveLeft ) this.object.translateX( - actualMoveSpeed );
  4217. if ( this.moveRight ) this.object.translateX( actualMoveSpeed );
  4218. if ( this.moveUp ) this.object.translateY( actualMoveSpeed );
  4219. if ( this.moveDown ) this.object.translateY( - actualMoveSpeed );
  4220. var actualLookSpeed = delta * this.lookSpeed;
  4221. if ( !this.activeLook ) {
  4222. actualLookSpeed = 0;
  4223. }
  4224. this.lon += this.mouseX * actualLookSpeed;
  4225. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed; // * this.invertVertical?-1:1;
  4226. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  4227. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  4228. this.theta = this.lon * Math.PI / 180;
  4229. var targetPosition = this.target,
  4230. position = this.object.position;
  4231. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  4232. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  4233. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  4234. }
  4235. var verticalLookRatio = 1;
  4236. if ( this.constrainVertical ) {
  4237. verticalLookRatio = Math.PI / ( this.verticalMax - this.verticalMin );
  4238. }
  4239. this.lon += this.mouseX * actualLookSpeed;
  4240. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed * verticalLookRatio;
  4241. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  4242. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  4243. this.theta = this.lon * Math.PI / 180;
  4244. if ( this.constrainVertical ) {
  4245. this.phi = THREE.Math.mapLinear( this.phi, 0, Math.PI, this.verticalMin, this.verticalMax );
  4246. }
  4247. var targetPosition = this.target,
  4248. position = this.object.position;
  4249. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  4250. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  4251. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  4252. this.object.lookAt( targetPosition );
  4253. };
  4254. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  4255. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  4256. this.domElement.addEventListener( 'mousedown', bind( this, this.onMouseDown ), false );
  4257. this.domElement.addEventListener( 'mouseup', bind( this, this.onMouseUp ), false );
  4258. this.domElement.addEventListener( 'keydown', bind( this, this.onKeyDown ), false );
  4259. this.domElement.addEventListener( 'keyup', bind( this, this.onKeyUp ), false );
  4260. function bind( scope, fn ) {
  4261. return function () {
  4262. fn.apply( scope, arguments );
  4263. };
  4264. };
  4265. this.handleResize();
  4266. };
  4267. /**
  4268. * @author alteredq / http://alteredqualia.com/
  4269. */
  4270. THREE.PathControls = function ( object, domElement ) {
  4271. this.object = object;
  4272. this.domElement = ( domElement !== undefined ) ? domElement : document;
  4273. this.id = "PathControls" + THREE.PathControlsIdCounter ++;
  4274. // API
  4275. this.duration = 10 * 1000; // milliseconds
  4276. this.waypoints = [];
  4277. this.useConstantSpeed = true;
  4278. this.resamplingCoef = 50;
  4279. this.debugPath = new THREE.Object3D();
  4280. this.debugDummy = new THREE.Object3D();
  4281. this.animationParent = new THREE.Object3D();
  4282. this.lookSpeed = 0.005;
  4283. this.lookVertical = true;
  4284. this.lookHorizontal = true;
  4285. this.verticalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  4286. this.horizontalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  4287. // internals
  4288. this.target = new THREE.Object3D();
  4289. this.mouseX = 0;
  4290. this.mouseY = 0;
  4291. this.lat = 0;
  4292. this.lon = 0;
  4293. this.phi = 0;
  4294. this.theta = 0;
  4295. var PI2 = Math.PI * 2,
  4296. PI180 = Math.PI / 180;
  4297. this.viewHalfX = 0;
  4298. this.viewHalfY = 0;
  4299. if ( this.domElement !== document ) {
  4300. this.domElement.setAttribute( 'tabindex', -1 );
  4301. }
  4302. // methods
  4303. this.handleResize = function () {
  4304. if ( this.domElement === document ) {
  4305. this.viewHalfX = window.innerWidth / 2;
  4306. this.viewHalfY = window.innerHeight / 2;
  4307. } else {
  4308. this.viewHalfX = this.domElement.offsetWidth / 2;
  4309. this.viewHalfY = this.domElement.offsetHeight / 2;
  4310. }
  4311. };
  4312. this.update = function ( delta ) {
  4313. var srcRange, dstRange;
  4314. if( this.lookHorizontal ) this.lon += this.mouseX * this.lookSpeed * delta;
  4315. if( this.lookVertical ) this.lat -= this.mouseY * this.lookSpeed * delta;
  4316. this.lon = Math.max( 0, Math.min( 360, this.lon ) );
  4317. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  4318. this.phi = ( 90 - this.lat ) * PI180;
  4319. this.theta = this.lon * PI180;
  4320. this.phi = normalize_angle_rad( this.phi );
  4321. // constrain vertical look angle
  4322. srcRange = this.verticalAngleMap.srcRange;
  4323. dstRange = this.verticalAngleMap.dstRange;
  4324. var tmpPhi = THREE.Math.mapLinear( this.phi, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  4325. var tmpPhiFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  4326. var tmpPhiNormalized = ( tmpPhi - dstRange[ 0 ] ) / tmpPhiFullRange;
  4327. this.phi = QuadraticEaseInOut( tmpPhiNormalized ) * tmpPhiFullRange + dstRange[ 0 ];
  4328. // constrain horizontal look angle
  4329. srcRange = this.horizontalAngleMap.srcRange;
  4330. dstRange = this.horizontalAngleMap.dstRange;
  4331. var tmpTheta = THREE.Math.mapLinear( this.theta, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  4332. var tmpThetaFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  4333. var tmpThetaNormalized = ( tmpTheta - dstRange[ 0 ] ) / tmpThetaFullRange;
  4334. this.theta = QuadraticEaseInOut( tmpThetaNormalized ) * tmpThetaFullRange + dstRange[ 0 ];
  4335. var targetPosition = this.target.position,
  4336. position = this.object.position;
  4337. targetPosition.x = 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  4338. targetPosition.y = 100 * Math.cos( this.phi );
  4339. targetPosition.z = 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  4340. this.object.lookAt( this.target.position );
  4341. };
  4342. this.onMouseMove = function ( event ) {
  4343. if ( this.domElement === document ) {
  4344. this.mouseX = event.pageX - this.viewHalfX;
  4345. this.mouseY = event.pageY - this.viewHalfY;
  4346. } else {
  4347. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  4348. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  4349. }
  4350. };
  4351. // utils
  4352. function normalize_angle_rad( a ) {
  4353. var b = a % PI2;
  4354. return b >= 0 ? b : b + PI2;
  4355. };
  4356. function distance( a, b ) {
  4357. var dx = a[ 0 ] - b[ 0 ],
  4358. dy = a[ 1 ] - b[ 1 ],
  4359. dz = a[ 2 ] - b[ 2 ];
  4360. return Math.sqrt( dx * dx + dy * dy + dz * dz );
  4361. };
  4362. function QuadraticEaseInOut ( k ) {
  4363. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k;
  4364. return - 0.5 * ( --k * ( k - 2 ) - 1 );
  4365. };
  4366. function bind( scope, fn ) {
  4367. return function () {
  4368. fn.apply( scope, arguments );
  4369. };
  4370. };
  4371. function initAnimationPath( parent, spline, name, duration ) {
  4372. var animationData = {
  4373. name: name,
  4374. fps: 0.6,
  4375. length: duration,
  4376. hierarchy: []
  4377. };
  4378. var i,
  4379. parentAnimation, childAnimation,
  4380. path = spline.getControlPointsArray(),
  4381. sl = spline.getLength(),
  4382. pl = path.length,
  4383. t = 0,
  4384. first = 0,
  4385. last = pl - 1;
  4386. parentAnimation = { parent: -1, keys: [] };
  4387. parentAnimation.keys[ first ] = { time: 0, pos: path[ first ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  4388. parentAnimation.keys[ last ] = { time: duration, pos: path[ last ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  4389. for ( i = 1; i < pl - 1; i++ ) {
  4390. // real distance (approximation via linear segments)
  4391. t = duration * sl.chunks[ i ] / sl.total;
  4392. // equal distance
  4393. //t = duration * ( i / pl );
  4394. // linear distance
  4395. //t += duration * distance( path[ i ], path[ i - 1 ] ) / sl.total;
  4396. parentAnimation.keys[ i ] = { time: t, pos: path[ i ] };
  4397. }
  4398. animationData.hierarchy[ 0 ] = parentAnimation;
  4399. THREE.AnimationHandler.add( animationData );
  4400. return new THREE.Animation( parent, name, THREE.AnimationHandler.CATMULLROM_FORWARD, false );
  4401. };
  4402. function createSplineGeometry( spline, n_sub ) {
  4403. var i, index, position,
  4404. geometry = new THREE.Geometry();
  4405. for ( i = 0; i < spline.points.length * n_sub; i ++ ) {
  4406. index = i / ( spline.points.length * n_sub );
  4407. position = spline.getPoint( index );
  4408. geometry.vertices[ i ] = new THREE.Vector3( position.x, position.y, position.z );
  4409. }
  4410. return geometry;
  4411. };
  4412. function createPath( parent, spline ) {
  4413. var lineGeo = createSplineGeometry( spline, 10 ),
  4414. particleGeo = createSplineGeometry( spline, 10 ),
  4415. lineMat = new THREE.LineBasicMaterial( { color: 0xff0000, linewidth: 3 } ),
  4416. lineObj = new THREE.Line( lineGeo, lineMat ),
  4417. particleObj = new THREE.ParticleSystem( particleGeo, new THREE.ParticleBasicMaterial( { color: 0xffaa00, size: 3 } ) );
  4418. lineObj.scale.set( 1, 1, 1 );
  4419. parent.add( lineObj );
  4420. particleObj.scale.set( 1, 1, 1 );
  4421. parent.add( particleObj );
  4422. var waypoint,
  4423. geo = new THREE.SphereGeometry( 1, 16, 8 ),
  4424. mat = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  4425. for ( var i = 0; i < spline.points.length; i ++ ) {
  4426. waypoint = new THREE.Mesh( geo, mat );
  4427. waypoint.position.copy( spline.points[ i ] );
  4428. parent.add( waypoint );
  4429. }
  4430. };
  4431. this.init = function ( ) {
  4432. // constructor
  4433. this.spline = new THREE.Spline();
  4434. this.spline.initFromArray( this.waypoints );
  4435. if ( this.useConstantSpeed ) {
  4436. this.spline.reparametrizeByArcLength( this.resamplingCoef );
  4437. }
  4438. if ( this.createDebugDummy ) {
  4439. var dummyParentMaterial = new THREE.MeshLambertMaterial( { color: 0x0077ff } ),
  4440. dummyChildMaterial = new THREE.MeshLambertMaterial( { color: 0x00ff00 } ),
  4441. dummyParentGeo = new THREE.CubeGeometry( 10, 10, 20 ),
  4442. dummyChildGeo = new THREE.CubeGeometry( 2, 2, 10 );
  4443. this.animationParent = new THREE.Mesh( dummyParentGeo, dummyParentMaterial );
  4444. var dummyChild = new THREE.Mesh( dummyChildGeo, dummyChildMaterial );
  4445. dummyChild.position.set( 0, 10, 0 );
  4446. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  4447. this.animationParent.add( this.object );
  4448. this.animationParent.add( this.target );
  4449. this.animationParent.add( dummyChild );
  4450. } else {
  4451. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  4452. this.animationParent.add( this.target );
  4453. this.animationParent.add( this.object );
  4454. }
  4455. if ( this.createDebugPath ) {
  4456. createPath( this.debugPath, this.spline );
  4457. }
  4458. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  4459. };
  4460. this.handleResize();
  4461. };
  4462. THREE.PathControlsIdCounter = 0;
  4463. /**
  4464. * @author James Baicoianu / http://www.baicoianu.com/
  4465. */
  4466. THREE.FlyControls = function ( object, domElement ) {
  4467. this.object = object;
  4468. this.domElement = ( domElement !== undefined ) ? domElement : document;
  4469. if ( domElement ) this.domElement.setAttribute( 'tabindex', -1 );
  4470. // API
  4471. this.movementSpeed = 1.0;
  4472. this.rollSpeed = 0.005;
  4473. this.dragToLook = false;
  4474. this.autoForward = false;
  4475. // disable default target object behavior
  4476. this.object.useQuaternion = true;
  4477. // internals
  4478. this.tmpQuaternion = new THREE.Quaternion();
  4479. this.mouseStatus = 0;
  4480. this.moveState = { up: 0, down: 0, left: 0, right: 0, forward: 0, back: 0, pitchUp: 0, pitchDown: 0, yawLeft: 0, yawRight: 0, rollLeft: 0, rollRight: 0 };
  4481. this.moveVector = new THREE.Vector3( 0, 0, 0 );
  4482. this.rotationVector = new THREE.Vector3( 0, 0, 0 );
  4483. this.handleEvent = function ( event ) {
  4484. if ( typeof this[ event.type ] == 'function' ) {
  4485. this[ event.type ]( event );
  4486. }
  4487. };
  4488. this.keydown = function( event ) {
  4489. if ( event.altKey ) {
  4490. return;
  4491. }
  4492. //event.preventDefault();
  4493. switch ( event.keyCode ) {
  4494. case 16: /* shift */ this.movementSpeedMultiplier = .1; break;
  4495. case 87: /*W*/ this.moveState.forward = 1; break;
  4496. case 83: /*S*/ this.moveState.back = 1; break;
  4497. case 65: /*A*/ this.moveState.left = 1; break;
  4498. case 68: /*D*/ this.moveState.right = 1; break;
  4499. case 82: /*R*/ this.moveState.up = 1; break;
  4500. case 70: /*F*/ this.moveState.down = 1; break;
  4501. case 38: /*up*/ this.moveState.pitchUp = 1; break;
  4502. case 40: /*down*/ this.moveState.pitchDown = 1; break;
  4503. case 37: /*left*/ this.moveState.yawLeft = 1; break;
  4504. case 39: /*right*/ this.moveState.yawRight = 1; break;
  4505. case 81: /*Q*/ this.moveState.rollLeft = 1; break;
  4506. case 69: /*E*/ this.moveState.rollRight = 1; break;
  4507. }
  4508. this.updateMovementVector();
  4509. this.updateRotationVector();
  4510. };
  4511. this.keyup = function( event ) {
  4512. switch( event.keyCode ) {
  4513. case 16: /* shift */ this.movementSpeedMultiplier = 1; break;
  4514. case 87: /*W*/ this.moveState.forward = 0; break;
  4515. case 83: /*S*/ this.moveState.back = 0; break;
  4516. case 65: /*A*/ this.moveState.left = 0; break;
  4517. case 68: /*D*/ this.moveState.right = 0; break;
  4518. case 82: /*R*/ this.moveState.up = 0; break;
  4519. case 70: /*F*/ this.moveState.down = 0; break;
  4520. case 38: /*up*/ this.moveState.pitchUp = 0; break;
  4521. case 40: /*down*/ this.moveState.pitchDown = 0; break;
  4522. case 37: /*left*/ this.moveState.yawLeft = 0; break;
  4523. case 39: /*right*/ this.moveState.yawRight = 0; break;
  4524. case 81: /*Q*/ this.moveState.rollLeft = 0; break;
  4525. case 69: /*E*/ this.moveState.rollRight = 0; break;
  4526. }
  4527. this.updateMovementVector();
  4528. this.updateRotationVector();
  4529. };
  4530. this.mousedown = function( event ) {
  4531. if ( this.domElement !== document ) {
  4532. this.domElement.focus();
  4533. }
  4534. event.preventDefault();
  4535. event.stopPropagation();
  4536. if ( this.dragToLook ) {
  4537. this.mouseStatus ++;
  4538. } else {
  4539. switch ( event.button ) {
  4540. case 0: this.object.moveForward = true; break;
  4541. case 2: this.object.moveBackward = true; break;
  4542. }
  4543. }
  4544. };
  4545. this.mousemove = function( event ) {
  4546. if ( !this.dragToLook || this.mouseStatus > 0 ) {
  4547. var container = this.getContainerDimensions();
  4548. var halfWidth = container.size[ 0 ] / 2;
  4549. var halfHeight = container.size[ 1 ] / 2;
  4550. this.moveState.yawLeft = - ( ( event.pageX - container.offset[ 0 ] ) - halfWidth ) / halfWidth;
  4551. this.moveState.pitchDown = ( ( event.pageY - container.offset[ 1 ] ) - halfHeight ) / halfHeight;
  4552. this.updateRotationVector();
  4553. }
  4554. };
  4555. this.mouseup = function( event ) {
  4556. event.preventDefault();
  4557. event.stopPropagation();
  4558. if ( this.dragToLook ) {
  4559. this.mouseStatus --;
  4560. this.moveState.yawLeft = this.moveState.pitchDown = 0;
  4561. } else {
  4562. switch ( event.button ) {
  4563. case 0: this.moveForward = false; break;
  4564. case 2: this.moveBackward = false; break;
  4565. }
  4566. }
  4567. this.updateRotationVector();
  4568. };
  4569. this.update = function( delta ) {
  4570. var moveMult = delta * this.movementSpeed;
  4571. var rotMult = delta * this.rollSpeed;
  4572. this.object.translateX( this.moveVector.x * moveMult );
  4573. this.object.translateY( this.moveVector.y * moveMult );
  4574. this.object.translateZ( this.moveVector.z * moveMult );
  4575. this.tmpQuaternion.set( this.rotationVector.x * rotMult, this.rotationVector.y * rotMult, this.rotationVector.z * rotMult, 1 ).normalize();
  4576. this.object.quaternion.multiplySelf( this.tmpQuaternion );
  4577. this.object.matrix.setPosition( this.object.position );
  4578. this.object.matrix.setRotationFromQuaternion( this.object.quaternion );
  4579. this.object.matrixWorldNeedsUpdate = true;
  4580. };
  4581. this.updateMovementVector = function() {
  4582. var forward = ( this.moveState.forward || ( this.autoForward && !this.moveState.back ) ) ? 1 : 0;
  4583. this.moveVector.x = ( -this.moveState.left + this.moveState.right );
  4584. this.moveVector.y = ( -this.moveState.down + this.moveState.up );
  4585. this.moveVector.z = ( -forward + this.moveState.back );
  4586. //console.log( 'move:', [ this.moveVector.x, this.moveVector.y, this.moveVector.z ] );
  4587. };
  4588. this.updateRotationVector = function() {
  4589. this.rotationVector.x = ( -this.moveState.pitchDown + this.moveState.pitchUp );
  4590. this.rotationVector.y = ( -this.moveState.yawRight + this.moveState.yawLeft );
  4591. this.rotationVector.z = ( -this.moveState.rollRight + this.moveState.rollLeft );
  4592. //console.log( 'rotate:', [ this.rotationVector.x, this.rotationVector.y, this.rotationVector.z ] );
  4593. };
  4594. this.getContainerDimensions = function() {
  4595. if ( this.domElement != document ) {
  4596. return {
  4597. size : [ this.domElement.offsetWidth, this.domElement.offsetHeight ],
  4598. offset : [ this.domElement.offsetLeft, this.domElement.offsetTop ]
  4599. };
  4600. } else {
  4601. return {
  4602. size : [ window.innerWidth, window.innerHeight ],
  4603. offset : [ 0, 0 ]
  4604. };
  4605. }
  4606. };
  4607. function bind( scope, fn ) {
  4608. return function () {
  4609. fn.apply( scope, arguments );
  4610. };
  4611. };
  4612. this.domElement.addEventListener( 'mousemove', bind( this, this.mousemove ), false );
  4613. this.domElement.addEventListener( 'mousedown', bind( this, this.mousedown ), false );
  4614. this.domElement.addEventListener( 'mouseup', bind( this, this.mouseup ), false );
  4615. this.domElement.addEventListener( 'keydown', bind( this, this.keydown ), false );
  4616. this.domElement.addEventListener( 'keyup', bind( this, this.keyup ), false );
  4617. this.updateMovementVector();
  4618. this.updateRotationVector();
  4619. };
  4620. /**
  4621. * @author mikael emtinger / http://gomo.se/
  4622. * @author alteredq / http://alteredqualia.com/
  4623. */
  4624. THREE.RollControls = function ( object, domElement ) {
  4625. this.object = object;
  4626. this.domElement = ( domElement !== undefined ) ? domElement : document;
  4627. // API
  4628. this.mouseLook = true;
  4629. this.autoForward = false;
  4630. this.lookSpeed = 1;
  4631. this.movementSpeed = 1;
  4632. this.rollSpeed = 1;
  4633. this.constrainVertical = [ -0.9, 0.9 ];
  4634. // disable default target object behavior
  4635. this.object.matrixAutoUpdate = false;
  4636. // internals
  4637. this.forward = new THREE.Vector3( 0, 0, 1 );
  4638. this.roll = 0;
  4639. var xTemp = new THREE.Vector3();
  4640. var yTemp = new THREE.Vector3();
  4641. var zTemp = new THREE.Vector3();
  4642. var rollMatrix = new THREE.Matrix4();
  4643. var doRoll = false, rollDirection = 1, forwardSpeed = 0, sideSpeed = 0, upSpeed = 0;
  4644. var mouseX = 0, mouseY = 0;
  4645. var windowHalfX = 0;
  4646. var windowHalfY = 0;
  4647. //
  4648. this.handleResize = function () {
  4649. windowHalfX = window.innerWidth / 2;
  4650. windowHalfY = window.innerHeight / 2;
  4651. };
  4652. // custom update
  4653. this.update = function ( delta ) {
  4654. if ( this.mouseLook ) {
  4655. var actualLookSpeed = delta * this.lookSpeed;
  4656. this.rotateHorizontally( actualLookSpeed * mouseX );
  4657. this.rotateVertically( actualLookSpeed * mouseY );
  4658. }
  4659. var actualSpeed = delta * this.movementSpeed;
  4660. var forwardOrAuto = ( forwardSpeed > 0 || ( this.autoForward && ! ( forwardSpeed < 0 ) ) ) ? 1 : forwardSpeed;
  4661. this.object.translateZ( -actualSpeed * forwardOrAuto );
  4662. this.object.translateX( actualSpeed * sideSpeed );
  4663. this.object.translateY( actualSpeed * upSpeed );
  4664. if( doRoll ) {
  4665. this.roll += this.rollSpeed * delta * rollDirection;
  4666. }
  4667. // cap forward up / down
  4668. if( this.forward.y > this.constrainVertical[ 1 ] ) {
  4669. this.forward.y = this.constrainVertical[ 1 ];
  4670. this.forward.normalize();
  4671. } else if( this.forward.y < this.constrainVertical[ 0 ] ) {
  4672. this.forward.y = this.constrainVertical[ 0 ];
  4673. this.forward.normalize();
  4674. }
  4675. // construct unrolled camera matrix
  4676. zTemp.copy( this.forward );
  4677. yTemp.set( 0, 1, 0 );
  4678. xTemp.cross( yTemp, zTemp ).normalize();
  4679. yTemp.cross( zTemp, xTemp ).normalize();
  4680. this.object.matrix.elements[0] = xTemp.x; this.object.matrix.elements[4] = yTemp.x; this.object.matrix.elements[8] = zTemp.x;
  4681. this.object.matrix.elements[1] = xTemp.y; this.object.matrix.elements[5] = yTemp.y; this.object.matrix.elements[9] = zTemp.y;
  4682. this.object.matrix.elements[2] = xTemp.z; this.object.matrix.elements[6] = yTemp.z; this.object.matrix.elements[10] = zTemp.z;
  4683. // calculate roll matrix
  4684. rollMatrix.identity();
  4685. rollMatrix.elements[0] = Math.cos( this.roll ); rollMatrix.elements[4] = -Math.sin( this.roll );
  4686. rollMatrix.elements[1] = Math.sin( this.roll ); rollMatrix.elements[5] = Math.cos( this.roll );
  4687. // multiply camera with roll
  4688. this.object.matrix.multiplySelf( rollMatrix );
  4689. this.object.matrixWorldNeedsUpdate = true;
  4690. // set position
  4691. this.object.matrix.elements[12] = this.object.position.x;
  4692. this.object.matrix.elements[13] = this.object.position.y;
  4693. this.object.matrix.elements[14] = this.object.position.z;
  4694. };
  4695. this.translateX = function ( distance ) {
  4696. this.object.position.x += this.object.matrix.elements[0] * distance;
  4697. this.object.position.y += this.object.matrix.elements[1] * distance;
  4698. this.object.position.z += this.object.matrix.elements[2] * distance;
  4699. };
  4700. this.translateY = function ( distance ) {
  4701. this.object.position.x += this.object.matrix.elements[4] * distance;
  4702. this.object.position.y += this.object.matrix.elements[5] * distance;
  4703. this.object.position.z += this.object.matrix.elements[6] * distance;
  4704. };
  4705. this.translateZ = function ( distance ) {
  4706. this.object.position.x -= this.object.matrix.elements[8] * distance;
  4707. this.object.position.y -= this.object.matrix.elements[9] * distance;
  4708. this.object.position.z -= this.object.matrix.elements[10] * distance;
  4709. };
  4710. this.rotateHorizontally = function ( amount ) {
  4711. // please note that the amount is NOT degrees, but a scale value
  4712. xTemp.set( this.object.matrix.elements[0], this.object.matrix.elements[1], this.object.matrix.elements[2] );
  4713. xTemp.multiplyScalar( amount );
  4714. this.forward.subSelf( xTemp );
  4715. this.forward.normalize();
  4716. };
  4717. this.rotateVertically = function ( amount ) {
  4718. // please note that the amount is NOT degrees, but a scale value
  4719. yTemp.set( this.object.matrix.elements[4], this.object.matrix.elements[5], this.object.matrix.elements[6] );
  4720. yTemp.multiplyScalar( amount );
  4721. this.forward.addSelf( yTemp );
  4722. this.forward.normalize();
  4723. };
  4724. function onKeyDown( event ) {
  4725. //event.preventDefault();
  4726. switch ( event.keyCode ) {
  4727. case 38: /*up*/
  4728. case 87: /*W*/ forwardSpeed = 1; break;
  4729. case 37: /*left*/
  4730. case 65: /*A*/ sideSpeed = -1; break;
  4731. case 40: /*down*/
  4732. case 83: /*S*/ forwardSpeed = -1; break;
  4733. case 39: /*right*/
  4734. case 68: /*D*/ sideSpeed = 1; break;
  4735. case 81: /*Q*/ doRoll = true; rollDirection = 1; break;
  4736. case 69: /*E*/ doRoll = true; rollDirection = -1; break;
  4737. case 82: /*R*/ upSpeed = 1; break;
  4738. case 70: /*F*/ upSpeed = -1; break;
  4739. }
  4740. };
  4741. function onKeyUp( event ) {
  4742. switch( event.keyCode ) {
  4743. case 38: /*up*/
  4744. case 87: /*W*/ forwardSpeed = 0; break;
  4745. case 37: /*left*/
  4746. case 65: /*A*/ sideSpeed = 0; break;
  4747. case 40: /*down*/
  4748. case 83: /*S*/ forwardSpeed = 0; break;
  4749. case 39: /*right*/
  4750. case 68: /*D*/ sideSpeed = 0; break;
  4751. case 81: /*Q*/ doRoll = false; break;
  4752. case 69: /*E*/ doRoll = false; break;
  4753. case 82: /*R*/ upSpeed = 0; break;
  4754. case 70: /*F*/ upSpeed = 0; break;
  4755. }
  4756. };
  4757. function onMouseMove( event ) {
  4758. mouseX = ( event.clientX - windowHalfX ) / window.innerWidth;
  4759. mouseY = ( event.clientY - windowHalfY ) / window.innerHeight;
  4760. };
  4761. function onMouseDown ( event ) {
  4762. event.preventDefault();
  4763. event.stopPropagation();
  4764. switch ( event.button ) {
  4765. case 0: forwardSpeed = 1; break;
  4766. case 2: forwardSpeed = -1; break;
  4767. }
  4768. };
  4769. function onMouseUp ( event ) {
  4770. event.preventDefault();
  4771. event.stopPropagation();
  4772. switch ( event.button ) {
  4773. case 0: forwardSpeed = 0; break;
  4774. case 2: forwardSpeed = 0; break;
  4775. }
  4776. };
  4777. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  4778. this.domElement.addEventListener( 'mousemove', onMouseMove, false );
  4779. this.domElement.addEventListener( 'mousedown', onMouseDown, false );
  4780. this.domElement.addEventListener( 'mouseup', onMouseUp, false );
  4781. this.domElement.addEventListener( 'keydown', onKeyDown, false );
  4782. this.domElement.addEventListener( 'keyup', onKeyUp, false );
  4783. this.handleResize();
  4784. };
  4785. /**
  4786. * @author Eberhard Graether / http://egraether.com/
  4787. */
  4788. THREE.TrackballControls = function ( object, domElement ) {
  4789. THREE.EventTarget.call( this );
  4790. var _this = this,
  4791. STATE = { NONE : -1, ROTATE : 0, ZOOM : 1, PAN : 2 };
  4792. this.object = object;
  4793. this.domElement = ( domElement !== undefined ) ? domElement : document;
  4794. // API
  4795. this.enabled = true;
  4796. this.screen = { width: 0, height: 0, offsetLeft: 0, offsetTop: 0 };
  4797. this.radius = ( this.screen.width + this.screen.height ) / 4;
  4798. this.rotateSpeed = 1.0;
  4799. this.zoomSpeed = 1.2;
  4800. this.panSpeed = 0.3;
  4801. this.noRotate = false;
  4802. this.noZoom = false;
  4803. this.noPan = false;
  4804. this.staticMoving = false;
  4805. this.dynamicDampingFactor = 0.2;
  4806. this.minDistance = 0;
  4807. this.maxDistance = Infinity;
  4808. this.keys = [ 65 /*A*/, 83 /*S*/, 68 /*D*/ ];
  4809. // internals
  4810. this.target = new THREE.Vector3();
  4811. var lastPosition = new THREE.Vector3();
  4812. var _keyPressed = false,
  4813. _state = STATE.NONE,
  4814. _eye = new THREE.Vector3(),
  4815. _rotateStart = new THREE.Vector3(),
  4816. _rotateEnd = new THREE.Vector3(),
  4817. _zoomStart = new THREE.Vector2(),
  4818. _zoomEnd = new THREE.Vector2(),
  4819. _panStart = new THREE.Vector2(),
  4820. _panEnd = new THREE.Vector2();
  4821. // events
  4822. var changeEvent = { type: 'change' };
  4823. // methods
  4824. this.handleResize = function () {
  4825. this.screen.width = window.innerWidth;
  4826. this.screen.height = window.innerHeight;
  4827. this.screen.offsetLeft = 0;
  4828. this.screen.offsetTop = 0;
  4829. this.radius = ( this.screen.width + this.screen.height ) / 4;
  4830. };
  4831. this.handleEvent = function ( event ) {
  4832. if ( typeof this[ event.type ] == 'function' ) {
  4833. this[ event.type ]( event );
  4834. }
  4835. };
  4836. this.getMouseOnScreen = function ( clientX, clientY ) {
  4837. return new THREE.Vector2(
  4838. ( clientX - _this.screen.offsetLeft ) / _this.radius * 0.5,
  4839. ( clientY - _this.screen.offsetTop ) / _this.radius * 0.5
  4840. );
  4841. };
  4842. this.getMouseProjectionOnBall = function ( clientX, clientY ) {
  4843. var mouseOnBall = new THREE.Vector3(
  4844. ( clientX - _this.screen.width * 0.5 - _this.screen.offsetLeft ) / _this.radius,
  4845. ( _this.screen.height * 0.5 + _this.screen.offsetTop - clientY ) / _this.radius,
  4846. 0.0
  4847. );
  4848. var length = mouseOnBall.length();
  4849. if ( length > 1.0 ) {
  4850. mouseOnBall.normalize();
  4851. } else {
  4852. mouseOnBall.z = Math.sqrt( 1.0 - length * length );
  4853. }
  4854. _eye.copy( _this.object.position ).subSelf( _this.target );
  4855. var projection = _this.object.up.clone().setLength( mouseOnBall.y );
  4856. projection.addSelf( _this.object.up.clone().crossSelf( _eye ).setLength( mouseOnBall.x ) );
  4857. projection.addSelf( _eye.setLength( mouseOnBall.z ) );
  4858. return projection;
  4859. };
  4860. this.rotateCamera = function () {
  4861. var angle = Math.acos( _rotateStart.dot( _rotateEnd ) / _rotateStart.length() / _rotateEnd.length() );
  4862. if ( angle ) {
  4863. var axis = ( new THREE.Vector3() ).cross( _rotateStart, _rotateEnd ).normalize(),
  4864. quaternion = new THREE.Quaternion();
  4865. angle *= _this.rotateSpeed;
  4866. quaternion.setFromAxisAngle( axis, -angle );
  4867. quaternion.multiplyVector3( _eye );
  4868. quaternion.multiplyVector3( _this.object.up );
  4869. quaternion.multiplyVector3( _rotateEnd );
  4870. if ( _this.staticMoving ) {
  4871. _rotateStart = _rotateEnd;
  4872. } else {
  4873. quaternion.setFromAxisAngle( axis, angle * ( _this.dynamicDampingFactor - 1.0 ) );
  4874. quaternion.multiplyVector3( _rotateStart );
  4875. }
  4876. }
  4877. };
  4878. this.zoomCamera = function () {
  4879. var factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * _this.zoomSpeed;
  4880. if ( factor !== 1.0 && factor > 0.0 ) {
  4881. _eye.multiplyScalar( factor );
  4882. if ( _this.staticMoving ) {
  4883. _zoomStart = _zoomEnd;
  4884. } else {
  4885. _zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor;
  4886. }
  4887. }
  4888. };
  4889. this.panCamera = function () {
  4890. var mouseChange = _panEnd.clone().subSelf( _panStart );
  4891. if ( mouseChange.lengthSq() ) {
  4892. mouseChange.multiplyScalar( _eye.length() * _this.panSpeed );
  4893. var pan = _eye.clone().crossSelf( _this.object.up ).setLength( mouseChange.x );
  4894. pan.addSelf( _this.object.up.clone().setLength( mouseChange.y ) );
  4895. _this.object.position.addSelf( pan );
  4896. _this.target.addSelf( pan );
  4897. if ( _this.staticMoving ) {
  4898. _panStart = _panEnd;
  4899. } else {
  4900. _panStart.addSelf( mouseChange.sub( _panEnd, _panStart ).multiplyScalar( _this.dynamicDampingFactor ) );
  4901. }
  4902. }
  4903. };
  4904. this.checkDistances = function () {
  4905. if ( !_this.noZoom || !_this.noPan ) {
  4906. if ( _this.object.position.lengthSq() > _this.maxDistance * _this.maxDistance ) {
  4907. _this.object.position.setLength( _this.maxDistance );
  4908. }
  4909. if ( _eye.lengthSq() < _this.minDistance * _this.minDistance ) {
  4910. _this.object.position.add( _this.target, _eye.setLength( _this.minDistance ) );
  4911. }
  4912. }
  4913. };
  4914. this.update = function () {
  4915. _eye.copy( _this.object.position ).subSelf( _this.target );
  4916. if ( !_this.noRotate ) {
  4917. _this.rotateCamera();
  4918. }
  4919. if ( !_this.noZoom ) {
  4920. _this.zoomCamera();
  4921. }
  4922. if ( !_this.noPan ) {
  4923. _this.panCamera();
  4924. }
  4925. _this.object.position.add( _this.target, _eye );
  4926. _this.checkDistances();
  4927. _this.object.lookAt( _this.target );
  4928. if ( lastPosition.distanceToSquared( _this.object.position ) > 0 ) {
  4929. _this.dispatchEvent( changeEvent );
  4930. lastPosition.copy( _this.object.position );
  4931. }
  4932. };
  4933. // listeners
  4934. function keydown( event ) {
  4935. if ( ! _this.enabled ) return;
  4936. //event.preventDefault();
  4937. if ( _state !== STATE.NONE ) {
  4938. return;
  4939. } else if ( event.keyCode === _this.keys[ STATE.ROTATE ] && !_this.noRotate ) {
  4940. _state = STATE.ROTATE;
  4941. } else if ( event.keyCode === _this.keys[ STATE.ZOOM ] && !_this.noZoom ) {
  4942. _state = STATE.ZOOM;
  4943. } else if ( event.keyCode === _this.keys[ STATE.PAN ] && !_this.noPan ) {
  4944. _state = STATE.PAN;
  4945. }
  4946. if ( _state !== STATE.NONE ) {
  4947. _keyPressed = true;
  4948. }
  4949. }
  4950. function keyup( event ) {
  4951. if ( ! _this.enabled ) return;
  4952. if ( _state !== STATE.NONE ) {
  4953. _state = STATE.NONE;
  4954. }
  4955. }
  4956. function mousedown( event ) {
  4957. if ( ! _this.enabled ) return;
  4958. event.preventDefault();
  4959. event.stopPropagation();
  4960. if ( _state === STATE.NONE ) {
  4961. _state = event.button;
  4962. if ( _state === STATE.ROTATE && !_this.noRotate ) {
  4963. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  4964. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  4965. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  4966. } else if ( !this.noPan ) {
  4967. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  4968. }
  4969. }
  4970. }
  4971. function mousemove( event ) {
  4972. if ( ! _this.enabled ) return;
  4973. if ( _keyPressed ) {
  4974. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  4975. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  4976. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  4977. _keyPressed = false;
  4978. }
  4979. if ( _state === STATE.NONE ) {
  4980. return;
  4981. } else if ( _state === STATE.ROTATE && !_this.noRotate ) {
  4982. _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  4983. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  4984. _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  4985. } else if ( _state === STATE.PAN && !_this.noPan ) {
  4986. _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  4987. }
  4988. }
  4989. function mouseup( event ) {
  4990. if ( ! _this.enabled ) return;
  4991. event.preventDefault();
  4992. event.stopPropagation();
  4993. _state = STATE.NONE;
  4994. }
  4995. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  4996. this.domElement.addEventListener( 'mousemove', mousemove, false );
  4997. this.domElement.addEventListener( 'mousedown', mousedown, false );
  4998. this.domElement.addEventListener( 'mouseup', mouseup, false );
  4999. // this.domElement.addEventListener( 'DOMMouseScroll', mousewheel, false );
  5000. // this.domElement.addEventListener( 'mousewheel', mousewheel, false );
  5001. window.addEventListener( 'keydown', keydown, false );
  5002. window.addEventListener( 'keyup', keyup, false );
  5003. this.handleResize();
  5004. };
  5005. /**
  5006. * @author qiao / https://github.com/qiao
  5007. * @author mrdoob / http://mrdoob.com
  5008. * @author alteredq / http://alteredqualia.com/
  5009. */
  5010. THREE.OrbitControls = function ( object, domElement ) {
  5011. THREE.EventTarget.call( this );
  5012. this.object = object;
  5013. this.domElement = ( domElement !== undefined ) ? domElement : document;
  5014. // API
  5015. this.center = new THREE.Vector3();
  5016. this.userZoom = true;
  5017. this.userZoomSpeed = 1.0;
  5018. this.userRotate = true;
  5019. this.userRotateSpeed = 1.0;
  5020. this.autoRotate = false;
  5021. this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
  5022. // internals
  5023. var scope = this;
  5024. var EPS = 0.000001;
  5025. var PIXELS_PER_ROUND = 1800;
  5026. var rotateStart = new THREE.Vector2();
  5027. var rotateEnd = new THREE.Vector2();
  5028. var rotateDelta = new THREE.Vector2();
  5029. var zoomStart = new THREE.Vector2();
  5030. var zoomEnd = new THREE.Vector2();
  5031. var zoomDelta = new THREE.Vector2();
  5032. var phiDelta = 0;
  5033. var thetaDelta = 0;
  5034. var scale = 1;
  5035. var lastPosition = new THREE.Vector3();
  5036. var STATE = { NONE : -1, ROTATE : 0, ZOOM : 1 };
  5037. var state = STATE.NONE;
  5038. // events
  5039. var changeEvent = { type: 'change' };
  5040. this.rotateLeft = function ( angle ) {
  5041. if ( angle === undefined ) {
  5042. angle = getAutoRotationAngle();
  5043. }
  5044. thetaDelta -= angle;
  5045. };
  5046. this.rotateRight = function ( angle ) {
  5047. if ( angle === undefined ) {
  5048. angle = getAutoRotationAngle();
  5049. }
  5050. thetaDelta += angle;
  5051. };
  5052. this.rotateUp = function ( angle ) {
  5053. if ( angle === undefined ) {
  5054. angle = getAutoRotationAngle();
  5055. }
  5056. phiDelta -= angle;
  5057. };
  5058. this.rotateDown = function ( angle ) {
  5059. if ( angle === undefined ) {
  5060. angle = getAutoRotationAngle();
  5061. }
  5062. phiDelta += angle;
  5063. };
  5064. this.zoomIn = function ( zoomScale ) {
  5065. if ( zoomScale === undefined ) {
  5066. zoomScale = getZoomScale();
  5067. }
  5068. scale /= zoomScale;
  5069. };
  5070. this.zoomOut = function ( zoomScale ) {
  5071. if ( zoomScale === undefined ) {
  5072. zoomScale = getZoomScale();
  5073. }
  5074. scale *= zoomScale;
  5075. };
  5076. this.update = function () {
  5077. var position = this.object.position;
  5078. var offset = position.clone().subSelf( this.center )
  5079. // angle from z-axis around y-axis
  5080. var theta = Math.atan2( offset.x, offset.z );
  5081. // angle from y-axis
  5082. var phi = Math.atan2( Math.sqrt( offset.x * offset.x + offset.z * offset.z ), offset.y );
  5083. if ( this.autoRotate ) {
  5084. this.rotateLeft( getAutoRotationAngle() );
  5085. }
  5086. theta += thetaDelta;
  5087. phi += phiDelta;
  5088. // restrict phi to be betwee EPS and PI-EPS
  5089. phi = Math.max( EPS, Math.min( Math.PI - EPS, phi ) );
  5090. var radius = offset.length();
  5091. offset.x = radius * Math.sin( phi ) * Math.sin( theta );
  5092. offset.y = radius * Math.cos( phi );
  5093. offset.z = radius * Math.sin( phi ) * Math.cos( theta );
  5094. offset.multiplyScalar( scale );
  5095. position.copy( this.center ).addSelf( offset );
  5096. this.object.lookAt( this.center );
  5097. thetaDelta = 0;
  5098. phiDelta = 0;
  5099. scale = 1;
  5100. if ( lastPosition.distanceTo( this.object.position ) > 0 ) {
  5101. this.dispatchEvent( changeEvent );
  5102. lastPosition.copy( this.object.position );
  5103. }
  5104. };
  5105. function getAutoRotationAngle() {
  5106. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  5107. }
  5108. function getZoomScale() {
  5109. return Math.pow( 0.95, scope.userZoomSpeed );
  5110. }
  5111. function onMouseDown( event ) {
  5112. if ( !scope.userRotate ) return;
  5113. event.preventDefault();
  5114. if ( event.button === 0 || event.button === 2 ) {
  5115. state = STATE.ROTATE;
  5116. rotateStart.set( event.clientX, event.clientY );
  5117. } else if ( event.button === 1 ) {
  5118. state = STATE.ZOOM;
  5119. zoomStart.set( event.clientX, event.clientY );
  5120. }
  5121. document.addEventListener( 'mousemove', onMouseMove, false );
  5122. document.addEventListener( 'mouseup', onMouseUp, false );
  5123. }
  5124. function onMouseMove( event ) {
  5125. event.preventDefault();
  5126. if ( state === STATE.ROTATE ) {
  5127. rotateEnd.set( event.clientX, event.clientY );
  5128. rotateDelta.sub( rotateEnd, rotateStart );
  5129. scope.rotateLeft( 2 * Math.PI * rotateDelta.x / PIXELS_PER_ROUND * scope.userRotateSpeed );
  5130. scope.rotateUp( 2 * Math.PI * rotateDelta.y / PIXELS_PER_ROUND * scope.userRotateSpeed );
  5131. rotateStart.copy( rotateEnd );
  5132. } else if ( state === STATE.ZOOM ) {
  5133. zoomEnd.set( event.clientX, event.clientY );
  5134. zoomDelta.sub( zoomEnd, zoomStart );
  5135. if ( zoomDelta.y > 0 ) {
  5136. scope.zoomIn();
  5137. } else {
  5138. scope.zoomOut();
  5139. }
  5140. zoomStart.copy( zoomEnd );
  5141. }
  5142. }
  5143. function onMouseUp( event ) {
  5144. if ( ! scope.userRotate ) return;
  5145. document.removeEventListener( 'mousemove', onMouseMove, false );
  5146. document.removeEventListener( 'mouseup', onMouseUp, false );
  5147. state = STATE.NONE;
  5148. }
  5149. function onMouseWheel( event ) {
  5150. if ( ! scope.userZoom ) return;
  5151. if ( event.wheelDelta > 0 ) {
  5152. scope.zoomOut();
  5153. } else {
  5154. scope.zoomIn();
  5155. }
  5156. }
  5157. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  5158. this.domElement.addEventListener( 'mousedown', onMouseDown, false );
  5159. this.domElement.addEventListener( 'mousewheel', onMouseWheel, false );
  5160. };
  5161. /**
  5162. * @author mr.doob / http://mrdoob.com/
  5163. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  5164. */
  5165. THREE.CubeGeometry = function ( width, height, depth, segmentsWidth, segmentsHeight, segmentsDepth, materials, sides ) {
  5166. THREE.Geometry.call( this );
  5167. var scope = this,
  5168. width_half = width / 2,
  5169. height_half = height / 2,
  5170. depth_half = depth / 2;
  5171. var mpx, mpy, mpz, mnx, mny, mnz;
  5172. if ( materials !== undefined ) {
  5173. if ( materials instanceof Array ) {
  5174. this.materials = materials;
  5175. } else {
  5176. this.materials = [];
  5177. for ( var i = 0; i < 6; i ++ ) {
  5178. this.materials.push( materials );
  5179. }
  5180. }
  5181. mpx = 0; mnx = 1; mpy = 2; mny = 3; mpz = 4; mnz = 5;
  5182. } else {
  5183. this.materials = [];
  5184. }
  5185. this.sides = { px: true, nx: true, py: true, ny: true, pz: true, nz: true };
  5186. if ( sides != undefined ) {
  5187. for ( var s in sides ) {
  5188. if ( this.sides[ s ] !== undefined ) {
  5189. this.sides[ s ] = sides[ s ];
  5190. }
  5191. }
  5192. }
  5193. this.sides.px && buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, mpx ); // px
  5194. this.sides.nx && buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, mnx ); // nx
  5195. this.sides.py && buildPlane( 'x', 'z', 1, 1, width, depth, height_half, mpy ); // py
  5196. this.sides.ny && buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, mny ); // ny
  5197. this.sides.pz && buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, mpz ); // pz
  5198. this.sides.nz && buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, mnz ); // nz
  5199. function buildPlane( u, v, udir, vdir, width, height, depth, material ) {
  5200. var w, ix, iy,
  5201. gridX = segmentsWidth || 1,
  5202. gridY = segmentsHeight || 1,
  5203. width_half = width / 2,
  5204. height_half = height / 2,
  5205. offset = scope.vertices.length;
  5206. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  5207. w = 'z';
  5208. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  5209. w = 'y';
  5210. gridY = segmentsDepth || 1;
  5211. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  5212. w = 'x';
  5213. gridX = segmentsDepth || 1;
  5214. }
  5215. var gridX1 = gridX + 1,
  5216. gridY1 = gridY + 1,
  5217. segment_width = width / gridX,
  5218. segment_height = height / gridY,
  5219. normal = new THREE.Vector3();
  5220. normal[ w ] = depth > 0 ? 1 : - 1;
  5221. for ( iy = 0; iy < gridY1; iy ++ ) {
  5222. for ( ix = 0; ix < gridX1; ix ++ ) {
  5223. var vector = new THREE.Vector3();
  5224. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  5225. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  5226. vector[ w ] = depth;
  5227. scope.vertices.push( vector );
  5228. }
  5229. }
  5230. for ( iy = 0; iy < gridY; iy++ ) {
  5231. for ( ix = 0; ix < gridX; ix++ ) {
  5232. var a = ix + gridX1 * iy;
  5233. var b = ix + gridX1 * ( iy + 1 );
  5234. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  5235. var d = ( ix + 1 ) + gridX1 * iy;
  5236. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  5237. face.normal.copy( normal );
  5238. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  5239. face.materialIndex = material;
  5240. scope.faces.push( face );
  5241. scope.faceVertexUvs[ 0 ].push( [
  5242. new THREE.UV( ix / gridX, 1 - iy / gridY ),
  5243. new THREE.UV( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  5244. new THREE.UV( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  5245. new THREE.UV( ( ix + 1 ) / gridX, 1 - iy / gridY )
  5246. ] );
  5247. }
  5248. }
  5249. }
  5250. this.computeCentroids();
  5251. this.mergeVertices();
  5252. };
  5253. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  5254. /**
  5255. * @author mr.doob / http://mrdoob.com/
  5256. */
  5257. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, segmentsRadius, segmentsHeight, openEnded ) {
  5258. THREE.Geometry.call( this );
  5259. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  5260. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  5261. height = height !== undefined ? height : 100;
  5262. var heightHalf = height / 2;
  5263. var segmentsX = segmentsRadius || 8;
  5264. var segmentsY = segmentsHeight || 1;
  5265. var x, y, vertices = [], uvs = [];
  5266. for ( y = 0; y <= segmentsY; y ++ ) {
  5267. var verticesRow = [];
  5268. var uvsRow = [];
  5269. var v = y / segmentsY;
  5270. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  5271. for ( x = 0; x <= segmentsX; x ++ ) {
  5272. var u = x / segmentsX;
  5273. var vertex = new THREE.Vector3();
  5274. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  5275. vertex.y = - v * height + heightHalf;
  5276. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  5277. this.vertices.push( vertex );
  5278. verticesRow.push( this.vertices.length - 1 );
  5279. uvsRow.push( new THREE.UV( u, v ) );
  5280. }
  5281. vertices.push( verticesRow );
  5282. uvs.push( uvsRow );
  5283. }
  5284. var tanTheta = ( radiusBottom - radiusTop ) / height;
  5285. var na, nb;
  5286. for ( x = 0; x < segmentsX; x ++ ) {
  5287. if ( radiusTop !== 0 ) {
  5288. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  5289. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  5290. } else {
  5291. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  5292. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  5293. }
  5294. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  5295. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  5296. for ( y = 0; y < segmentsY; y ++ ) {
  5297. var v1 = vertices[ y ][ x ];
  5298. var v2 = vertices[ y + 1 ][ x ];
  5299. var v3 = vertices[ y + 1 ][ x + 1 ];
  5300. var v4 = vertices[ y ][ x + 1 ];
  5301. var n1 = na.clone();
  5302. var n2 = na.clone();
  5303. var n3 = nb.clone();
  5304. var n4 = nb.clone();
  5305. var uv1 = uvs[ y ][ x ].clone();
  5306. var uv2 = uvs[ y + 1 ][ x ].clone();
  5307. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  5308. var uv4 = uvs[ y ][ x + 1 ].clone();
  5309. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  5310. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  5311. }
  5312. }
  5313. // top cap
  5314. if ( !openEnded && radiusTop > 0 ) {
  5315. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  5316. for ( x = 0; x < segmentsX; x ++ ) {
  5317. var v1 = vertices[ 0 ][ x ];
  5318. var v2 = vertices[ 0 ][ x + 1 ];
  5319. var v3 = this.vertices.length - 1;
  5320. var n1 = new THREE.Vector3( 0, 1, 0 );
  5321. var n2 = new THREE.Vector3( 0, 1, 0 );
  5322. var n3 = new THREE.Vector3( 0, 1, 0 );
  5323. var uv1 = uvs[ 0 ][ x ].clone();
  5324. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  5325. var uv3 = new THREE.UV( uv2.u, 0 );
  5326. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  5327. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  5328. }
  5329. }
  5330. // bottom cap
  5331. if ( !openEnded && radiusBottom > 0 ) {
  5332. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  5333. for ( x = 0; x < segmentsX; x ++ ) {
  5334. var v1 = vertices[ y ][ x + 1 ];
  5335. var v2 = vertices[ y ][ x ];
  5336. var v3 = this.vertices.length - 1;
  5337. var n1 = new THREE.Vector3( 0, - 1, 0 );
  5338. var n2 = new THREE.Vector3( 0, - 1, 0 );
  5339. var n3 = new THREE.Vector3( 0, - 1, 0 );
  5340. var uv1 = uvs[ y ][ x + 1 ].clone();
  5341. var uv2 = uvs[ y ][ x ].clone();
  5342. var uv3 = new THREE.UV( uv2.u, 1 );
  5343. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  5344. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  5345. }
  5346. }
  5347. this.computeCentroids();
  5348. this.computeFaceNormals();
  5349. }
  5350. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  5351. /**
  5352. * @author zz85 / http://www.lab4games.net/zz85/blog
  5353. *
  5354. * Creates extruded geometry from a path shape.
  5355. *
  5356. * parameters = {
  5357. *
  5358. * size: <float>, // size of the text
  5359. * height: <float>, // thickness to extrude text
  5360. * curveSegments: <int>, // number of points on the curves
  5361. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  5362. amount: <int>, // Amount
  5363. *
  5364. * bevelEnabled: <bool>, // turn on bevel
  5365. * bevelThickness: <float>, // how deep into text bevel goes
  5366. * bevelSize: <float>, // how far from text outline is bevel
  5367. * bevelSegments: <int>, // number of bevel layers
  5368. *
  5369. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  5370. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  5371. * bendPath: <THREE.CurvePath> // 2d path for bend the shape around x/y plane
  5372. *
  5373. * material: <int> // material index for front and back faces
  5374. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  5375. * uvGenerator: <Object> // object that provides UV generator functions
  5376. *
  5377. * }
  5378. **/
  5379. THREE.ExtrudeGeometry = function( shapes, options ) {
  5380. if ( typeof( shapes ) === "undefined" ) {
  5381. shapes = [];
  5382. return;
  5383. }
  5384. THREE.Geometry.call( this );
  5385. shapes = shapes instanceof Array ? shapes : [ shapes ];
  5386. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  5387. this.addShapeList( shapes, options );
  5388. this.computeCentroids();
  5389. this.computeFaceNormals();
  5390. // can't really use automatic vertex normals
  5391. // as then front and back sides get smoothed too
  5392. // should do separate smoothing just for sides
  5393. //this.computeVertexNormals();
  5394. //console.log( "took", ( Date.now() - startTime ) );
  5395. };
  5396. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  5397. THREE.ExtrudeGeometry.prototype.addShapeList = function(shapes, options) {
  5398. var sl = shapes.length;
  5399. for ( var s = 0; s < sl; s ++ ) {
  5400. var shape = shapes[ s ];
  5401. this.addShape( shape, options );
  5402. }
  5403. };
  5404. THREE.ExtrudeGeometry.prototype.addShape = function( shape, options ) {
  5405. var amount = options.amount !== undefined ? options.amount : 100;
  5406. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  5407. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  5408. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  5409. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  5410. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  5411. var steps = options.steps !== undefined ? options.steps : 1;
  5412. var bendPath = options.bendPath;
  5413. var extrudePath = options.extrudePath;
  5414. var extrudePts, extrudeByPath = false;
  5415. var material = options.material;
  5416. var extrudeMaterial = options.extrudeMaterial;
  5417. // Use default WorldUVGenerator if no UV generators are specified.
  5418. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  5419. var shapebb = this.shapebb;
  5420. //shapebb = shape.getBoundingBox();
  5421. var splineTube, binormal, normal, position2;
  5422. if ( extrudePath ) {
  5423. extrudePts = extrudePath.getSpacedPoints( steps );
  5424. extrudeByPath = true;
  5425. bevelEnabled = false; // bevels not supported for path extrusion
  5426. // SETUP TNB variables
  5427. // Reuse TNB from TubeGeomtry for now.
  5428. // TODO1 - have a .isClosed in spline?
  5429. splineTube = options.frames !== undefined ?
  5430. options.frames :
  5431. new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  5432. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  5433. binormal = new THREE.Vector3();
  5434. normal = new THREE.Vector3();
  5435. position2 = new THREE.Vector3();
  5436. }
  5437. // Safeguards if bevels are not enabled
  5438. if ( ! bevelEnabled ) {
  5439. bevelSegments = 0;
  5440. bevelThickness = 0;
  5441. bevelSize = 0;
  5442. }
  5443. // Variables initalization
  5444. var ahole, h, hl; // looping of holes
  5445. var scope = this;
  5446. var bevelPoints = [];
  5447. var shapesOffset = this.vertices.length;
  5448. if ( bendPath ) {
  5449. shape.addWrapPath( bendPath );
  5450. }
  5451. var shapePoints = shape.extractPoints();
  5452. var vertices = shapePoints.shape;
  5453. var holes = shapePoints.holes;
  5454. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  5455. if ( reverse ) {
  5456. vertices = vertices.reverse();
  5457. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  5458. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  5459. ahole = holes[ h ];
  5460. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  5461. holes[ h ] = ahole.reverse();
  5462. }
  5463. }
  5464. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  5465. }
  5466. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  5467. //var faces = THREE.Shape.Utils.triangulate2( vertices, holes );
  5468. // Would it be better to move points after triangulation?
  5469. // shapePoints = shape.extractAllPointsWithBend( curveSegments, bendPath );
  5470. // vertices = shapePoints.shape;
  5471. // holes = shapePoints.holes;
  5472. //console.log(faces);
  5473. ////
  5474. /// Handle Vertices
  5475. ////
  5476. var contour = vertices; // vertices has all points but contour has only points of circumference
  5477. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  5478. ahole = holes[ h ];
  5479. vertices = vertices.concat( ahole );
  5480. }
  5481. function scalePt2 ( pt, vec, size ) {
  5482. if ( !vec ) console.log( "die" );
  5483. return vec.clone().multiplyScalar( size ).addSelf( pt );
  5484. }
  5485. var b, bs, t, z,
  5486. vert, vlen = vertices.length,
  5487. face, flen = faces.length,
  5488. cont, clen = contour.length;
  5489. //------
  5490. // Find directions for point movement
  5491. //
  5492. var RAD_TO_DEGREES = 180 / Math.PI;
  5493. function getBevelVec( pt_i, pt_j, pt_k ) {
  5494. // Algorithm 2
  5495. return getBevelVec2( pt_i, pt_j, pt_k );
  5496. }
  5497. function getBevelVec1( pt_i, pt_j, pt_k ) {
  5498. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  5499. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  5500. if ( anglea > angleb ) {
  5501. angleb += Math.PI * 2;
  5502. }
  5503. var anglec = ( anglea + angleb ) / 2;
  5504. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  5505. var x = - Math.cos( anglec );
  5506. var y = - Math.sin( anglec );
  5507. var vec = new THREE.Vector2( x, y ); //.normalize();
  5508. return vec;
  5509. }
  5510. function getBevelVec2( pt_i, pt_j, pt_k ) {
  5511. var a = THREE.ExtrudeGeometry.__v1,
  5512. b = THREE.ExtrudeGeometry.__v2,
  5513. v_hat = THREE.ExtrudeGeometry.__v3,
  5514. w_hat = THREE.ExtrudeGeometry.__v4,
  5515. p = THREE.ExtrudeGeometry.__v5,
  5516. q = THREE.ExtrudeGeometry.__v6,
  5517. v, w,
  5518. v_dot_w_hat, q_sub_p_dot_w_hat,
  5519. s, intersection;
  5520. // good reading for line-line intersection
  5521. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  5522. // define a as vector j->i
  5523. // define b as vectot k->i
  5524. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  5525. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  5526. // get unit vectors
  5527. v = a.normalize();
  5528. w = b.normalize();
  5529. // normals from pt i
  5530. v_hat.set( -v.y, v.x );
  5531. w_hat.set( w.y, -w.x );
  5532. // pts from i
  5533. p.copy( pt_i ).addSelf( v_hat );
  5534. q.copy( pt_i ).addSelf( w_hat );
  5535. if ( p.equals( q ) ) {
  5536. //console.log("Warning: lines are straight");
  5537. return w_hat.clone();
  5538. }
  5539. // Points from j, k. helps prevents points cross overover most of the time
  5540. p.copy( pt_j ).addSelf( v_hat );
  5541. q.copy( pt_k ).addSelf( w_hat );
  5542. v_dot_w_hat = v.dot( w_hat );
  5543. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  5544. // We should not reach these conditions
  5545. if ( v_dot_w_hat === 0 ) {
  5546. console.log( "Either infinite or no solutions!" );
  5547. if ( q_sub_p_dot_w_hat === 0 ) {
  5548. console.log( "Its finite solutions." );
  5549. } else {
  5550. console.log( "Too bad, no solutions." );
  5551. }
  5552. }
  5553. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  5554. if ( s < 0 ) {
  5555. // in case of emergecy, revert to algorithm 1.
  5556. return getBevelVec1( pt_i, pt_j, pt_k );
  5557. }
  5558. intersection = v.multiplyScalar( s ).addSelf( p );
  5559. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  5560. }
  5561. var contourMovements = [];
  5562. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  5563. if ( j === il ) j = 0;
  5564. if ( k === il ) k = 0;
  5565. // (j)---(i)---(k)
  5566. // console.log('i,j,k', i, j , k)
  5567. var pt_i = contour[ i ];
  5568. var pt_j = contour[ j ];
  5569. var pt_k = contour[ k ];
  5570. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  5571. }
  5572. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  5573. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  5574. ahole = holes[ h ];
  5575. oneHoleMovements = [];
  5576. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  5577. if ( j === il ) j = 0;
  5578. if ( k === il ) k = 0;
  5579. // (j)---(i)---(k)
  5580. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  5581. }
  5582. holesMovements.push( oneHoleMovements );
  5583. verticesMovements = verticesMovements.concat( oneHoleMovements );
  5584. }
  5585. // Loop bevelSegments, 1 for the front, 1 for the back
  5586. for ( b = 0; b < bevelSegments; b ++ ) {
  5587. //for ( b = bevelSegments; b > 0; b -- ) {
  5588. t = b / bevelSegments;
  5589. z = bevelThickness * ( 1 - t );
  5590. //z = bevelThickness * t;
  5591. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  5592. //bs = bevelSize * t ; // linear
  5593. // contract shape
  5594. for ( i = 0, il = contour.length; i < il; i ++ ) {
  5595. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  5596. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  5597. v( vert.x, vert.y, - z );
  5598. }
  5599. // expand holes
  5600. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  5601. ahole = holes[ h ];
  5602. oneHoleMovements = holesMovements[ h ];
  5603. for ( i = 0, il = ahole.length; i < il; i++ ) {
  5604. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  5605. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  5606. v( vert.x, vert.y, -z );
  5607. }
  5608. }
  5609. }
  5610. bs = bevelSize;
  5611. // Back facing vertices
  5612. for ( i = 0; i < vlen; i ++ ) {
  5613. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  5614. if ( !extrudeByPath ) {
  5615. v( vert.x, vert.y, 0 );
  5616. } else {
  5617. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  5618. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  5619. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  5620. position2.copy(extrudePts[0]).addSelf(normal).addSelf(binormal);
  5621. v(position2.x, position2.y, position2.z);
  5622. }
  5623. }
  5624. // Add stepped vertices...
  5625. // Including front facing vertices
  5626. var s;
  5627. for ( s = 1; s <= steps; s ++ ) {
  5628. for ( i = 0; i < vlen; i ++ ) {
  5629. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  5630. if ( !extrudeByPath ) {
  5631. v( vert.x, vert.y, amount / steps * s );
  5632. } else {
  5633. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  5634. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  5635. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  5636. position2.copy(extrudePts[s]).addSelf(normal).addSelf(binormal);
  5637. v(position2.x, position2.y, position2.z );
  5638. }
  5639. }
  5640. }
  5641. // Add bevel segments planes
  5642. //for ( b = 1; b <= bevelSegments; b ++ ) {
  5643. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  5644. t = b / bevelSegments;
  5645. z = bevelThickness * ( 1 - t );
  5646. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  5647. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  5648. // contract shape
  5649. for ( i = 0, il = contour.length; i < il; i ++ ) {
  5650. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  5651. v( vert.x, vert.y, amount + z );
  5652. }
  5653. // expand holes
  5654. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  5655. ahole = holes[ h ];
  5656. oneHoleMovements = holesMovements[ h ];
  5657. for ( i = 0, il = ahole.length; i < il; i++ ) {
  5658. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  5659. if ( !extrudeByPath ) {
  5660. v( vert.x, vert.y, amount + z );
  5661. } else {
  5662. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  5663. }
  5664. }
  5665. }
  5666. }
  5667. ////
  5668. /// Handle Faces
  5669. ////
  5670. // Top and bottom faces
  5671. buildLidFaces();
  5672. // Sides faces
  5673. buildSideFaces();
  5674. ///// Internal functions
  5675. function buildLidFaces() {
  5676. if ( bevelEnabled ) {
  5677. var layer = 0 ; // steps + 1
  5678. var offset = vlen * layer;
  5679. // Bottom faces
  5680. for ( i = 0; i < flen; i ++ ) {
  5681. face = faces[ i ];
  5682. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  5683. }
  5684. layer = steps + bevelSegments * 2;
  5685. offset = vlen * layer;
  5686. // Top faces
  5687. for ( i = 0; i < flen; i ++ ) {
  5688. face = faces[ i ];
  5689. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  5690. }
  5691. } else {
  5692. // Bottom faces
  5693. for ( i = 0; i < flen; i++ ) {
  5694. face = faces[ i ];
  5695. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  5696. }
  5697. // Top faces
  5698. for ( i = 0; i < flen; i ++ ) {
  5699. face = faces[ i ];
  5700. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  5701. }
  5702. }
  5703. }
  5704. // Create faces for the z-sides of the shape
  5705. function buildSideFaces() {
  5706. var layeroffset = 0;
  5707. sidewalls( contour, layeroffset );
  5708. layeroffset += contour.length;
  5709. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  5710. ahole = holes[ h ];
  5711. sidewalls( ahole, layeroffset );
  5712. //, true
  5713. layeroffset += ahole.length;
  5714. }
  5715. }
  5716. function sidewalls( contour, layeroffset ) {
  5717. var j, k;
  5718. i = contour.length;
  5719. while ( --i >= 0 ) {
  5720. j = i;
  5721. k = i - 1;
  5722. if ( k < 0 ) k = contour.length - 1;
  5723. //console.log('b', i,j, i-1, k,vertices.length);
  5724. var s = 0, sl = steps + bevelSegments * 2;
  5725. for ( s = 0; s < sl; s ++ ) {
  5726. var slen1 = vlen * s;
  5727. var slen2 = vlen * ( s + 1 );
  5728. var a = layeroffset + j + slen1,
  5729. b = layeroffset + k + slen1,
  5730. c = layeroffset + k + slen2,
  5731. d = layeroffset + j + slen2;
  5732. f4( a, b, c, d, contour, s, sl, j, k );
  5733. }
  5734. }
  5735. }
  5736. function v( x, y, z ) {
  5737. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  5738. }
  5739. function f3( a, b, c, isBottom ) {
  5740. a += shapesOffset;
  5741. b += shapesOffset;
  5742. c += shapesOffset;
  5743. // normal, color, material
  5744. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  5745. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c)
  5746. : uvgen.generateTopUV( scope, shape, options, a, b, c);
  5747. scope.faceVertexUvs[ 0 ].push(uvs);
  5748. }
  5749. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  5750. a += shapesOffset;
  5751. b += shapesOffset;
  5752. c += shapesOffset;
  5753. d += shapesOffset;
  5754. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  5755. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  5756. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  5757. scope.faceVertexUvs[ 0 ].push(uvs);
  5758. }
  5759. };
  5760. THREE.ExtrudeGeometry.WorldUVGenerator = {
  5761. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC) {
  5762. var ax = geometry.vertices[ indexA ].x,
  5763. ay = geometry.vertices[ indexA ].y,
  5764. bx = geometry.vertices[ indexB ].x,
  5765. by = geometry.vertices[ indexB ].y,
  5766. cx = geometry.vertices[ indexC ].x,
  5767. cy = geometry.vertices[ indexC ].y;
  5768. return [
  5769. new THREE.UV( ax, 1 - ay ),
  5770. new THREE.UV( bx, 1 - by ),
  5771. new THREE.UV( cx, 1 - cy )
  5772. ];
  5773. },
  5774. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC) {
  5775. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  5776. },
  5777. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  5778. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  5779. contourIndex1, contourIndex2 ) {
  5780. var ax = geometry.vertices[ indexA ].x,
  5781. ay = geometry.vertices[ indexA ].y,
  5782. az = geometry.vertices[ indexA ].z,
  5783. bx = geometry.vertices[ indexB ].x,
  5784. by = geometry.vertices[ indexB ].y,
  5785. bz = geometry.vertices[ indexB ].z,
  5786. cx = geometry.vertices[ indexC ].x,
  5787. cy = geometry.vertices[ indexC ].y,
  5788. cz = geometry.vertices[ indexC ].z,
  5789. dx = geometry.vertices[ indexD ].x,
  5790. dy = geometry.vertices[ indexD ].y,
  5791. dz = geometry.vertices[ indexD ].z;
  5792. if ( Math.abs( ay - by ) < 0.01 ) {
  5793. return [
  5794. new THREE.UV( ax, az ),
  5795. new THREE.UV( bx, bz ),
  5796. new THREE.UV( cx, cz ),
  5797. new THREE.UV( dx, dz )
  5798. ];
  5799. } else {
  5800. return [
  5801. new THREE.UV( ay, az ),
  5802. new THREE.UV( by, bz ),
  5803. new THREE.UV( cy, cz ),
  5804. new THREE.UV( dy, dz )
  5805. ];
  5806. }
  5807. }
  5808. };
  5809. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  5810. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  5811. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  5812. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  5813. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  5814. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  5815. /**
  5816. * @author astrodud / http://astrodud.isgreat.org/
  5817. * @author zz85 / https://github.com/zz85
  5818. */
  5819. THREE.LatheGeometry = function ( points, steps, angle ) {
  5820. THREE.Geometry.call( this );
  5821. var _steps = steps || 12;
  5822. var _angle = angle || 2 * Math.PI;
  5823. var _newV = [];
  5824. var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
  5825. for ( var j = 0; j < points.length; j ++ ) {
  5826. _newV[ j ] = points[ j ].clone();
  5827. this.vertices.push( _newV[ j ] );
  5828. }
  5829. var i, il = _steps + 1;
  5830. for ( i = 0; i < il; i ++ ) {
  5831. for ( var j = 0; j < _newV.length; j ++ ) {
  5832. _newV[ j ] = _matrix.multiplyVector3( _newV[ j ].clone() );
  5833. this.vertices.push( _newV[ j ] );
  5834. }
  5835. }
  5836. for ( i = 0; i < _steps; i ++ ) {
  5837. for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
  5838. var a = i * kl + k;
  5839. var b = ( ( i + 1 ) % il ) * kl + k;
  5840. var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
  5841. var d = i * kl + ( k + 1 ) % kl;
  5842. this.faces.push( new THREE.Face4( a, b, c, d ) );
  5843. this.faceVertexUvs[ 0 ].push( [
  5844. new THREE.UV( 1 - i / _steps, k / kl ),
  5845. new THREE.UV( 1 - ( i + 1 ) / _steps, k / kl ),
  5846. new THREE.UV( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
  5847. new THREE.UV( 1 - i / _steps, ( k + 1 ) / kl )
  5848. ] );
  5849. }
  5850. }
  5851. this.computeCentroids();
  5852. this.computeFaceNormals();
  5853. this.computeVertexNormals();
  5854. };
  5855. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  5856. /**
  5857. * @author mr.doob / http://mrdoob.com/
  5858. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  5859. */
  5860. THREE.PlaneGeometry = function ( width, depth, segmentsWidth, segmentsDepth ) {
  5861. THREE.Geometry.call( this );
  5862. var ix, iz,
  5863. width_half = width / 2,
  5864. depth_half = depth / 2,
  5865. gridX = segmentsWidth || 1,
  5866. gridZ = segmentsDepth || 1,
  5867. gridX1 = gridX + 1,
  5868. gridZ1 = gridZ + 1,
  5869. segment_width = width / gridX,
  5870. segment_depth = depth / gridZ,
  5871. normal = new THREE.Vector3( 0, 1, 0 );
  5872. for ( iz = 0; iz < gridZ1; iz ++ ) {
  5873. for ( ix = 0; ix < gridX1; ix ++ ) {
  5874. var x = ix * segment_width - width_half;
  5875. var z = iz * segment_depth - depth_half;
  5876. this.vertices.push( new THREE.Vector3( x, 0, z ) );
  5877. }
  5878. }
  5879. for ( iz = 0; iz < gridZ; iz ++ ) {
  5880. for ( ix = 0; ix < gridX; ix ++ ) {
  5881. var a = ix + gridX1 * iz;
  5882. var b = ix + gridX1 * ( iz + 1 );
  5883. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  5884. var d = ( ix + 1 ) + gridX1 * iz;
  5885. var face = new THREE.Face4( a, b, c, d );
  5886. face.normal.copy( normal );
  5887. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  5888. this.faces.push( face );
  5889. this.faceVertexUvs[ 0 ].push( [
  5890. new THREE.UV( ix / gridX, 1 - iz / gridZ ),
  5891. new THREE.UV( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  5892. new THREE.UV( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  5893. new THREE.UV( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  5894. ] );
  5895. }
  5896. }
  5897. this.computeCentroids();
  5898. };
  5899. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  5900. /**
  5901. * @author mr.doob / http://mrdoob.com/
  5902. */
  5903. THREE.SphereGeometry = function ( radius, segmentsWidth, segmentsHeight, phiStart, phiLength, thetaStart, thetaLength ) {
  5904. THREE.Geometry.call( this );
  5905. radius = radius || 50;
  5906. phiStart = phiStart !== undefined ? phiStart : 0;
  5907. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  5908. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  5909. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  5910. var segmentsX = Math.max( 3, Math.floor( segmentsWidth ) || 8 );
  5911. var segmentsY = Math.max( 2, Math.floor( segmentsHeight ) || 6 );
  5912. var x, y, vertices = [], uvs = [];
  5913. for ( y = 0; y <= segmentsY; y ++ ) {
  5914. var verticesRow = [];
  5915. var uvsRow = [];
  5916. for ( x = 0; x <= segmentsX; x ++ ) {
  5917. var u = x / segmentsX;
  5918. var v = y / segmentsY;
  5919. var vertex = new THREE.Vector3();
  5920. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  5921. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  5922. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  5923. this.vertices.push( vertex );
  5924. verticesRow.push( this.vertices.length - 1 );
  5925. uvsRow.push( new THREE.UV( u, 1 - v ) );
  5926. }
  5927. vertices.push( verticesRow );
  5928. uvs.push( uvsRow );
  5929. }
  5930. for ( y = 0; y < segmentsY; y ++ ) {
  5931. for ( x = 0; x < segmentsX; x ++ ) {
  5932. var v1 = vertices[ y ][ x + 1 ];
  5933. var v2 = vertices[ y ][ x ];
  5934. var v3 = vertices[ y + 1 ][ x ];
  5935. var v4 = vertices[ y + 1 ][ x + 1 ];
  5936. var n1 = this.vertices[ v1 ].clone().normalize();
  5937. var n2 = this.vertices[ v2 ].clone().normalize();
  5938. var n3 = this.vertices[ v3 ].clone().normalize();
  5939. var n4 = this.vertices[ v4 ].clone().normalize();
  5940. var uv1 = uvs[ y ][ x + 1 ].clone();
  5941. var uv2 = uvs[ y ][ x ].clone();
  5942. var uv3 = uvs[ y + 1 ][ x ].clone();
  5943. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  5944. if ( Math.abs( this.vertices[ v1 ].y ) == radius ) {
  5945. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  5946. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  5947. } else if ( Math.abs( this.vertices[ v3 ].y ) == radius ) {
  5948. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  5949. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  5950. } else {
  5951. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  5952. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  5953. }
  5954. }
  5955. }
  5956. this.computeCentroids();
  5957. this.computeFaceNormals();
  5958. this.boundingSphere = { radius: radius };
  5959. };
  5960. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  5961. /**
  5962. * @author zz85 / http://www.lab4games.net/zz85/blog
  5963. * @author alteredq / http://alteredqualia.com/
  5964. *
  5965. * For creating 3D text geometry in three.js
  5966. *
  5967. * Text = 3D Text
  5968. *
  5969. * parameters = {
  5970. * size: <float>, // size of the text
  5971. * height: <float>, // thickness to extrude text
  5972. * curveSegments: <int>, // number of points on the curves
  5973. *
  5974. * font: <string>, // font name
  5975. * weight: <string>, // font weight (normal, bold)
  5976. * style: <string>, // font style (normal, italics)
  5977. *
  5978. * bevelEnabled: <bool>, // turn on bevel
  5979. * bevelThickness: <float>, // how deep into text bevel goes
  5980. * bevelSize: <float>, // how far from text outline is bevel
  5981. *
  5982. * bend: <bool> // bend according to hardcoded curve (generates bendPath)
  5983. * bendPath: <curve> // wraps text according to bend Path
  5984. * }
  5985. *
  5986. */
  5987. /* Usage Examples
  5988. // TextGeometry wrapper
  5989. var text3d = new TextGeometry( text, options );
  5990. // Complete manner
  5991. var textShapes = THREE.FontUtils.generateShapes( text, options );
  5992. var text3d = new ExtrudeGeometry( textShapes, options );
  5993. */
  5994. THREE.TextGeometry = function ( text, parameters ) {
  5995. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  5996. // translate parameters to ExtrudeGeometry API
  5997. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  5998. // defaults
  5999. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  6000. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  6001. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  6002. if ( parameters.bend ) {
  6003. var b = textShapes[ textShapes.length - 1 ].getBoundingBox();
  6004. var max = b.maxX;
  6005. parameters.bendPath = new THREE.QuadraticBezierCurve(
  6006. new THREE.Vector2( 0, 0 ),
  6007. new THREE.Vector2( max / 2, 120 ),
  6008. new THREE.Vector2( max, 0 )
  6009. );
  6010. }
  6011. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  6012. };
  6013. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  6014. /**
  6015. * @author oosmoxiecode
  6016. * @author mr.doob / http://mrdoob.com/
  6017. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  6018. */
  6019. THREE.TorusGeometry = function ( radius, tube, segmentsR, segmentsT, arc ) {
  6020. THREE.Geometry.call( this );
  6021. var scope = this;
  6022. this.radius = radius || 100;
  6023. this.tube = tube || 40;
  6024. this.segmentsR = segmentsR || 8;
  6025. this.segmentsT = segmentsT || 6;
  6026. this.arc = arc || Math.PI * 2;
  6027. var center = new THREE.Vector3(), uvs = [], normals = [];
  6028. for ( var j = 0; j <= this.segmentsR; j ++ ) {
  6029. for ( var i = 0; i <= this.segmentsT; i ++ ) {
  6030. var u = i / this.segmentsT * this.arc;
  6031. var v = j / this.segmentsR * Math.PI * 2;
  6032. center.x = this.radius * Math.cos( u );
  6033. center.y = this.radius * Math.sin( u );
  6034. var vertex = new THREE.Vector3();
  6035. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  6036. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  6037. vertex.z = this.tube * Math.sin( v );
  6038. this.vertices.push( vertex );
  6039. uvs.push( new THREE.UV( i / this.segmentsT, 1 - j / this.segmentsR ) );
  6040. normals.push( vertex.clone().subSelf( center ).normalize() );
  6041. }
  6042. }
  6043. for ( var j = 1; j <= this.segmentsR; j ++ ) {
  6044. for ( var i = 1; i <= this.segmentsT; i ++ ) {
  6045. var a = ( this.segmentsT + 1 ) * j + i - 1;
  6046. var b = ( this.segmentsT + 1 ) * ( j - 1 ) + i - 1;
  6047. var c = ( this.segmentsT + 1 ) * ( j - 1 ) + i;
  6048. var d = ( this.segmentsT + 1 ) * j + i;
  6049. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  6050. face.normal.addSelf( normals[ a ] );
  6051. face.normal.addSelf( normals[ b ] );
  6052. face.normal.addSelf( normals[ c ] );
  6053. face.normal.addSelf( normals[ d ] );
  6054. face.normal.normalize();
  6055. this.faces.push( face );
  6056. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  6057. }
  6058. }
  6059. this.computeCentroids();
  6060. };
  6061. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  6062. /**
  6063. * @author oosmoxiecode
  6064. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  6065. */
  6066. THREE.TorusKnotGeometry = function ( radius, tube, segmentsR, segmentsT, p, q, heightScale ) {
  6067. THREE.Geometry.call( this );
  6068. var scope = this;
  6069. this.radius = radius || 200;
  6070. this.tube = tube || 40;
  6071. this.segmentsR = segmentsR || 64;
  6072. this.segmentsT = segmentsT || 8;
  6073. this.p = p || 2;
  6074. this.q = q || 3;
  6075. this.heightScale = heightScale || 1;
  6076. this.grid = new Array(this.segmentsR);
  6077. var tang = new THREE.Vector3();
  6078. var n = new THREE.Vector3();
  6079. var bitan = new THREE.Vector3();
  6080. for ( var i = 0; i < this.segmentsR; ++ i ) {
  6081. this.grid[ i ] = new Array( this.segmentsT );
  6082. for ( var j = 0; j < this.segmentsT; ++ j ) {
  6083. var u = i / this.segmentsR * 2 * this.p * Math.PI;
  6084. var v = j / this.segmentsT * 2 * Math.PI;
  6085. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  6086. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  6087. var cx, cy;
  6088. tang.sub( p2, p1 );
  6089. n.add( p2, p1 );
  6090. bitan.cross( tang, n );
  6091. n.cross( bitan, tang );
  6092. bitan.normalize();
  6093. n.normalize();
  6094. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  6095. cy = this.tube * Math.sin( v );
  6096. p1.x += cx * n.x + cy * bitan.x;
  6097. p1.y += cx * n.y + cy * bitan.y;
  6098. p1.z += cx * n.z + cy * bitan.z;
  6099. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  6100. }
  6101. }
  6102. for ( var i = 0; i < this.segmentsR; ++ i ) {
  6103. for ( var j = 0; j < this.segmentsT; ++ j ) {
  6104. var ip = ( i + 1 ) % this.segmentsR;
  6105. var jp = ( j + 1 ) % this.segmentsT;
  6106. var a = this.grid[ i ][ j ];
  6107. var b = this.grid[ ip ][ j ];
  6108. var c = this.grid[ ip ][ jp ];
  6109. var d = this.grid[ i ][ jp ];
  6110. var uva = new THREE.UV( i / this.segmentsR, j / this.segmentsT );
  6111. var uvb = new THREE.UV( ( i + 1 ) / this.segmentsR, j / this.segmentsT );
  6112. var uvc = new THREE.UV( ( i + 1 ) / this.segmentsR, ( j + 1 ) / this.segmentsT );
  6113. var uvd = new THREE.UV( i / this.segmentsR, ( j + 1 ) / this.segmentsT );
  6114. this.faces.push( new THREE.Face4( a, b, c, d ) );
  6115. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  6116. }
  6117. }
  6118. this.computeCentroids();
  6119. this.computeFaceNormals();
  6120. this.computeVertexNormals();
  6121. function vert( x, y, z ) {
  6122. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  6123. }
  6124. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  6125. var cu = Math.cos( u );
  6126. var cv = Math.cos( v );
  6127. var su = Math.sin( u );
  6128. var quOverP = in_q / in_p * u;
  6129. var cs = Math.cos( quOverP );
  6130. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  6131. var ty = radius * ( 2 + cs ) * su * 0.5;
  6132. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  6133. return new THREE.Vector3( tx, ty, tz );
  6134. }
  6135. };
  6136. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  6137. /**
  6138. * @author WestLangley / https://github.com/WestLangley
  6139. * @author zz85 / https://github.com/zz85
  6140. * @author miningold / https://github.com/miningold
  6141. *
  6142. * Modified from the TorusKnotGeometry by @oosmoxiecode
  6143. *
  6144. * Creates a tube which extrudes along a 3d spline
  6145. *
  6146. * Uses parallel transport frames as described in
  6147. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  6148. */
  6149. THREE.TubeGeometry = function( path, segments, radius, segmentsRadius, closed, debug ) {
  6150. THREE.Geometry.call( this );
  6151. this.path = path;
  6152. this.segments = segments || 64;
  6153. this.radius = radius || 1;
  6154. this.segmentsRadius = segmentsRadius || 8;
  6155. this.closed = closed || false;
  6156. if ( debug ) this.debug = new THREE.Object3D();
  6157. this.grid = [];
  6158. var scope = this,
  6159. tangent,
  6160. normal,
  6161. binormal,
  6162. numpoints = this.segments + 1,
  6163. x, y, z,
  6164. tx, ty, tz,
  6165. u, v,
  6166. cx, cy,
  6167. pos, pos2 = new THREE.Vector3(),
  6168. i, j,
  6169. ip, jp,
  6170. a, b, c, d,
  6171. uva, uvb, uvc, uvd;
  6172. var frames = new THREE.TubeGeometry.FrenetFrames(path, segments, closed),
  6173. tangents = frames.tangents,
  6174. normals = frames.normals,
  6175. binormals = frames.binormals;
  6176. // proxy internals
  6177. this.tangents = tangents;
  6178. this.normals = normals;
  6179. this.binormals = binormals;
  6180. function vert( x, y, z ) {
  6181. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  6182. }
  6183. // consruct the grid
  6184. for ( i = 0; i < numpoints; i++ ) {
  6185. this.grid[ i ] = [];
  6186. u = i / ( numpoints - 1 );
  6187. pos = path.getPointAt( u );
  6188. tangent = tangents[ i ];
  6189. normal = normals[ i ];
  6190. binormal = binormals[ i ];
  6191. if ( this.debug ) {
  6192. this.debug.add(new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff));
  6193. this.debug.add(new THREE.ArrowHelper(normal, pos, radius, 0xff0000));
  6194. this.debug.add(new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00));
  6195. }
  6196. for ( j = 0; j < this.segmentsRadius; j++ ) {
  6197. v = j / this.segmentsRadius * 2 * Math.PI;
  6198. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  6199. cy = this.radius * Math.sin( v );
  6200. pos2.copy( pos );
  6201. pos2.x += cx * normal.x + cy * binormal.x;
  6202. pos2.y += cx * normal.y + cy * binormal.y;
  6203. pos2.z += cx * normal.z + cy * binormal.z;
  6204. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  6205. }
  6206. }
  6207. // construct the mesh
  6208. for ( i = 0; i < this.segments; i++ ) {
  6209. for ( j = 0; j < this.segmentsRadius; j++ ) {
  6210. ip = ( closed ) ? (i + 1) % this.segments : i + 1;
  6211. jp = (j + 1) % this.segmentsRadius;
  6212. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  6213. b = this.grid[ ip ][ j ];
  6214. c = this.grid[ ip ][ jp ];
  6215. d = this.grid[ i ][ jp ];
  6216. uva = new THREE.UV( i / this.segments, j / this.segmentsRadius );
  6217. uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.segmentsRadius );
  6218. uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.segmentsRadius );
  6219. uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.segmentsRadius );
  6220. this.faces.push( new THREE.Face4( a, b, c, d ) );
  6221. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  6222. }
  6223. }
  6224. this.computeCentroids();
  6225. this.computeFaceNormals();
  6226. this.computeVertexNormals();
  6227. };
  6228. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  6229. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  6230. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  6231. var
  6232. tangent = new THREE.Vector3(),
  6233. normal = new THREE.Vector3(),
  6234. binormal = new THREE.Vector3(),
  6235. tangents = [],
  6236. normals = [],
  6237. binormals = [],
  6238. vec = new THREE.Vector3(),
  6239. mat = new THREE.Matrix4(),
  6240. numpoints = segments + 1,
  6241. theta,
  6242. epsilon = 0.0001,
  6243. smallest,
  6244. tx, ty, tz,
  6245. i, u, v;
  6246. // expose internals
  6247. this.tangents = tangents;
  6248. this.normals = normals;
  6249. this.binormals = binormals;
  6250. // compute the tangent vectors for each segment on the path
  6251. for ( i = 0; i < numpoints; i++ ) {
  6252. u = i / ( numpoints - 1 );
  6253. tangents[ i ] = path.getTangentAt( u );
  6254. tangents[ i ].normalize();
  6255. }
  6256. initialNormal3();
  6257. function initialNormal1(lastBinormal) {
  6258. // fixed start binormal. Has dangers of 0 vectors
  6259. normals[ 0 ] = new THREE.Vector3();
  6260. binormals[ 0 ] = new THREE.Vector3();
  6261. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  6262. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  6263. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  6264. }
  6265. function initialNormal2() {
  6266. // This uses the Frenet-Serret formula for deriving binormal
  6267. var t2 = path.getTangentAt( epsilon );
  6268. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
  6269. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  6270. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  6271. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  6272. }
  6273. function initialNormal3() {
  6274. // select an initial normal vector perpenicular to the first tangent vector,
  6275. // and in the direction of the smallest tangent xyz component
  6276. normals[ 0 ] = new THREE.Vector3();
  6277. binormals[ 0 ] = new THREE.Vector3();
  6278. smallest = Number.MAX_VALUE;
  6279. tx = Math.abs( tangents[ 0 ].x );
  6280. ty = Math.abs( tangents[ 0 ].y );
  6281. tz = Math.abs( tangents[ 0 ].z );
  6282. if ( tx <= smallest ) {
  6283. smallest = tx;
  6284. normal.set( 1, 0, 0 );
  6285. }
  6286. if ( ty <= smallest ) {
  6287. smallest = ty;
  6288. normal.set( 0, 1, 0 );
  6289. }
  6290. if ( tz <= smallest ) {
  6291. normal.set( 0, 0, 1 );
  6292. }
  6293. vec.cross( tangents[ 0 ], normal ).normalize();
  6294. normals[ 0 ].cross( tangents[ 0 ], vec );
  6295. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  6296. }
  6297. // compute the slowly-varying normal and binormal vectors for each segment on the path
  6298. for ( i = 1; i < numpoints; i++ ) {
  6299. normals[ i ] = normals[ i-1 ].clone();
  6300. binormals[ i ] = binormals[ i-1 ].clone();
  6301. vec.cross( tangents[ i-1 ], tangents[ i ] );
  6302. if ( vec.length() > epsilon ) {
  6303. vec.normalize();
  6304. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  6305. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  6306. }
  6307. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  6308. }
  6309. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  6310. if ( closed ) {
  6311. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  6312. theta /= ( numpoints - 1 );
  6313. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  6314. theta = -theta;
  6315. }
  6316. for ( i = 1; i < numpoints; i++ ) {
  6317. // twist a little...
  6318. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  6319. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  6320. }
  6321. }
  6322. };
  6323. /**
  6324. * @author clockworkgeek / https://github.com/clockworkgeek
  6325. * @author timothypratley / https://github.com/timothypratley
  6326. */
  6327. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  6328. THREE.Geometry.call( this );
  6329. radius = radius || 1;
  6330. detail = detail || 0;
  6331. var that = this;
  6332. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  6333. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  6334. }
  6335. var midpoints = [], p = this.vertices;
  6336. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  6337. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  6338. }
  6339. this.mergeVertices();
  6340. // Apply radius
  6341. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  6342. this.vertices[ i ].multiplyScalar( radius );
  6343. }
  6344. /**
  6345. * Project vector onto sphere's surface
  6346. */
  6347. function prepare( vector ) {
  6348. var vertex = vector.normalize().clone();
  6349. vertex.index = that.vertices.push( vertex ) - 1;
  6350. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  6351. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  6352. var v = inclination( vector ) / Math.PI + 0.5;
  6353. vertex.uv = new THREE.UV( u, v );
  6354. return vertex;
  6355. }
  6356. /**
  6357. * Approximate a curved face with recursively sub-divided triangles.
  6358. */
  6359. function make( v1, v2, v3, detail ) {
  6360. if ( detail < 1 ) {
  6361. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  6362. face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
  6363. face.normal = face.centroid.clone().normalize();
  6364. that.faces.push( face );
  6365. var azi = azimuth( face.centroid );
  6366. that.faceVertexUvs[ 0 ].push( [
  6367. correctUV( v1.uv, v1, azi ),
  6368. correctUV( v2.uv, v2, azi ),
  6369. correctUV( v3.uv, v3, azi )
  6370. ] );
  6371. }
  6372. else {
  6373. detail -= 1;
  6374. // split triangle into 4 smaller triangles
  6375. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  6376. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  6377. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  6378. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  6379. }
  6380. }
  6381. function midpoint( v1, v2 ) {
  6382. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  6383. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  6384. var mid = midpoints[ v1.index ][ v2.index ];
  6385. if ( mid === undefined ) {
  6386. // generate mean point and project to surface with prepare()
  6387. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  6388. new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
  6389. );
  6390. }
  6391. return mid;
  6392. }
  6393. /**
  6394. * Angle around the Y axis, counter-clockwise when looking from above.
  6395. */
  6396. function azimuth( vector ) {
  6397. return Math.atan2( vector.z, -vector.x );
  6398. }
  6399. /**
  6400. * Angle above the XZ plane.
  6401. */
  6402. function inclination( vector ) {
  6403. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  6404. }
  6405. /**
  6406. * Texture fixing helper. Spheres have some odd behaviours.
  6407. */
  6408. function correctUV( uv, vector, azimuth ) {
  6409. if ( (azimuth < 0) && (uv.u === 1) ) uv = new THREE.UV( uv.u - 1, uv.v );
  6410. if ( (vector.x === 0) && (vector.z === 0) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
  6411. return uv;
  6412. }
  6413. this.computeCentroids();
  6414. this.boundingSphere = { radius: radius };
  6415. };
  6416. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  6417. /**
  6418. * @author timothypratley / https://github.com/timothypratley
  6419. */
  6420. THREE.IcosahedronGeometry = function ( radius, detail ) {
  6421. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  6422. var vertices = [
  6423. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  6424. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  6425. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  6426. ];
  6427. var faces = [
  6428. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  6429. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  6430. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  6431. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  6432. ];
  6433. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  6434. };
  6435. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  6436. /**
  6437. * @author timothypratley / https://github.com/timothypratley
  6438. */
  6439. THREE.OctahedronGeometry = function ( radius, detail ) {
  6440. var vertices = [
  6441. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  6442. ];
  6443. var faces = [
  6444. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  6445. ];
  6446. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  6447. };
  6448. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  6449. /**
  6450. * @author timothypratley / https://github.com/timothypratley
  6451. */
  6452. THREE.TetrahedronGeometry = function ( radius, detail ) {
  6453. var vertices = [
  6454. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  6455. ];
  6456. var faces = [
  6457. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  6458. ];
  6459. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  6460. };
  6461. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  6462. /**
  6463. * @author zz85 / https://github.com/zz85
  6464. * Parametric Surfaces Geometry
  6465. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  6466. *
  6467. * new THREE.ParametricGeometry( parametricFunction, uSements, ySegements, useTris );
  6468. *
  6469. */
  6470. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  6471. THREE.Geometry.call( this );
  6472. var verts = this.vertices;
  6473. var faces = this.faces;
  6474. var uvs = this.faceVertexUvs[ 0 ];
  6475. useTris = (useTris === undefined) ? false : useTris;
  6476. var i, il, j, p;
  6477. var u, v;
  6478. var stackCount = stacks + 1;
  6479. var sliceCount = slices + 1;
  6480. for ( i = 0; i <= stacks; i ++ ) {
  6481. v = i / stacks;
  6482. for ( j = 0; j <= slices; j ++ ) {
  6483. u = j / slices;
  6484. p = func( u, v );
  6485. verts.push( p );
  6486. }
  6487. }
  6488. var a, b, c, d;
  6489. var uva, uvb, uvc, uvd;
  6490. for ( i = 0; i < stacks; i ++ ) {
  6491. for ( j = 0; j < slices; j ++ ) {
  6492. a = i * sliceCount + j;
  6493. b = i * sliceCount + j + 1;
  6494. c = (i + 1) * sliceCount + j;
  6495. d = (i + 1) * sliceCount + j + 1;
  6496. uva = new THREE.UV( j / slices, i / stacks );
  6497. uvb = new THREE.UV( ( j + 1 ) / slices, i / stacks );
  6498. uvc = new THREE.UV( j / slices, ( i + 1 ) / stacks );
  6499. uvd = new THREE.UV( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  6500. if ( useTris ) {
  6501. faces.push( new THREE.Face3( a, b, c ) );
  6502. faces.push( new THREE.Face3( b, d, c ) );
  6503. uvs.push( [ uva, uvb, uvc ] );
  6504. uvs.push( [ uvb, uvd, uvc ] );
  6505. } else {
  6506. faces.push( new THREE.Face4( a, b, d, c ) );
  6507. uvs.push( [ uva, uvb, uvd, uvc ] );
  6508. }
  6509. }
  6510. }
  6511. // console.log(this);
  6512. // magic bullet
  6513. // var diff = this.mergeVertices();
  6514. // console.log('removed ', diff, ' vertices by merging');
  6515. this.computeCentroids();
  6516. this.computeFaceNormals();
  6517. this.computeVertexNormals();
  6518. };
  6519. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  6520. /**
  6521. * @author qiao / https://github.com/qiao
  6522. * @fileoverview This is a convex hull generator using the incremental method.
  6523. * The complexity is O(n^2) where n is the number of vertices.
  6524. * O(nlogn) algorithms do exist, but they are much more complicated.
  6525. *
  6526. * Benchmark:
  6527. *
  6528. * Platform: CPU: P7350 @2.00GHz Engine: V8
  6529. *
  6530. * Num Vertices Time(ms)
  6531. *
  6532. * 10 1
  6533. * 20 3
  6534. * 30 19
  6535. * 40 48
  6536. * 50 107
  6537. */
  6538. THREE.ConvexGeometry = function( vertices ) {
  6539. THREE.Geometry.call( this );
  6540. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  6541. for ( var i = 3; i < vertices.length; i++ ) {
  6542. addPoint( i );
  6543. }
  6544. function addPoint( vertexId ) {
  6545. var vertex = vertices[ vertexId ].clone();
  6546. var mag = vertex.length();
  6547. vertex.x += mag * randomOffset();
  6548. vertex.y += mag * randomOffset();
  6549. vertex.z += mag * randomOffset();
  6550. var hole = [];
  6551. for ( var f = 0; f < faces.length; ) {
  6552. var face = faces[ f ];
  6553. // for each face, if the vertex can see it,
  6554. // then we try to add the face's edges into the hole.
  6555. if ( visible( face, vertex ) ) {
  6556. for ( var e = 0; e < 3; e++ ) {
  6557. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  6558. var boundary = true;
  6559. // remove duplicated edges.
  6560. for ( var h = 0; h < hole.length; h++ ) {
  6561. if ( equalEdge( hole[ h ], edge ) ) {
  6562. hole[ h ] = hole[ hole.length - 1 ];
  6563. hole.pop();
  6564. boundary = false;
  6565. break;
  6566. }
  6567. }
  6568. if ( boundary ) {
  6569. hole.push( edge );
  6570. }
  6571. }
  6572. // remove faces[ f ]
  6573. faces[ f ] = faces[ faces.length - 1 ];
  6574. faces.pop();
  6575. } else { // not visible
  6576. f++;
  6577. }
  6578. }
  6579. // construct the new faces formed by the edges of the hole and the vertex
  6580. for ( var h = 0; h < hole.length; h++ ) {
  6581. faces.push( [
  6582. hole[ h ][ 0 ],
  6583. hole[ h ][ 1 ],
  6584. vertexId
  6585. ] );
  6586. }
  6587. }
  6588. /**
  6589. * Whether the face is visible from the vertex
  6590. */
  6591. function visible( face, vertex ) {
  6592. var va = vertices[ face[ 0 ] ];
  6593. var vb = vertices[ face[ 1 ] ];
  6594. var vc = vertices[ face[ 2 ] ];
  6595. var n = normal( va, vb, vc );
  6596. // distance from face to origin
  6597. var dist = n.dot( va );
  6598. return n.dot( vertex ) >= dist;
  6599. }
  6600. /**
  6601. * Face normal
  6602. */
  6603. function normal( va, vb, vc ) {
  6604. var cb = new THREE.Vector3();
  6605. var ab = new THREE.Vector3();
  6606. cb.sub( vc, vb );
  6607. ab.sub( va, vb );
  6608. cb.crossSelf( ab );
  6609. if ( !cb.isZero() ) {
  6610. cb.normalize();
  6611. }
  6612. return cb;
  6613. }
  6614. /**
  6615. * Detect whether two edges are equal.
  6616. * Note that when constructing the convex hull, two same edges can only
  6617. * be of the negative direction.
  6618. */
  6619. function equalEdge( ea, eb ) {
  6620. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  6621. }
  6622. /**
  6623. * Create a random offset between -1e-6 and 1e-6.
  6624. */
  6625. function randomOffset() {
  6626. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  6627. }
  6628. /**
  6629. * XXX: Not sure if this is the correct approach. Need someone to review.
  6630. */
  6631. function vertexUv( vertex ) {
  6632. var mag = vertex.length();
  6633. return new THREE.UV( vertex.x / mag, vertex.y / mag );
  6634. }
  6635. // Push vertices into `this.vertices`, skipping those inside the hull
  6636. var id = 0;
  6637. var newId = new Array( vertices.length ); // map from old vertex id to new id
  6638. for ( var i = 0; i < faces.length; i++ ) {
  6639. var face = faces[ i ];
  6640. for ( var j = 0; j < 3; j++ ) {
  6641. if ( newId[ face[ j ] ] === undefined ) {
  6642. newId[ face[ j ] ] = id++;
  6643. this.vertices.push( vertices[ face[ j ] ] );
  6644. }
  6645. face[ j ] = newId[ face[ j ] ];
  6646. }
  6647. }
  6648. // Convert faces into instances of THREE.Face3
  6649. for ( var i = 0; i < faces.length; i++ ) {
  6650. this.faces.push( new THREE.Face3(
  6651. faces[ i ][ 0 ],
  6652. faces[ i ][ 1 ],
  6653. faces[ i ][ 2 ]
  6654. ) );
  6655. }
  6656. // Compute UVs
  6657. for ( var i = 0; i < this.faces.length; i++ ) {
  6658. var face = this.faces[ i ];
  6659. this.faceVertexUvs[ 0 ].push( [
  6660. vertexUv( this.vertices[ face.a ] ),
  6661. vertexUv( this.vertices[ face.b ] ),
  6662. vertexUv( this.vertices[ face.c ])
  6663. ] );
  6664. }
  6665. this.computeCentroids();
  6666. this.computeFaceNormals();
  6667. this.computeVertexNormals();
  6668. };
  6669. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  6670. /**
  6671. * @author sroucheray / http://sroucheray.org/
  6672. * @author mr.doob / http://mrdoob.com/
  6673. */
  6674. THREE.AxisHelper = function () {
  6675. THREE.Object3D.call( this );
  6676. var lineGeometry = new THREE.Geometry();
  6677. lineGeometry.vertices.push( new THREE.Vector3() );
  6678. lineGeometry.vertices.push( new THREE.Vector3( 0, 100, 0 ) );
  6679. var coneGeometry = new THREE.CylinderGeometry( 0, 5, 25, 5, 1 );
  6680. var line, cone;
  6681. // x
  6682. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0xff0000 } ) );
  6683. line.rotation.z = - Math.PI / 2;
  6684. this.add( line );
  6685. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0xff0000 } ) );
  6686. cone.position.x = 100;
  6687. cone.rotation.z = - Math.PI / 2;
  6688. this.add( cone );
  6689. // y
  6690. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x00ff00 } ) );
  6691. this.add( line );
  6692. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x00ff00 } ) );
  6693. cone.position.y = 100;
  6694. this.add( cone );
  6695. // z
  6696. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x0000ff } ) );
  6697. line.rotation.x = Math.PI / 2;
  6698. this.add( line );
  6699. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x0000ff } ) );
  6700. cone.position.z = 100;
  6701. cone.rotation.x = Math.PI / 2;
  6702. this.add( cone );
  6703. };
  6704. THREE.AxisHelper.prototype = Object.create( THREE.Object3D.prototype );
  6705. /**
  6706. * @author WestLangley / http://github.com/WestLangley
  6707. * @author zz85 / https://github.com/zz85
  6708. *
  6709. * Creates an arrow for visualizing directions
  6710. *
  6711. * Parameters:
  6712. * dir - Vector3
  6713. * origin - Vector3
  6714. * length - Number
  6715. * hex - color in hex value
  6716. */
  6717. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  6718. THREE.Object3D.call( this );
  6719. if ( hex === undefined ) hex = 0xffff00;
  6720. if ( length === undefined ) length = 20;
  6721. var lineGeometry = new THREE.Geometry();
  6722. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  6723. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  6724. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  6725. this.add( this.line );
  6726. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  6727. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  6728. this.cone.position.set( 0, 1, 0 );
  6729. this.add( this.cone );
  6730. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  6731. this.setDirection( dir );
  6732. this.setLength( length );
  6733. };
  6734. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  6735. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  6736. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  6737. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  6738. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  6739. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  6740. };
  6741. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  6742. this.scale.set( length, length, length );
  6743. };
  6744. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  6745. this.line.material.color.setHex( hex );
  6746. this.cone.material.color.setHex( hex );
  6747. };
  6748. /**
  6749. * @author alteredq / http://alteredqualia.com/
  6750. *
  6751. * - shows frustum, line of sight and up of the camera
  6752. * - suitable for fast updates
  6753. * - based on frustum visualization in lightgl.js shadowmap example
  6754. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  6755. */
  6756. THREE.CameraHelper = function ( camera ) {
  6757. THREE.Object3D.call( this );
  6758. var _this = this;
  6759. this.lineGeometry = new THREE.Geometry();
  6760. this.lineMaterial = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  6761. this.pointMap = {};
  6762. // colors
  6763. var hexFrustum = 0xffaa00,
  6764. hexCone = 0xff0000,
  6765. hexUp = 0x00aaff,
  6766. hexTarget = 0xffffff,
  6767. hexCross = 0x333333;
  6768. // near
  6769. addLine( "n1", "n2", hexFrustum );
  6770. addLine( "n2", "n4", hexFrustum );
  6771. addLine( "n4", "n3", hexFrustum );
  6772. addLine( "n3", "n1", hexFrustum );
  6773. // far
  6774. addLine( "f1", "f2", hexFrustum );
  6775. addLine( "f2", "f4", hexFrustum );
  6776. addLine( "f4", "f3", hexFrustum );
  6777. addLine( "f3", "f1", hexFrustum );
  6778. // sides
  6779. addLine( "n1", "f1", hexFrustum );
  6780. addLine( "n2", "f2", hexFrustum );
  6781. addLine( "n3", "f3", hexFrustum );
  6782. addLine( "n4", "f4", hexFrustum );
  6783. // cone
  6784. addLine( "p", "n1", hexCone );
  6785. addLine( "p", "n2", hexCone );
  6786. addLine( "p", "n3", hexCone );
  6787. addLine( "p", "n4", hexCone );
  6788. // up
  6789. addLine( "u1", "u2", hexUp );
  6790. addLine( "u2", "u3", hexUp );
  6791. addLine( "u3", "u1", hexUp );
  6792. // target
  6793. addLine( "c", "t", hexTarget );
  6794. addLine( "p", "c", hexCross );
  6795. // cross
  6796. addLine( "cn1", "cn2", hexCross );
  6797. addLine( "cn3", "cn4", hexCross );
  6798. addLine( "cf1", "cf2", hexCross );
  6799. addLine( "cf3", "cf4", hexCross );
  6800. this.camera = camera;
  6801. function addLine( a, b, hex ) {
  6802. addPoint( a, hex );
  6803. addPoint( b, hex );
  6804. }
  6805. function addPoint( id, hex ) {
  6806. _this.lineGeometry.vertices.push( new THREE.Vector3() );
  6807. _this.lineGeometry.colors.push( new THREE.Color( hex ) );
  6808. if ( _this.pointMap[ id ] === undefined ) _this.pointMap[ id ] = [];
  6809. _this.pointMap[ id ].push( _this.lineGeometry.vertices.length - 1 );
  6810. }
  6811. this.update( camera );
  6812. this.lines = new THREE.Line( this.lineGeometry, this.lineMaterial, THREE.LinePieces );
  6813. this.add( this.lines );
  6814. };
  6815. THREE.CameraHelper.prototype = Object.create( THREE.Object3D.prototype );
  6816. THREE.CameraHelper.prototype.update = function () {
  6817. var camera = this.camera;
  6818. var w = 1;
  6819. var h = 1;
  6820. var _this = this;
  6821. // we need just camera projection matrix
  6822. // world matrix must be identity
  6823. THREE.CameraHelper.__c.projectionMatrix.copy( camera.projectionMatrix );
  6824. // center / target
  6825. setPoint( "c", 0, 0, -1 );
  6826. setPoint( "t", 0, 0, 1 );
  6827. // near
  6828. setPoint( "n1", -w, -h, -1 );
  6829. setPoint( "n2", w, -h, -1 );
  6830. setPoint( "n3", -w, h, -1 );
  6831. setPoint( "n4", w, h, -1 );
  6832. // far
  6833. setPoint( "f1", -w, -h, 1 );
  6834. setPoint( "f2", w, -h, 1 );
  6835. setPoint( "f3", -w, h, 1 );
  6836. setPoint( "f4", w, h, 1 );
  6837. // up
  6838. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  6839. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  6840. setPoint( "u3", 0, h * 2, -1 );
  6841. // cross
  6842. setPoint( "cf1", -w, 0, 1 );
  6843. setPoint( "cf2", w, 0, 1 );
  6844. setPoint( "cf3", 0, -h, 1 );
  6845. setPoint( "cf4", 0, h, 1 );
  6846. setPoint( "cn1", -w, 0, -1 );
  6847. setPoint( "cn2", w, 0, -1 );
  6848. setPoint( "cn3", 0, -h, -1 );
  6849. setPoint( "cn4", 0, h, -1 );
  6850. function setPoint( point, x, y, z ) {
  6851. THREE.CameraHelper.__v.set( x, y, z );
  6852. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  6853. var points = _this.pointMap[ point ];
  6854. if ( points !== undefined ) {
  6855. for ( var i = 0, il = points.length; i < il; i ++ ) {
  6856. var j = points[ i ];
  6857. _this.lineGeometry.vertices[ j ].copy( THREE.CameraHelper.__v );
  6858. }
  6859. }
  6860. }
  6861. this.lineGeometry.verticesNeedUpdate = true;
  6862. };
  6863. THREE.CameraHelper.__projector = new THREE.Projector();
  6864. THREE.CameraHelper.__v = new THREE.Vector3();
  6865. THREE.CameraHelper.__c = new THREE.Camera();
  6866. /*
  6867. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  6868. *
  6869. * Subdivision Geometry Modifier
  6870. * using Catmull-Clark Subdivision Surfaces
  6871. * for creating smooth geometry meshes
  6872. *
  6873. * Note: a modifier modifies vertices and faces of geometry,
  6874. * so use THREE.GeometryUtils.clone() if orignal geoemtry needs to be retained
  6875. *
  6876. * Readings:
  6877. * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  6878. * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
  6879. * http://xrt.wikidot.com/blog:31
  6880. * "Subdivision Surfaces in Character Animation"
  6881. *
  6882. * Supports:
  6883. * Closed and Open geometries.
  6884. *
  6885. * TODO:
  6886. * crease vertex and "semi-sharp" features
  6887. * selective subdivision
  6888. */
  6889. THREE.SubdivisionModifier = function( subdivisions ) {
  6890. this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
  6891. // Settings
  6892. this.useOldVertexColors = false;
  6893. this.supportUVs = true;
  6894. this.debug = false;
  6895. };
  6896. // Applies the "modify" pattern
  6897. THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {
  6898. var repeats = this.subdivisions;
  6899. while ( repeats-- > 0 ) {
  6900. this.smooth( geometry );
  6901. }
  6902. };
  6903. // Performs an iteration of Catmull-Clark Subdivision
  6904. THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
  6905. //debug( 'running smooth' );
  6906. // New set of vertices, faces and uvs
  6907. var newVertices = [], newFaces = [], newUVs = [];
  6908. function v( x, y, z ) {
  6909. newVertices.push( new THREE.Vector3( x, y, z ) );
  6910. }
  6911. var scope = this;
  6912. function debug() {
  6913. if (scope.debug) console.log.apply(console, arguments);
  6914. }
  6915. function warn() {
  6916. if (console)
  6917. console.log.apply(console, arguments);
  6918. }
  6919. function f4( a, b, c, d, oldFace, orders, facei ) {
  6920. // TODO move vertex selection over here!
  6921. var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.materialIndex );
  6922. if (scope.useOldVertexColors) {
  6923. newFace.vertexColors = [];
  6924. var color, tmpColor, order;
  6925. for (var i=0;i<4;i++) {
  6926. order = orders[i];
  6927. color = new THREE.Color(),
  6928. color.setRGB(0,0,0);
  6929. for (var j=0, jl=0; j<order.length;j++) {
  6930. tmpColor = oldFace.vertexColors[order[j]-1];
  6931. color.r += tmpColor.r;
  6932. color.g += tmpColor.g;
  6933. color.b += tmpColor.b;
  6934. }
  6935. color.r /= order.length;
  6936. color.g /= order.length;
  6937. color.b /= order.length;
  6938. newFace.vertexColors[i] = color;
  6939. }
  6940. }
  6941. newFaces.push( newFace );
  6942. if (scope.supportUVs) {
  6943. var aUv = [
  6944. getUV(a, ''),
  6945. getUV(b, facei),
  6946. getUV(c, facei),
  6947. getUV(d, facei)
  6948. ];
  6949. if (!aUv[0]) debug('a :( ', a+':'+facei);
  6950. else if (!aUv[1]) debug('b :( ', b+':'+facei);
  6951. else if (!aUv[2]) debug('c :( ', c+':'+facei);
  6952. else if (!aUv[3]) debug('d :( ', d+':'+facei);
  6953. else
  6954. newUVs.push( aUv );
  6955. }
  6956. }
  6957. function edge_hash( a, b ) {
  6958. return Math.min( a, b ) + "_" + Math.max( a, b );
  6959. }
  6960. function computeEdgeFaces( geometry ) {
  6961. var i, il, v1, v2, j, k,
  6962. face, faceIndices, faceIndex,
  6963. edge,
  6964. hash,
  6965. edgeFaceMap = {};
  6966. function mapEdgeHash( hash, i ) {
  6967. if ( edgeFaceMap[ hash ] === undefined ) {
  6968. edgeFaceMap[ hash ] = [];
  6969. }
  6970. edgeFaceMap[ hash ].push( i );
  6971. }
  6972. // construct vertex -> face map
  6973. for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  6974. face = geometry.faces[ i ];
  6975. if ( face instanceof THREE.Face3 ) {
  6976. hash = edge_hash( face.a, face.b );
  6977. mapEdgeHash( hash, i );
  6978. hash = edge_hash( face.b, face.c );
  6979. mapEdgeHash( hash, i );
  6980. hash = edge_hash( face.c, face.a );
  6981. mapEdgeHash( hash, i );
  6982. } else if ( face instanceof THREE.Face4 ) {
  6983. hash = edge_hash( face.a, face.b );
  6984. mapEdgeHash( hash, i );
  6985. hash = edge_hash( face.b, face.c );
  6986. mapEdgeHash( hash, i );
  6987. hash = edge_hash( face.c, face.d );
  6988. mapEdgeHash( hash, i );
  6989. hash = edge_hash( face.d, face.a );
  6990. mapEdgeHash( hash, i );
  6991. }
  6992. }
  6993. // extract faces
  6994. // var edges = [];
  6995. //
  6996. // var numOfEdges = 0;
  6997. // for (i in edgeFaceMap) {
  6998. // numOfEdges++;
  6999. //
  7000. // edge = edgeFaceMap[i];
  7001. // edges.push(edge);
  7002. //
  7003. // }
  7004. //debug('edgeFaceMap', edgeFaceMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
  7005. return edgeFaceMap;
  7006. }
  7007. var originalPoints = oldGeometry.vertices;
  7008. var originalFaces = oldGeometry.faces;
  7009. var newPoints = originalPoints.concat(); // Vertices
  7010. var facePoints = [], edgePoints = {};
  7011. var sharpEdges = {}, sharpVertices = [], sharpFaces = [];
  7012. var uvForVertices = {}; // Stored in {vertex}:{old face} format
  7013. var originalVerticesLength = originalPoints.length;
  7014. function getUV(vertexNo, oldFaceNo) {
  7015. var j,jl;
  7016. var key = vertexNo+':'+oldFaceNo;
  7017. var theUV = uvForVertices[key];
  7018. if (!theUV) {
  7019. if (vertexNo>=originalVerticesLength && vertexNo < (originalVerticesLength + originalFaces.length)) {
  7020. debug('face pt');
  7021. } else {
  7022. debug('edge pt');
  7023. }
  7024. warn('warning, UV not found for', key);
  7025. return null;
  7026. }
  7027. return theUV;
  7028. // Original faces -> Vertex Nos.
  7029. // new Facepoint -> Vertex Nos.
  7030. // edge Points
  7031. }
  7032. function addUV(vertexNo, oldFaceNo, value) {
  7033. var key = vertexNo+':'+oldFaceNo;
  7034. if (!(key in uvForVertices)) {
  7035. uvForVertices[key] = value;
  7036. } else {
  7037. warn('dup vertexNo', vertexNo, 'oldFaceNo', oldFaceNo, 'value', value, 'key', key, uvForVertices[key]);
  7038. }
  7039. }
  7040. // Step 1
  7041. // For each face, add a face point
  7042. // Set each face point to be the centroid of all original points for the respective face.
  7043. // debug(oldGeometry);
  7044. var i, il, j, jl, face;
  7045. // For Uvs
  7046. var uvs = oldGeometry.faceVertexUvs[0];
  7047. var abcd = 'abcd', vertice;
  7048. debug('originalFaces, uvs, originalVerticesLength', originalFaces.length, uvs.length, originalVerticesLength);
  7049. if (scope.supportUVs)
  7050. for (i=0, il = uvs.length; i<il; i++ ) {
  7051. for (j=0,jl=uvs[i].length;j<jl;j++) {
  7052. vertice = originalFaces[i][abcd.charAt(j)];
  7053. addUV(vertice, i, uvs[i][j]);
  7054. }
  7055. }
  7056. if (uvs.length == 0) scope.supportUVs = false;
  7057. // Additional UVs check, if we index original
  7058. var uvCount = 0;
  7059. for (var u in uvForVertices) {
  7060. uvCount++;
  7061. }
  7062. if (!uvCount) {
  7063. scope.supportUVs = false;
  7064. debug('no uvs');
  7065. }
  7066. debug('-- Original Faces + Vertices UVs completed', uvForVertices, 'vs', uvs.length);
  7067. var avgUv ;
  7068. for (i=0, il = originalFaces.length; i<il ;i++) {
  7069. face = originalFaces[ i ];
  7070. facePoints.push( face.centroid );
  7071. newPoints.push( face.centroid );
  7072. if (!scope.supportUVs) continue;
  7073. // Prepare subdivided uv
  7074. avgUv = new THREE.UV();
  7075. if ( face instanceof THREE.Face3 ) {
  7076. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u;
  7077. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v;
  7078. avgUv.u /= 3;
  7079. avgUv.v /= 3;
  7080. } else if ( face instanceof THREE.Face4 ) {
  7081. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u + getUV( face.d, i ).u;
  7082. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v + getUV( face.d, i ).v;
  7083. avgUv.u /= 4;
  7084. avgUv.v /= 4;
  7085. }
  7086. addUV(originalVerticesLength + i, '', avgUv);
  7087. }
  7088. debug('-- added UVs for new Faces', uvForVertices);
  7089. // Step 2
  7090. // For each edge, add an edge point.
  7091. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
  7092. var edgeFaceMap = computeEdgeFaces ( oldGeometry ); // Edge Hash -> Faces Index
  7093. var edge, faceIndexA, faceIndexB, avg;
  7094. // debug('edgeFaceMap', edgeFaceMap);
  7095. var edgeCount = 0;
  7096. var edgeVertex, edgeVertexA, edgeVertexB;
  7097. ////
  7098. var vertexEdgeMap = {}; // Gives edges connecting from each vertex
  7099. var vertexFaceMap = {}; // Gives faces connecting from each vertex
  7100. function addVertexEdgeMap(vertex, edge) {
  7101. if (vertexEdgeMap[vertex]===undefined) {
  7102. vertexEdgeMap[vertex] = [];
  7103. }
  7104. vertexEdgeMap[vertex].push(edge);
  7105. }
  7106. function addVertexFaceMap(vertex, face, edge) {
  7107. if (vertexFaceMap[vertex]===undefined) {
  7108. vertexFaceMap[vertex] = {};
  7109. }
  7110. vertexFaceMap[vertex][face] = edge;
  7111. // vertexFaceMap[vertex][face] = null;
  7112. }
  7113. // Prepares vertexEdgeMap and vertexFaceMap
  7114. for (i in edgeFaceMap) { // This is for every edge
  7115. edge = edgeFaceMap[i];
  7116. edgeVertex = i.split('_');
  7117. edgeVertexA = edgeVertex[0];
  7118. edgeVertexB = edgeVertex[1];
  7119. // Maps an edgeVertex to connecting edges
  7120. addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
  7121. addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
  7122. for (j=0,jl=edge.length;j<jl;j++) {
  7123. face = edge[j];
  7124. addVertexFaceMap(edgeVertexA, face, i);
  7125. addVertexFaceMap(edgeVertexB, face, i);
  7126. }
  7127. if (edge.length < 2) {
  7128. // edge is "sharp";
  7129. sharpEdges[i] = true;
  7130. sharpVertices[edgeVertexA] = true;
  7131. sharpVertices[edgeVertexB] = true;
  7132. }
  7133. }
  7134. debug('vertexEdgeMap',vertexEdgeMap, 'vertexFaceMap', vertexFaceMap);
  7135. for (i in edgeFaceMap) {
  7136. edge = edgeFaceMap[i];
  7137. faceIndexA = edge[0]; // face index a
  7138. faceIndexB = edge[1]; // face index b
  7139. edgeVertex = i.split('_');
  7140. edgeVertexA = edgeVertex[0];
  7141. edgeVertexB = edgeVertex[1];
  7142. avg = new THREE.Vector3();
  7143. //debug(i, faceIndexB,facePoints[faceIndexB]);
  7144. if (sharpEdges[i]) {
  7145. //debug('warning, ', i, 'edge has only 1 connecting face', edge);
  7146. // For a sharp edge, average the edge end points.
  7147. avg.addSelf(originalPoints[edgeVertexA]);
  7148. avg.addSelf(originalPoints[edgeVertexB]);
  7149. avg.multiplyScalar(0.5);
  7150. sharpVertices[newPoints.length] = true;
  7151. } else {
  7152. avg.addSelf(facePoints[faceIndexA]);
  7153. avg.addSelf(facePoints[faceIndexB]);
  7154. avg.addSelf(originalPoints[edgeVertexA]);
  7155. avg.addSelf(originalPoints[edgeVertexB]);
  7156. avg.multiplyScalar(0.25);
  7157. }
  7158. edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
  7159. newPoints.push( avg );
  7160. edgeCount ++;
  7161. if (!scope.supportUVs) {
  7162. continue;
  7163. }
  7164. // debug('faceIndexAB', faceIndexA, faceIndexB, sharpEdges[i]);
  7165. // Prepare subdivided uv
  7166. avgUv = new THREE.UV();
  7167. avgUv.u = getUV(edgeVertexA, faceIndexA).u + getUV(edgeVertexB, faceIndexA).u;
  7168. avgUv.v = getUV(edgeVertexA, faceIndexA).v + getUV(edgeVertexB, faceIndexA).v;
  7169. avgUv.u /= 2;
  7170. avgUv.v /= 2;
  7171. addUV(edgePoints[i], faceIndexA, avgUv);
  7172. if (!sharpEdges[i]) {
  7173. avgUv = new THREE.UV();
  7174. avgUv.u = getUV(edgeVertexA, faceIndexB).u + getUV(edgeVertexB, faceIndexB).u;
  7175. avgUv.v = getUV(edgeVertexA, faceIndexB).v + getUV(edgeVertexB, faceIndexB).v;
  7176. avgUv.u /= 2;
  7177. avgUv.v /= 2;
  7178. addUV(edgePoints[i], faceIndexB, avgUv);
  7179. }
  7180. }
  7181. debug('-- Step 2 done');
  7182. // Step 3
  7183. // For each face point, add an edge for every edge of the face,
  7184. // connecting the face point to each edge point for the face.
  7185. var facePt, currentVerticeIndex;
  7186. var hashAB, hashBC, hashCD, hashDA, hashCA;
  7187. var abc123 = ['123', '12', '2', '23'];
  7188. var bca123 = ['123', '23', '3', '31'];
  7189. var cab123 = ['123', '31', '1', '12'];
  7190. var abc1234 = ['1234', '12', '2', '23'];
  7191. var bcd1234 = ['1234', '23', '3', '34'];
  7192. var cda1234 = ['1234', '34', '4', '41'];
  7193. var dab1234 = ['1234', '41', '1', '12'];
  7194. for (i=0, il = facePoints.length; i<il ;i++) { // for every face
  7195. facePt = facePoints[i];
  7196. face = originalFaces[i];
  7197. currentVerticeIndex = originalVerticesLength+ i;
  7198. if ( face instanceof THREE.Face3 ) {
  7199. // create 3 face4s
  7200. hashAB = edge_hash( face.a, face.b );
  7201. hashBC = edge_hash( face.b, face.c );
  7202. hashCA = edge_hash( face.c, face.a );
  7203. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123, i );
  7204. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123, i );
  7205. f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123, i );
  7206. } else if ( face instanceof THREE.Face4 ) {
  7207. // create 4 face4s
  7208. hashAB = edge_hash( face.a, face.b );
  7209. hashBC = edge_hash( face.b, face.c );
  7210. hashCD = edge_hash( face.c, face.d );
  7211. hashDA = edge_hash( face.d, face.a );
  7212. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234, i );
  7213. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234, i );
  7214. f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234, i );
  7215. f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234, i );
  7216. } else {
  7217. debug('face should be a face!', face);
  7218. }
  7219. }
  7220. newVertices = newPoints;
  7221. // debug('original ', oldGeometry.vertices.length, oldGeometry.faces.length );
  7222. // debug('new points', newPoints.length, 'faces', newFaces.length );
  7223. // Step 4
  7224. // For each original point P,
  7225. // take the average F of all n face points for faces touching P,
  7226. // and take the average R of all n edge midpoints for edges touching P,
  7227. // where each edge midpoint is the average of its two endpoint vertices.
  7228. // Move each original point to the point
  7229. var F = new THREE.Vector3();
  7230. var R = new THREE.Vector3();
  7231. var n;
  7232. for (i=0, il = originalPoints.length; i<il; i++) {
  7233. // (F + 2R + (n-3)P) / n
  7234. if (vertexEdgeMap[i]===undefined) continue;
  7235. F.set(0,0,0);
  7236. R.set(0,0,0);
  7237. var newPos = new THREE.Vector3(0,0,0);
  7238. var f =0;
  7239. for (j in vertexFaceMap[i]) {
  7240. F.addSelf(facePoints[j]);
  7241. f++;
  7242. }
  7243. var sharpEdgeCount = 0;
  7244. n = vertexEdgeMap[i].length;
  7245. for (j=0;j<n;j++) {
  7246. if (
  7247. sharpEdges[
  7248. edge_hash(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
  7249. ]) {
  7250. sharpEdgeCount++;
  7251. }
  7252. }
  7253. if ( sharpEdgeCount==2 ) {
  7254. continue;
  7255. // Do not move vertex if there's 2 connecting sharp edges.
  7256. }
  7257. /*
  7258. if (sharpEdgeCount>2) {
  7259. // TODO
  7260. }
  7261. */
  7262. F.divideScalar(f);
  7263. for (j=0; j<n;j++) {
  7264. edge = vertexEdgeMap[i][j];
  7265. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  7266. R.addSelf(midPt);
  7267. // R.addSelf(originalPoints[edge[0]]);
  7268. // R.addSelf(originalPoints[edge[1]]);
  7269. }
  7270. R.divideScalar(n);
  7271. newPos.addSelf(originalPoints[i]);
  7272. newPos.multiplyScalar(n - 3);
  7273. newPos.addSelf(F);
  7274. newPos.addSelf(R.multiplyScalar(2));
  7275. newPos.divideScalar(n);
  7276. newVertices[i] = newPos;
  7277. }
  7278. var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
  7279. newGeometry.vertices = newVertices;
  7280. newGeometry.faces = newFaces;
  7281. newGeometry.faceVertexUvs[ 0 ] = newUVs;
  7282. delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
  7283. newGeometry.computeCentroids();
  7284. newGeometry.computeFaceNormals();
  7285. newGeometry.computeVertexNormals();
  7286. };
  7287. /**
  7288. * @author alteredq / http://alteredqualia.com/
  7289. */
  7290. THREE.ImmediateRenderObject = function ( ) {
  7291. THREE.Object3D.call( this );
  7292. this.render = function ( renderCallback ) { };
  7293. };
  7294. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  7295. /**
  7296. * @author mikael emtinger / http://gomo.se/
  7297. * @author alteredq / http://alteredqualia.com/
  7298. */
  7299. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  7300. THREE.Object3D.call( this );
  7301. this.lensFlares = [];
  7302. this.positionScreen = new THREE.Vector3();
  7303. this.customUpdateCallback = undefined;
  7304. if( texture !== undefined ) {
  7305. this.add( texture, size, distance, blending, color );
  7306. }
  7307. };
  7308. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  7309. /*
  7310. * Add: adds another flare
  7311. */
  7312. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  7313. if( size === undefined ) size = -1;
  7314. if( distance === undefined ) distance = 0;
  7315. if( opacity === undefined ) opacity = 1;
  7316. if( color === undefined ) color = new THREE.Color( 0xffffff );
  7317. if( blending === undefined ) blending = THREE.NormalBlending;
  7318. distance = Math.min( distance, Math.max( 0, distance ) );
  7319. this.lensFlares.push( { texture: texture, // THREE.Texture
  7320. size: size, // size in pixels (-1 = use texture.width)
  7321. distance: distance, // distance (0-1) from light source (0=at light source)
  7322. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  7323. scale: 1, // scale
  7324. rotation: 1, // rotation
  7325. opacity: opacity, // opacity
  7326. color: color, // color
  7327. blending: blending } ); // blending
  7328. };
  7329. /*
  7330. * Update lens flares update positions on all flares based on the screen position
  7331. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  7332. */
  7333. THREE.LensFlare.prototype.updateLensFlares = function () {
  7334. var f, fl = this.lensFlares.length;
  7335. var flare;
  7336. var vecX = -this.positionScreen.x * 2;
  7337. var vecY = -this.positionScreen.y * 2;
  7338. for( f = 0; f < fl; f ++ ) {
  7339. flare = this.lensFlares[ f ];
  7340. flare.x = this.positionScreen.x + vecX * flare.distance;
  7341. flare.y = this.positionScreen.y + vecY * flare.distance;
  7342. flare.wantedRotation = flare.x * Math.PI * 0.25;
  7343. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  7344. }
  7345. };
  7346. /**
  7347. * @author alteredq / http://alteredqualia.com/
  7348. */
  7349. THREE.MorphBlendMesh = function( geometry, material ) {
  7350. THREE.Mesh.call( this, geometry, material );
  7351. this.animationsMap = {};
  7352. this.animationsList = [];
  7353. // prepare default animation
  7354. // (all frames played together in 1 second)
  7355. var numFrames = this.geometry.morphTargets.length;
  7356. var name = "__default";
  7357. var startFrame = 0;
  7358. var endFrame = numFrames - 1;
  7359. var fps = numFrames / 1;
  7360. this.createAnimation( name, startFrame, endFrame, fps );
  7361. this.setAnimationWeight( name, 1 );
  7362. };
  7363. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  7364. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  7365. var animation = {
  7366. startFrame: start,
  7367. endFrame: end,
  7368. length: end - start + 1,
  7369. fps: fps,
  7370. duration: ( end - start ) / fps,
  7371. lastFrame: 0,
  7372. currentFrame: 0,
  7373. active: false,
  7374. time: 0,
  7375. direction: 1,
  7376. weight: 1,
  7377. directionBackwards: false,
  7378. mirroredLoop: false
  7379. };
  7380. this.animationsMap[ name ] = animation;
  7381. this.animationsList.push( animation );
  7382. };
  7383. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  7384. var pattern = /([a-z]+)(\d+)/;
  7385. var firstAnimation, frameRanges = {};
  7386. var geometry = this.geometry;
  7387. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  7388. var morph = geometry.morphTargets[ i ];
  7389. var chunks = morph.name.match( pattern );
  7390. if ( chunks && chunks.length > 1 ) {
  7391. var name = chunks[ 1 ];
  7392. var num = chunks[ 2 ];
  7393. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  7394. var range = frameRanges[ name ];
  7395. if ( i < range.start ) range.start = i;
  7396. if ( i > range.end ) range.end = i;
  7397. if ( ! firstAnimation ) firstAnimation = name;
  7398. }
  7399. }
  7400. for ( var name in frameRanges ) {
  7401. var range = frameRanges[ name ];
  7402. this.createAnimation( name, range.start, range.end, fps );
  7403. }
  7404. this.firstAnimation = firstAnimation;
  7405. };
  7406. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  7407. var animation = this.animationsMap[ name ];
  7408. if ( animation ) {
  7409. animation.direction = 1;
  7410. animation.directionBackwards = false;
  7411. }
  7412. };
  7413. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  7414. var animation = this.animationsMap[ name ];
  7415. if ( animation ) {
  7416. animation.direction = -1;
  7417. animation.directionBackwards = true;
  7418. }
  7419. };
  7420. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  7421. var animation = this.animationsMap[ name ];
  7422. if ( animation ) {
  7423. animation.fps = fps;
  7424. animation.duration = ( animation.end - animation.start ) / animation.fps;
  7425. }
  7426. };
  7427. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  7428. var animation = this.animationsMap[ name ];
  7429. if ( animation ) {
  7430. animation.duration = duration;
  7431. animation.fps = ( animation.end - animation.start ) / animation.duration;
  7432. }
  7433. };
  7434. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  7435. var animation = this.animationsMap[ name ];
  7436. if ( animation ) {
  7437. animation.weight = weight;
  7438. }
  7439. };
  7440. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  7441. var animation = this.animationsMap[ name ];
  7442. if ( animation ) {
  7443. animation.time = time;
  7444. }
  7445. };
  7446. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  7447. var time = 0;
  7448. var animation = this.animationsMap[ name ];
  7449. if ( animation ) {
  7450. time = animation.time;
  7451. }
  7452. return time;
  7453. };
  7454. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  7455. var duration = -1;
  7456. var animation = this.animationsMap[ name ];
  7457. if ( animation ) {
  7458. duration = animation.duration;
  7459. }
  7460. return duration;
  7461. };
  7462. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  7463. var animation = this.animationsMap[ name ];
  7464. if ( animation ) {
  7465. animation.time = 0;
  7466. animation.active = true;
  7467. } else {
  7468. console.warn( "animation[" + name + "] undefined" );
  7469. }
  7470. };
  7471. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  7472. var animation = this.animationsMap[ name ];
  7473. if ( animation ) {
  7474. animation.active = false;
  7475. }
  7476. };
  7477. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  7478. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  7479. var animation = this.animationsList[ i ];
  7480. if ( ! animation.active ) continue;
  7481. var frameTime = animation.duration / animation.length;
  7482. animation.time += animation.direction * delta;
  7483. if ( animation.mirroredLoop ) {
  7484. if ( animation.time > animation.duration || animation.time < 0 ) {
  7485. animation.direction *= -1;
  7486. if ( animation.time > animation.duration ) {
  7487. animation.time = animation.duration;
  7488. animation.directionBackwards = true;
  7489. }
  7490. if ( animation.time < 0 ) {
  7491. animation.time = 0;
  7492. animation.directionBackwards = false;
  7493. }
  7494. }
  7495. } else {
  7496. animation.time = animation.time % animation.duration;
  7497. if ( animation.time < 0 ) animation.time += animation.duration;
  7498. }
  7499. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  7500. var weight = animation.weight;
  7501. if ( keyframe !== animation.currentFrame ) {
  7502. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  7503. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  7504. this.morphTargetInfluences[ keyframe ] = 0;
  7505. animation.lastFrame = animation.currentFrame;
  7506. animation.currentFrame = keyframe;
  7507. }
  7508. var mix = ( animation.time % frameTime ) / frameTime;
  7509. if ( animation.directionBackwards ) mix = 1 - mix;
  7510. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  7511. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  7512. }
  7513. };
  7514. /**
  7515. * @author mikael emtinger / http://gomo.se/
  7516. * @author alteredq / http://alteredqualia.com/
  7517. */
  7518. THREE.LensFlarePlugin = function ( ) {
  7519. var _gl, _renderer, _lensFlare = {};
  7520. this.init = function ( renderer ) {
  7521. _gl = renderer.context;
  7522. _renderer = renderer;
  7523. _lensFlare.vertices = new Float32Array( 8 + 8 );
  7524. _lensFlare.faces = new Uint16Array( 6 );
  7525. var i = 0;
  7526. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  7527. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  7528. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  7529. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  7530. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  7531. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  7532. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  7533. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  7534. i = 0;
  7535. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  7536. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  7537. // buffers
  7538. _lensFlare.vertexBuffer = _gl.createBuffer();
  7539. _lensFlare.elementBuffer = _gl.createBuffer();
  7540. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  7541. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  7542. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  7543. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  7544. // textures
  7545. _lensFlare.tempTexture = _gl.createTexture();
  7546. _lensFlare.occlusionTexture = _gl.createTexture();
  7547. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  7548. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  7549. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  7550. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  7551. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  7552. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  7553. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  7554. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  7555. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  7556. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  7557. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  7558. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  7559. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  7560. _lensFlare.hasVertexTexture = false;
  7561. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  7562. } else {
  7563. _lensFlare.hasVertexTexture = true;
  7564. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  7565. }
  7566. _lensFlare.attributes = {};
  7567. _lensFlare.uniforms = {};
  7568. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  7569. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  7570. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  7571. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  7572. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  7573. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  7574. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  7575. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  7576. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  7577. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  7578. _lensFlare.attributesEnabled = false;
  7579. };
  7580. /*
  7581. * Render lens flares
  7582. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  7583. * reads these back and calculates occlusion.
  7584. * Then _lensFlare.update_lensFlares() is called to re-position and
  7585. * update transparency of flares. Then they are rendered.
  7586. *
  7587. */
  7588. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  7589. var flares = scene.__webglFlares,
  7590. nFlares = flares.length;
  7591. if ( ! nFlares ) return;
  7592. var tempPosition = new THREE.Vector3();
  7593. var invAspect = viewportHeight / viewportWidth,
  7594. halfViewportWidth = viewportWidth * 0.5,
  7595. halfViewportHeight = viewportHeight * 0.5;
  7596. var size = 16 / viewportHeight,
  7597. scale = new THREE.Vector2( size * invAspect, size );
  7598. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  7599. screenPositionPixels = new THREE.Vector2( 1, 1 );
  7600. var uniforms = _lensFlare.uniforms,
  7601. attributes = _lensFlare.attributes;
  7602. // set _lensFlare program and reset blending
  7603. _gl.useProgram( _lensFlare.program );
  7604. if ( ! _lensFlare.attributesEnabled ) {
  7605. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  7606. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  7607. _lensFlare.attributesEnabled = true;
  7608. }
  7609. // loop through all lens flares to update their occlusion and positions
  7610. // setup gl and common used attribs/unforms
  7611. _gl.uniform1i( uniforms.occlusionMap, 0 );
  7612. _gl.uniform1i( uniforms.map, 1 );
  7613. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  7614. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  7615. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  7616. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  7617. _gl.disable( _gl.CULL_FACE );
  7618. _gl.depthMask( false );
  7619. var i, j, jl, flare, sprite;
  7620. for ( i = 0; i < nFlares; i ++ ) {
  7621. size = 16 / viewportHeight;
  7622. scale.set( size * invAspect, size );
  7623. // calc object screen position
  7624. flare = flares[ i ];
  7625. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  7626. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  7627. camera.projectionMatrix.multiplyVector3( tempPosition );
  7628. // setup arrays for gl programs
  7629. screenPosition.copy( tempPosition )
  7630. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  7631. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  7632. // screen cull
  7633. if ( _lensFlare.hasVertexTexture || (
  7634. screenPositionPixels.x > 0 &&
  7635. screenPositionPixels.x < viewportWidth &&
  7636. screenPositionPixels.y > 0 &&
  7637. screenPositionPixels.y < viewportHeight ) ) {
  7638. // save current RGB to temp texture
  7639. _gl.activeTexture( _gl.TEXTURE1 );
  7640. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  7641. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  7642. // render pink quad
  7643. _gl.uniform1i( uniforms.renderType, 0 );
  7644. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  7645. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  7646. _gl.disable( _gl.BLEND );
  7647. _gl.enable( _gl.DEPTH_TEST );
  7648. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  7649. // copy result to occlusionMap
  7650. _gl.activeTexture( _gl.TEXTURE0 );
  7651. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  7652. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  7653. // restore graphics
  7654. _gl.uniform1i( uniforms.renderType, 1 );
  7655. _gl.disable( _gl.DEPTH_TEST );
  7656. _gl.activeTexture( _gl.TEXTURE1 );
  7657. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  7658. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  7659. // update object positions
  7660. flare.positionScreen.copy( screenPosition )
  7661. if ( flare.customUpdateCallback ) {
  7662. flare.customUpdateCallback( flare );
  7663. } else {
  7664. flare.updateLensFlares();
  7665. }
  7666. // render flares
  7667. _gl.uniform1i( uniforms.renderType, 2 );
  7668. _gl.enable( _gl.BLEND );
  7669. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  7670. sprite = flare.lensFlares[ j ];
  7671. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  7672. screenPosition.x = sprite.x;
  7673. screenPosition.y = sprite.y;
  7674. screenPosition.z = sprite.z;
  7675. size = sprite.size * sprite.scale / viewportHeight;
  7676. scale.x = size * invAspect;
  7677. scale.y = size;
  7678. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  7679. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  7680. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  7681. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  7682. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  7683. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  7684. _renderer.setTexture( sprite.texture, 1 );
  7685. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  7686. }
  7687. }
  7688. }
  7689. }
  7690. // restore gl
  7691. _gl.enable( _gl.CULL_FACE );
  7692. _gl.enable( _gl.DEPTH_TEST );
  7693. _gl.depthMask( true );
  7694. };
  7695. function createProgram ( shader ) {
  7696. var program = _gl.createProgram();
  7697. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  7698. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  7699. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  7700. _gl.shaderSource( vertexShader, shader.vertexShader );
  7701. _gl.compileShader( fragmentShader );
  7702. _gl.compileShader( vertexShader );
  7703. _gl.attachShader( program, fragmentShader );
  7704. _gl.attachShader( program, vertexShader );
  7705. _gl.linkProgram( program );
  7706. return program;
  7707. };
  7708. };/**
  7709. * @author alteredq / http://alteredqualia.com/
  7710. */
  7711. THREE.ShadowMapPlugin = function ( ) {
  7712. var _gl,
  7713. _renderer,
  7714. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin,
  7715. _frustum = new THREE.Frustum(),
  7716. _projScreenMatrix = new THREE.Matrix4(),
  7717. _min = new THREE.Vector3(),
  7718. _max = new THREE.Vector3();
  7719. this.init = function ( renderer ) {
  7720. _gl = renderer.context;
  7721. _renderer = renderer;
  7722. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  7723. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  7724. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  7725. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  7726. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  7727. _depthMaterial._shadowPass = true;
  7728. _depthMaterialMorph._shadowPass = true;
  7729. _depthMaterialSkin._shadowPass = true;
  7730. };
  7731. this.render = function ( scene, camera ) {
  7732. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  7733. this.update( scene, camera );
  7734. };
  7735. this.update = function ( scene, camera ) {
  7736. var i, il, j, jl, n,
  7737. shadowMap, shadowMatrix, shadowCamera,
  7738. program, buffer, material,
  7739. webglObject, object, light,
  7740. renderList,
  7741. lights = [],
  7742. k = 0,
  7743. fog = null;
  7744. // set GL state for depth map
  7745. _gl.clearColor( 1, 1, 1, 1 );
  7746. _gl.disable( _gl.BLEND );
  7747. _gl.enable( _gl.CULL_FACE );
  7748. if ( _renderer.shadowMapCullFrontFaces ) {
  7749. _gl.cullFace( _gl.FRONT );
  7750. } else {
  7751. _gl.cullFace( _gl.BACK );
  7752. }
  7753. _renderer.setDepthTest( true );
  7754. // preprocess lights
  7755. // - skip lights that are not casting shadows
  7756. // - create virtual lights for cascaded shadow maps
  7757. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  7758. light = scene.__lights[ i ];
  7759. if ( ! light.castShadow ) continue;
  7760. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  7761. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  7762. var virtualLight;
  7763. if ( ! light.shadowCascadeArray[ n ] ) {
  7764. virtualLight = createVirtualLight( light, n );
  7765. virtualLight.originalCamera = camera;
  7766. var gyro = new THREE.Gyroscope();
  7767. gyro.position = light.shadowCascadeOffset;
  7768. gyro.add( virtualLight );
  7769. gyro.add( virtualLight.target );
  7770. camera.add( gyro );
  7771. light.shadowCascadeArray[ n ] = virtualLight;
  7772. console.log( "Created virtualLight", virtualLight );
  7773. } else {
  7774. virtualLight = light.shadowCascadeArray[ n ];
  7775. }
  7776. updateVirtualLight( light, n );
  7777. lights[ k ] = virtualLight;
  7778. k ++;
  7779. }
  7780. } else {
  7781. lights[ k ] = light;
  7782. k ++;
  7783. }
  7784. }
  7785. // render depth map
  7786. for ( i = 0, il = lights.length; i < il; i ++ ) {
  7787. light = lights[ i ];
  7788. if ( ! light.shadowMap ) {
  7789. var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  7790. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  7791. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  7792. light.shadowMatrix = new THREE.Matrix4();
  7793. }
  7794. if ( ! light.shadowCamera ) {
  7795. if ( light instanceof THREE.SpotLight ) {
  7796. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  7797. } else if ( light instanceof THREE.DirectionalLight ) {
  7798. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  7799. } else {
  7800. console.error( "Unsupported light type for shadow" );
  7801. continue;
  7802. }
  7803. scene.add( light.shadowCamera );
  7804. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  7805. }
  7806. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  7807. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  7808. light.shadowCamera.add( light.cameraHelper );
  7809. }
  7810. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  7811. updateShadowCamera( camera, light );
  7812. }
  7813. shadowMap = light.shadowMap;
  7814. shadowMatrix = light.shadowMatrix;
  7815. shadowCamera = light.shadowCamera;
  7816. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  7817. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  7818. shadowCamera.updateMatrixWorld();
  7819. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  7820. if ( light.cameraHelper ) light.cameraHelper.lines.visible = light.shadowCameraVisible;
  7821. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  7822. // compute shadow matrix
  7823. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  7824. 0.0, 0.5, 0.0, 0.5,
  7825. 0.0, 0.0, 0.5, 0.5,
  7826. 0.0, 0.0, 0.0, 1.0 );
  7827. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  7828. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  7829. // update camera matrices and frustum
  7830. if ( ! shadowCamera._viewMatrixArray ) shadowCamera._viewMatrixArray = new Float32Array( 16 );
  7831. if ( ! shadowCamera._projectionMatrixArray ) shadowCamera._projectionMatrixArray = new Float32Array( 16 );
  7832. shadowCamera.matrixWorldInverse.flattenToArray( shadowCamera._viewMatrixArray );
  7833. shadowCamera.projectionMatrix.flattenToArray( shadowCamera._projectionMatrixArray );
  7834. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  7835. _frustum.setFromMatrix( _projScreenMatrix );
  7836. // render shadow map
  7837. _renderer.setRenderTarget( shadowMap );
  7838. _renderer.clear();
  7839. // set object matrices & frustum culling
  7840. renderList = scene.__webglObjects;
  7841. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  7842. webglObject = renderList[ j ];
  7843. object = webglObject.object;
  7844. webglObject.render = false;
  7845. if ( object.visible && object.castShadow ) {
  7846. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  7847. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  7848. webglObject.render = true;
  7849. }
  7850. }
  7851. }
  7852. // render regular objects
  7853. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  7854. webglObject = renderList[ j ];
  7855. if ( webglObject.render ) {
  7856. object = webglObject.object;
  7857. buffer = webglObject.buffer;
  7858. // culling is overriden globally for all objects
  7859. // while rendering depth map
  7860. //_renderer.setObjectFaces( object );
  7861. if ( object.customDepthMaterial ) {
  7862. material = object.customDepthMaterial;
  7863. } else if ( object.geometry.morphTargets.length ) {
  7864. material = _depthMaterialMorph;
  7865. } else if ( object instanceof THREE.SkinnedMesh ) {
  7866. material = _depthMaterialSkin;
  7867. } else {
  7868. material = _depthMaterial;
  7869. }
  7870. if ( buffer instanceof THREE.BufferGeometry ) {
  7871. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  7872. } else {
  7873. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  7874. }
  7875. }
  7876. }
  7877. // set matrices and render immediate objects
  7878. renderList = scene.__webglObjectsImmediate;
  7879. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  7880. webglObject = renderList[ j ];
  7881. object = webglObject.object;
  7882. if ( object.visible && object.castShadow ) {
  7883. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  7884. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  7885. }
  7886. }
  7887. }
  7888. // restore GL state
  7889. var clearColor = _renderer.getClearColor(),
  7890. clearAlpha = _renderer.getClearAlpha();
  7891. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  7892. _gl.enable( _gl.BLEND );
  7893. if ( _renderer.shadowMapCullFrontFaces ) {
  7894. _gl.cullFace( _gl.BACK );
  7895. }
  7896. };
  7897. function createVirtualLight( light, cascade ) {
  7898. var virtualLight = new THREE.DirectionalLight();
  7899. virtualLight.isVirtual = true;
  7900. virtualLight.onlyShadow = true;
  7901. virtualLight.castShadow = true;
  7902. virtualLight.shadowCameraNear = light.shadowCameraNear;
  7903. virtualLight.shadowCameraFar = light.shadowCameraFar;
  7904. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  7905. virtualLight.shadowCameraRight = light.shadowCameraRight;
  7906. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  7907. virtualLight.shadowCameraTop = light.shadowCameraTop;
  7908. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  7909. virtualLight.shadowDarkness = light.shadowDarkness;
  7910. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  7911. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  7912. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  7913. virtualLight.pointsWorld = [];
  7914. virtualLight.pointsFrustum = [];
  7915. var pointsWorld = virtualLight.pointsWorld,
  7916. pointsFrustum = virtualLight.pointsFrustum;
  7917. for ( var i = 0; i < 8; i ++ ) {
  7918. pointsWorld[ i ] = new THREE.Vector3();
  7919. pointsFrustum[ i ] = new THREE.Vector3();
  7920. }
  7921. var nearZ = light.shadowCascadeNearZ[ cascade ];
  7922. var farZ = light.shadowCascadeFarZ[ cascade ];
  7923. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  7924. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  7925. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  7926. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  7927. pointsFrustum[ 4 ].set( -1, -1, farZ );
  7928. pointsFrustum[ 5 ].set( 1, -1, farZ );
  7929. pointsFrustum[ 6 ].set( -1, 1, farZ );
  7930. pointsFrustum[ 7 ].set( 1, 1, farZ );
  7931. return virtualLight;
  7932. }
  7933. // Synchronize virtual light with the original light
  7934. function updateVirtualLight( light, cascade ) {
  7935. var virtualLight = light.shadowCascadeArray[ cascade ];
  7936. virtualLight.position.copy( light.position );
  7937. virtualLight.target.position.copy( light.target.position );
  7938. virtualLight.lookAt( virtualLight.target );
  7939. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  7940. virtualLight.shadowDarkness = light.shadowDarkness;
  7941. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  7942. var nearZ = light.shadowCascadeNearZ[ cascade ];
  7943. var farZ = light.shadowCascadeFarZ[ cascade ];
  7944. var pointsFrustum = virtualLight.pointsFrustum;
  7945. pointsFrustum[ 0 ].z = nearZ;
  7946. pointsFrustum[ 1 ].z = nearZ;
  7947. pointsFrustum[ 2 ].z = nearZ;
  7948. pointsFrustum[ 3 ].z = nearZ;
  7949. pointsFrustum[ 4 ].z = farZ;
  7950. pointsFrustum[ 5 ].z = farZ;
  7951. pointsFrustum[ 6 ].z = farZ;
  7952. pointsFrustum[ 7 ].z = farZ;
  7953. }
  7954. // Fit shadow camera's ortho frustum to camera frustum
  7955. function updateShadowCamera( camera, light ) {
  7956. var shadowCamera = light.shadowCamera,
  7957. pointsFrustum = light.pointsFrustum,
  7958. pointsWorld = light.pointsWorld;
  7959. _min.set( Infinity, Infinity, Infinity );
  7960. _max.set( -Infinity, -Infinity, -Infinity );
  7961. for ( var i = 0; i < 8; i ++ ) {
  7962. var p = pointsWorld[ i ];
  7963. p.copy( pointsFrustum[ i ] );
  7964. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  7965. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  7966. if ( p.x < _min.x ) _min.x = p.x;
  7967. if ( p.x > _max.x ) _max.x = p.x;
  7968. if ( p.y < _min.y ) _min.y = p.y;
  7969. if ( p.y > _max.y ) _max.y = p.y;
  7970. if ( p.z < _min.z ) _min.z = p.z;
  7971. if ( p.z > _max.z ) _max.z = p.z;
  7972. }
  7973. shadowCamera.left = _min.x;
  7974. shadowCamera.right = _max.x;
  7975. shadowCamera.top = _max.y;
  7976. shadowCamera.bottom = _min.y;
  7977. // can't really fit near/far
  7978. //shadowCamera.near = _min.z;
  7979. //shadowCamera.far = _max.z;
  7980. shadowCamera.updateProjectionMatrix();
  7981. }
  7982. };
  7983. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  7984. /**
  7985. * @author mikael emtinger / http://gomo.se/
  7986. * @author alteredq / http://alteredqualia.com/
  7987. */
  7988. THREE.SpritePlugin = function ( ) {
  7989. var _gl, _renderer, _sprite = {};
  7990. this.init = function ( renderer ) {
  7991. _gl = renderer.context;
  7992. _renderer = renderer;
  7993. _sprite.vertices = new Float32Array( 8 + 8 );
  7994. _sprite.faces = new Uint16Array( 6 );
  7995. var i = 0;
  7996. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  7997. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  7998. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  7999. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  8000. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  8001. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  8002. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  8003. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  8004. i = 0;
  8005. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  8006. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  8007. _sprite.vertexBuffer = _gl.createBuffer();
  8008. _sprite.elementBuffer = _gl.createBuffer();
  8009. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  8010. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  8011. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  8012. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  8013. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  8014. _sprite.attributes = {};
  8015. _sprite.uniforms = {};
  8016. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  8017. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  8018. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  8019. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  8020. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  8021. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  8022. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  8023. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  8024. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  8025. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  8026. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  8027. _sprite.uniforms.affectedByDistance = _gl.getUniformLocation( _sprite.program, "affectedByDistance" );
  8028. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  8029. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  8030. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  8031. _sprite.attributesEnabled = false;
  8032. };
  8033. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  8034. var sprites = scene.__webglSprites,
  8035. nSprites = sprites.length;
  8036. if ( ! nSprites ) return;
  8037. var attributes = _sprite.attributes,
  8038. uniforms = _sprite.uniforms;
  8039. var invAspect = viewportHeight / viewportWidth;
  8040. var halfViewportWidth = viewportWidth * 0.5,
  8041. halfViewportHeight = viewportHeight * 0.5;
  8042. var mergeWith3D = true;
  8043. // setup gl
  8044. _gl.useProgram( _sprite.program );
  8045. if ( ! _sprite.attributesEnabled ) {
  8046. _gl.enableVertexAttribArray( attributes.position );
  8047. _gl.enableVertexAttribArray( attributes.uv );
  8048. _sprite.attributesEnabled = true;
  8049. }
  8050. _gl.disable( _gl.CULL_FACE );
  8051. _gl.enable( _gl.BLEND );
  8052. _gl.depthMask( true );
  8053. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  8054. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  8055. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  8056. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  8057. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  8058. _gl.activeTexture( _gl.TEXTURE0 );
  8059. _gl.uniform1i( uniforms.map, 0 );
  8060. // update positions and sort
  8061. var i, sprite, screenPosition, size, scale = [];
  8062. for( i = 0; i < nSprites; i ++ ) {
  8063. sprite = sprites[ i ];
  8064. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  8065. if( ! sprite.useScreenCoordinates ) {
  8066. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld );
  8067. sprite.z = - sprite._modelViewMatrix.elements[14];
  8068. } else {
  8069. sprite.z = - sprite.position.z;
  8070. }
  8071. }
  8072. sprites.sort( painterSort );
  8073. // render all sprites
  8074. for( i = 0; i < nSprites; i ++ ) {
  8075. sprite = sprites[ i ];
  8076. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  8077. if ( sprite.map && sprite.map.image && sprite.map.image.width ) {
  8078. if ( sprite.useScreenCoordinates ) {
  8079. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  8080. _gl.uniform3f( uniforms.screenPosition, ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  8081. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  8082. Math.max( 0, Math.min( 1, sprite.position.z ) ) );
  8083. } else {
  8084. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  8085. _gl.uniform1i( uniforms.affectedByDistance, sprite.affectedByDistance ? 1 : 0 );
  8086. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  8087. }
  8088. size = sprite.map.image.width / ( sprite.scaleByViewport ? viewportHeight : 1 );
  8089. scale[ 0 ] = size * invAspect * sprite.scale.x;
  8090. scale[ 1 ] = size * sprite.scale.y;
  8091. _gl.uniform2f( uniforms.uvScale, sprite.uvScale.x, sprite.uvScale.y );
  8092. _gl.uniform2f( uniforms.uvOffset, sprite.uvOffset.x, sprite.uvOffset.y );
  8093. _gl.uniform2f( uniforms.alignment, sprite.alignment.x, sprite.alignment.y );
  8094. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  8095. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  8096. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  8097. _gl.uniform2fv( uniforms.scale, scale );
  8098. if ( sprite.mergeWith3D && !mergeWith3D ) {
  8099. _gl.enable( _gl.DEPTH_TEST );
  8100. mergeWith3D = true;
  8101. } else if ( ! sprite.mergeWith3D && mergeWith3D ) {
  8102. _gl.disable( _gl.DEPTH_TEST );
  8103. mergeWith3D = false;
  8104. }
  8105. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  8106. _renderer.setTexture( sprite.map, 0 );
  8107. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  8108. }
  8109. }
  8110. // restore gl
  8111. _gl.enable( _gl.CULL_FACE );
  8112. _gl.enable( _gl.DEPTH_TEST );
  8113. _gl.depthMask( true );
  8114. };
  8115. function createProgram ( shader ) {
  8116. var program = _gl.createProgram();
  8117. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  8118. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  8119. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  8120. _gl.shaderSource( vertexShader, shader.vertexShader );
  8121. _gl.compileShader( fragmentShader );
  8122. _gl.compileShader( vertexShader );
  8123. _gl.attachShader( program, fragmentShader );
  8124. _gl.attachShader( program, vertexShader );
  8125. _gl.linkProgram( program );
  8126. return program;
  8127. };
  8128. function painterSort ( a, b ) {
  8129. return b.z - a.z;
  8130. };
  8131. };/**
  8132. * @author alteredq / http://alteredqualia.com/
  8133. */
  8134. THREE.DepthPassPlugin = function ( ) {
  8135. this.enabled = false;
  8136. this.renderTarget = null;
  8137. var _gl,
  8138. _renderer,
  8139. _depthMaterial, _depthMaterialMorph,
  8140. _frustum = new THREE.Frustum(),
  8141. _projScreenMatrix = new THREE.Matrix4();
  8142. this.init = function ( renderer ) {
  8143. _gl = renderer.context;
  8144. _renderer = renderer;
  8145. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  8146. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  8147. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  8148. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  8149. _depthMaterial._shadowPass = true;
  8150. _depthMaterialMorph._shadowPass = true;
  8151. };
  8152. this.render = function ( scene, camera ) {
  8153. if ( ! this.enabled ) return;
  8154. this.update( scene, camera );
  8155. };
  8156. this.update = function ( scene, camera ) {
  8157. var i, il, j, jl, n,
  8158. program, buffer, material,
  8159. webglObject, object, light,
  8160. renderList,
  8161. fog = null;
  8162. // set GL state for depth map
  8163. _gl.clearColor( 1, 1, 1, 1 );
  8164. _gl.disable( _gl.BLEND );
  8165. _renderer.setDepthTest( true );
  8166. // update scene
  8167. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  8168. // update camera matrices and frustum
  8169. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  8170. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  8171. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  8172. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  8173. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  8174. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  8175. _frustum.setFromMatrix( _projScreenMatrix );
  8176. // render depth map
  8177. _renderer.setRenderTarget( this.renderTarget );
  8178. _renderer.clear();
  8179. // set object matrices & frustum culling
  8180. renderList = scene.__webglObjects;
  8181. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  8182. webglObject = renderList[ j ];
  8183. object = webglObject.object;
  8184. webglObject.render = false;
  8185. if ( object.visible ) {
  8186. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  8187. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  8188. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  8189. webglObject.render = true;
  8190. }
  8191. }
  8192. }
  8193. // render regular objects
  8194. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  8195. webglObject = renderList[ j ];
  8196. if ( webglObject.render ) {
  8197. object = webglObject.object;
  8198. buffer = webglObject.buffer;
  8199. _renderer.setObjectFaces( object );
  8200. if ( object.customDepthMaterial ) {
  8201. material = object.customDepthMaterial;
  8202. } else if ( object.geometry.morphTargets.length ) {
  8203. material = _depthMaterialMorph;
  8204. } else {
  8205. material = _depthMaterial;
  8206. }
  8207. if ( buffer instanceof THREE.BufferGeometry ) {
  8208. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  8209. } else {
  8210. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  8211. }
  8212. }
  8213. }
  8214. // set matrices and render immediate objects
  8215. renderList = scene.__webglObjectsImmediate;
  8216. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  8217. webglObject = renderList[ j ];
  8218. object = webglObject.object;
  8219. if ( object.visible && object.castShadow ) {
  8220. /*
  8221. if ( object.matrixAutoUpdate ) {
  8222. object.matrixWorld.flattenToArray( object._objectMatrixArray );
  8223. }
  8224. */
  8225. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  8226. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  8227. }
  8228. }
  8229. // restore GL state
  8230. var clearColor = _renderer.getClearColor(),
  8231. clearAlpha = _renderer.getClearAlpha();
  8232. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  8233. _gl.enable( _gl.BLEND );
  8234. };
  8235. };
  8236. /**
  8237. * @author mikael emtinger / http://gomo.se/
  8238. *
  8239. */
  8240. THREE.ShaderFlares = {
  8241. 'lensFlareVertexTexture': {
  8242. vertexShader: [
  8243. "uniform vec3 screenPosition;",
  8244. "uniform vec2 scale;",
  8245. "uniform float rotation;",
  8246. "uniform int renderType;",
  8247. "uniform sampler2D occlusionMap;",
  8248. "attribute vec2 position;",
  8249. "attribute vec2 uv;",
  8250. "varying vec2 vUV;",
  8251. "varying float vVisibility;",
  8252. "void main() {",
  8253. "vUV = uv;",
  8254. "vec2 pos = position;",
  8255. "if( renderType == 2 ) {",
  8256. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  8257. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  8258. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  8259. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  8260. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  8261. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  8262. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  8263. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  8264. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  8265. "vVisibility = ( visibility.r / 9.0 ) *",
  8266. "( 1.0 - visibility.g / 9.0 ) *",
  8267. "( visibility.b / 9.0 ) *",
  8268. "( 1.0 - visibility.a / 9.0 );",
  8269. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  8270. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  8271. "}",
  8272. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  8273. "}"
  8274. ].join( "\n" ),
  8275. fragmentShader: [
  8276. "precision mediump float;",
  8277. "uniform sampler2D map;",
  8278. "uniform float opacity;",
  8279. "uniform int renderType;",
  8280. "uniform vec3 color;",
  8281. "varying vec2 vUV;",
  8282. "varying float vVisibility;",
  8283. "void main() {",
  8284. // pink square
  8285. "if( renderType == 0 ) {",
  8286. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  8287. // restore
  8288. "} else if( renderType == 1 ) {",
  8289. "gl_FragColor = texture2D( map, vUV );",
  8290. // flare
  8291. "} else {",
  8292. "vec4 texture = texture2D( map, vUV );",
  8293. "texture.a *= opacity * vVisibility;",
  8294. "gl_FragColor = texture;",
  8295. "gl_FragColor.rgb *= color;",
  8296. "}",
  8297. "}"
  8298. ].join( "\n" )
  8299. },
  8300. 'lensFlare': {
  8301. vertexShader: [
  8302. "uniform vec3 screenPosition;",
  8303. "uniform vec2 scale;",
  8304. "uniform float rotation;",
  8305. "uniform int renderType;",
  8306. "attribute vec2 position;",
  8307. "attribute vec2 uv;",
  8308. "varying vec2 vUV;",
  8309. "void main() {",
  8310. "vUV = uv;",
  8311. "vec2 pos = position;",
  8312. "if( renderType == 2 ) {",
  8313. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  8314. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  8315. "}",
  8316. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  8317. "}"
  8318. ].join( "\n" ),
  8319. fragmentShader: [
  8320. "precision mediump float;",
  8321. "uniform sampler2D map;",
  8322. "uniform sampler2D occlusionMap;",
  8323. "uniform float opacity;",
  8324. "uniform int renderType;",
  8325. "uniform vec3 color;",
  8326. "varying vec2 vUV;",
  8327. "void main() {",
  8328. // pink square
  8329. "if( renderType == 0 ) {",
  8330. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  8331. // restore
  8332. "} else if( renderType == 1 ) {",
  8333. "gl_FragColor = texture2D( map, vUV );",
  8334. // flare
  8335. "} else {",
  8336. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  8337. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  8338. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  8339. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  8340. "visibility = ( 1.0 - visibility / 4.0 );",
  8341. "vec4 texture = texture2D( map, vUV );",
  8342. "texture.a *= opacity * visibility;",
  8343. "gl_FragColor = texture;",
  8344. "gl_FragColor.rgb *= color;",
  8345. "}",
  8346. "}"
  8347. ].join( "\n" )
  8348. }
  8349. };
  8350. /**
  8351. * @author mikael emtinger / http://gomo.se/
  8352. *
  8353. */
  8354. THREE.ShaderSprite = {
  8355. 'sprite': {
  8356. vertexShader: [
  8357. "uniform int useScreenCoordinates;",
  8358. "uniform int affectedByDistance;",
  8359. "uniform vec3 screenPosition;",
  8360. "uniform mat4 modelViewMatrix;",
  8361. "uniform mat4 projectionMatrix;",
  8362. "uniform float rotation;",
  8363. "uniform vec2 scale;",
  8364. "uniform vec2 alignment;",
  8365. "uniform vec2 uvOffset;",
  8366. "uniform vec2 uvScale;",
  8367. "attribute vec2 position;",
  8368. "attribute vec2 uv;",
  8369. "varying vec2 vUV;",
  8370. "void main() {",
  8371. "vUV = uvOffset + uv * uvScale;",
  8372. "vec2 alignedPosition = position + alignment;",
  8373. "vec2 rotatedPosition;",
  8374. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  8375. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  8376. "vec4 finalPosition;",
  8377. "if( useScreenCoordinates != 0 ) {",
  8378. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  8379. "} else {",
  8380. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  8381. "finalPosition.xy += rotatedPosition * ( affectedByDistance == 1 ? 1.0 : finalPosition.z );",
  8382. "}",
  8383. "gl_Position = finalPosition;",
  8384. "}"
  8385. ].join( "\n" ),
  8386. fragmentShader: [
  8387. "precision mediump float;",
  8388. "uniform vec3 color;",
  8389. "uniform sampler2D map;",
  8390. "uniform float opacity;",
  8391. "varying vec2 vUV;",
  8392. "void main() {",
  8393. "vec4 texture = texture2D( map, vUV );",
  8394. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  8395. "}"
  8396. ].join( "\n" )
  8397. }
  8398. };